Files
archie/ui/src/workflows/WorkflowsPage.vue
T

299 lines
13 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { Ellipsis, Plus, RotateCcw } from "@lucide/vue";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import PageHeader from "@/base/PageHeader.vue";
import { Button } from "@/components/ui/button";
import {
Empty,
EmptyHeader,
EmptyTitle,
} from "@/components/ui/empty";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { api } from "@/lib/api";
import { delivered } from "@/lib/delivered";
import { compact } from "@/lib/format";
import { cn } from "@/lib/utils";
import { statusKind, statusLabel } from "@/lib/task-meta";
import { cloneControlPlaneValue } from "@/stores/settings";
import { restoreShippedDefinitions, useWorkflowsStore } from "@/stores/workflows";
import { useLiveResource } from "@/stores/session";
import ApplyStatusRows from "@/settings/ApplyStatusRows.vue";
import SlowestStagesCard from "./SlowestStagesCard.vue";
import StageFailuresCard from "./StageFailuresCard.vue";
import type { StageStats } from "./stages";
import WorkflowEditor from "./WorkflowEditor.vue";
import { workflowRows, type WorkflowDefinition, type WorkflowStats } from "./workflow-rows";
interface WorkflowsResponse {
definitions?: WorkflowDefinition[];
workflows?: WorkflowStats[];
stages?: StageStats[];
}
interface RunTask {
id: number | string;
title?: string;
status?: string;
workflow?: string;
owner?: string;
repo?: string;
issue_number?: number;
}
const store = useWorkflowsStore();
const data = ref<WorkflowsResponse>({});
const runs = ref<RunTask[]>([]);
const error = ref<string | null>(null);
const loading = ref(true);
async function load() {
try {
const [workflows, tasks] = await Promise.all([api.workflows<WorkflowsResponse>(), api.tasks<RunTask[]>()]);
data.value = workflows ?? {};
runs.value = tasks ?? [];
error.value = null;
void loadWorkflowRuns();
} catch (err) {
error.value = String((err as Error).message || err);
} finally {
loading.value = false;
}
}
useLiveResource("tasks", () => void load(), 500);
onMounted(() => Promise.all([load(), store.load()]));
// Stored definitions are the source of truth for the list; statistics join
// them by id, and a workflow seen only in statistics still gets a row.
const stored = computed(() => store.collection.definitions);
const rows = computed(() =>
workflowRows(
data.value.workflows,
[...stored.value, ...store.drafts.filter((draft) => !stored.value.some((d) => d.id === draft.id))].map((d) => ({
id: d.id,
name: d.id,
origin: data.value.definitions?.find((x) => x.id === d.id)?.origin,
})),
),
);
// What each workflow is doing now, from the live task list: how many runs are
// working, and how the newest run ended up.
const live = computed(() => {
const byWorkflow = new Map<string, { running: number; last?: RunTask }>();
for (const run of runs.value) {
if (!run.workflow) continue;
const entry = byWorkflow.get(run.workflow) ?? { running: 0 };
if (run.status === "running") entry.running++;
if (!entry.last || Number(run.id) > Number(entry.last.id)) entry.last = run;
byWorkflow.set(run.workflow, entry);
}
return byWorkflow;
});
// ?workflow= names the selection, so Jump to can open a workflow directly. It
// applies once the workflow is listed: selecting it before the definitions load
// would open an empty editor.
const route = useRoute();
const selected = ref("");
let applied = "";
watch(
[() => route.query.workflow, rows],
([wanted]) => {
if (typeof wanted === "string" && wanted !== applied && rows.value.some((row) => row.id === wanted)) {
selected.value = applied = wanted;
} else if (!selected.value && rows.value.length) selected.value = rows.value[0]!.id;
},
{ immediate: true },
);
// Whether this workflow is still the one archie ships: "Edited" when it has
// been changed, "Custom" when archie ships nothing by that name.
const provenance = computed(() => {
const shippedYAML = store.shipped.definitions.find((d) => d.id === selected.value)?.yaml;
const storedYAML = stored.value.find((d) => d.id === selected.value)?.yaml;
if (storedYAML === undefined) return "";
if (shippedYAML === undefined) return "Custom";
return shippedYAML === storedYAML ? "" : "Edited";
});
// A workflow the server does not list yet (a new, unsaved one) has no
// enabled state to show.
const enabled = computed(() => data.value.definitions?.find((d) => d.id === selected.value)?.enabled);
async function setEnabled(value: boolean) {
try {
await api.workflowEnabled(selected.value, value);
await load();
} catch (err) {
error.value = String((err as Error).message || err);
}
}
const stages = computed(() => (data.value.stages ?? []).filter((s) => s.workflow === selected.value));
// The selected workflow's runs come from a workflow-filtered page: the global
// list above holds only the newest tasks of every workflow.
const workflowRuns = ref<RunTask[]>([]);
const runsLoading = ref(false);
const runsError = ref("");
let runsRequest = 0;
async function loadWorkflowRuns() {
const request = ++runsRequest;
const requested = selected.value;
runsLoading.value = true;
runsError.value = "";
workflowRuns.value = [];
try {
const page = requested ? await api.taskPage<RunTask>({ workflow: requested }) : null;
if (request === runsRequest) workflowRuns.value = page?.tasks ?? [];
} catch (err) {
if (request === runsRequest) runsError.value = String((err as Error).message || err);
} finally {
if (request === runsRequest) runsLoading.value = false;
}
}
watch(selected, () => void loadWorkflowRuns(), { immediate: true });
function create() {
let n = 1;
while (stored.value.some((d) => d.id === `workflow-${n}`)) n++;
selected.value = `workflow-${n}`;
}
const confirmRestore = ref(false);
async function restoreShipped() {
const shipped = store.shipped;
const restored = restoreShippedDefinitions({ definitions: stored.value }, shipped);
if (await store.save(cloneControlPlaneValue(restored)))
selected.value = shipped.definitions[0]?.id ?? "";
}
// The share of a workflow's runs whose work is finished: merged, or ended
// with nothing to merge (a no-change build, a no-code triage -- `completed`).
const rate = (deliveredRuns = 0, total = 0) => (total ? deliveredRuns / total : 0);
</script>
<template>
<div>
<PageHeader title="Workflows">
<DropdownMenu>
<DropdownMenuTrigger as-child>
<Button variant="ghost" size="icon-sm" aria-label="More"><Ellipsis /></Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem :disabled="!store.shipped.definitions.length" @select="confirmRestore = true">
<RotateCcw />Restore shipped workflows</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Button size="sm" @click="create"><Plus data-icon="inline-start" />New workflow</Button>
</PageHeader>
<AlertDialog v-model:open="confirmRestore">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Restore shipped workflows?</AlertDialogTitle>
<AlertDialogDescription>Every shipped workflow is reset to its default, discarding edits to it. Custom workflows are kept.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction @click="restoreShipped">Restore</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<div v-if="error || store.error" class="mb-4 text-sm text-danger" role="alert">
<p>{{ error || store.error }}</p>
<Button variant="outline" size="sm" @click="load(); store.load()">Retry</Button>
</div>
<p v-if="loading || (!store.state.resource && !store.error)" class="text-sm text-fg-muted" role="status">Loading workflows…</p>
<div class="grid items-start gap-6 lg:grid-cols-[24rem_minmax(0,1fr)]">
<ul class="flex gap-1 overflow-x-auto pb-2 lg:flex-col lg:gap-0.5 lg:overflow-visible lg:pb-0" aria-label="Workflows">
<li v-for="row in rows" :key="row.id" class="min-w-36 shrink-0 lg:min-w-0">
<button
type="button"
:aria-current="row.id === selected ? 'true' : undefined"
:class="cn('w-full rounded-md px-3 py-2.5 text-left transition-colors hover:bg-secondary', row.id === selected && 'bg-secondary')"
@click="selected = row.id"
>
<span class="flex items-baseline gap-2">
<span class="min-w-0 flex-1 truncate font-mono text-[13px]" :class="row.id === selected && 'font-medium'">{{ row.id }}</span>
<Badge v-if="store.drafts.some((draft) => draft.id === row.id)" variant="outline">Draft</Badge>
<span class="font-mono text-xs text-fg-subtle">{{ row.avg_tokens ? compact(row.avg_tokens) : "–" }}</span>
</span>
<span v-if="row.runs" class="mt-1.5 flex items-center gap-2 text-xs text-fg-subtle">
<span v-if="live.get(row.id)?.running" class="flex w-20 shrink-0 items-center gap-1.5 text-info">
<span class="size-1.5 animate-pulse rounded-full bg-current" aria-hidden="true" />{{ live.get(row.id)?.running }} running
</span>
<span v-else-if="live.get(row.id)?.last" class="w-20 shrink-0 truncate" :title="`Latest run: ${statusLabel(live.get(row.id)?.last?.status ?? '')}`">{{ statusLabel(live.get(row.id)?.last?.status ?? "") }}</span>
<span v-else class="w-20 shrink-0">{{ row.runs }} runs</span>
<span class="h-1 flex-1 overflow-hidden rounded-full bg-secondary">
<span class="block h-full rounded-full bg-primary" :style="{ width: `${rate(delivered(row), row.runs) * 100}%` }" />
</span>
<span class="w-16 shrink-0 text-right font-mono">{{ delivered(row) }} of {{ row.runs }}</span>
</span>
</button>
</li>
</ul>
<section v-if="!selected && !loading && store.state.resource && !error" class="min-w-0 rounded-lg border border-border bg-card" aria-label="Workflow">
<Empty>
<EmptyHeader>
<EmptyTitle>No workflows</EmptyTitle>
</EmptyHeader>
</Empty>
</section>
<section v-else-if="selected && store.state.resource" class="min-w-0 rounded-lg border border-border bg-card px-3 py-4 sm:px-5" aria-label="Workflow">
<header class="mb-2 flex flex-wrap items-center gap-2">
<h2 class="font-mono text-[15px] font-medium">{{ selected }}</h2>
<Badge v-if="provenance" variant="outline">{{ provenance }}</Badge>
<div class="ml-auto flex items-center gap-3">
<ApplyStatusRows kind="workflow-definitions" compact />
<label v-if="enabled !== undefined" class="flex items-center gap-2 text-xs text-fg-muted">Enabled
<Switch :model-value="enabled" aria-label="Workflow enabled" @update:model-value="setEnabled" />
</label>
</div>
</header>
<WorkflowEditor v-model:selected="selected" :runs-count="workflowRuns.length">
<template #performance>
<Empty v-if="!stages.length">
<EmptyHeader>
<EmptyTitle>No stage timings yet</EmptyTitle>
</EmptyHeader>
</Empty>
<template v-else>
<SlowestStagesCard :stages="stages" />
<StageFailuresCard :stages="stages" />
</template>
</template>
<template #runs>
<p v-if="runsLoading" role="status" class="text-sm text-fg-muted">Loading runs…</p>
<div v-else-if="runsError" role="alert" class="text-sm text-danger">
<p>{{ runsError }}</p>
<Button variant="outline" size="sm" @click="loadWorkflowRuns">Retry</Button>
</div>
<Empty v-else-if="!workflowRuns.length">
<EmptyHeader>
<EmptyTitle>No runs yet</EmptyTitle>
</EmptyHeader>
</Empty>
<ul v-else class="divide-y divide-border">
<li v-for="t in workflowRuns" :key="t.id" class="flex items-center gap-3 py-2 text-sm">
<RouterLink :to="`/tasks/${t.id}`" class="min-w-0 flex-1 truncate hover:underline">{{ t.title || `Task ${t.id}` }}</RouterLink>
<span class="font-mono text-xs text-fg-subtle">{{ t.owner && t.repo ? `${t.owner}/${t.repo} #${t.issue_number}` : "" }}</span>
<Badge :variant="statusKind(t.status ?? '')">{{ statusLabel(t.status ?? "") }}</Badge>
</li>
</ul>
</template>
</WorkflowEditor>
</section>
</div>
</div>
</template>