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

272 lines
12 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 { Plus } from "@lucide/vue";
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 { Card } from "@/components/ui/card";
import { Section } from "@/components/ui/section";
import { StatusDot } from "@/components/ui/status-dot";
import { Table, TableBody, TableCell, TableRow } from "@/components/ui/table";
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 { 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 WorkflowPicker from "./WorkflowPicker.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;
issue_url?: string;
}
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, selected],
([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}`;
}
// 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 class="max-md:flex max-md:min-h-0 max-md:flex-1 max-md:flex-col">
<PageHeader title="Workflows" class="shrink-0">
<Button size="icon-sm" variant="ghost" aria-label="New workflow" title="New workflow" @click="create"><Plus /></Button>
</PageHeader>
<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)] max-md:min-h-0 max-md:flex-1 max-md:grid-rows-[minmax(0,1fr)]">
<div class="hidden min-w-0 flex-col gap-1 lg:flex">
<ul class="hidden max-h-[calc(100dvh-10rem)] flex-col gap-0.5 overflow-y-auto lg:flex" aria-label="Workflows">
<li v-for="row in rows" :key="row.id" class="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 text-label" :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 v-if="row.avg_tokens" class="font-mono text-xs text-fg-subtle" :title="`${row.avg_tokens.toLocaleString()} tokens per run on average`">{{ compact(row.avg_tokens) }} tok</span>
</span>
<span 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">
<StatusDot tone="info" live />{{ 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">–</span>
<span v-if="row.runs" class="h-1 flex-1 overflow-hidden rounded-full bg-border" role="img" :aria-label="`${delivered(row)} of ${row.runs ?? 0} runs delivered`" :title="`${delivered(row)} of ${row.runs ?? 0} runs delivered`">
<span class="block h-full rounded-full bg-primary" :style="{ width: `${rate(delivered(row), row.runs) * 100}%` }" />
</span>
<span v-if="row.runs" class="w-16 shrink-0 text-right font-mono" aria-hidden="true">{{ delivered(row) }}/{{ row.runs }}</span>
</span>
</button>
</li>
</ul>
</div>
<Section v-if="!selected && !loading && store.state.resource && !error" class="mb-0 min-w-0" role="region" aria-label="Workflow">
<Empty>
<EmptyHeader>
<EmptyTitle>No workflows</EmptyTitle>
</EmptyHeader>
</Empty>
</Section>
<Card v-else-if="selected && store.state.resource" class="min-w-0 px-3 sm:px-5 max-md:flex max-md:h-full max-md:min-h-0 max-md:flex-col" role="region" aria-label="Workflow">
<!-- Below lg the list is gone: this picks the workflow instead. -->
<header class="mb-2 flex shrink-0 items-center gap-2 lg:hidden">
<div class="min-w-0 flex-1"><WorkflowPicker class="w-full" :value="selected" :workflows="rows" label="Workflow" @pick="selected = $event" /></div>
<Badge v-if="provenance" variant="outline" class="shrink-0">{{ provenance }}</Badge>
<ApplyStatusRows kind="workflow-definitions" compact />
</header>
<WorkflowEditor v-model:selected="selected" :runs-count="workflowRuns.length">
<template #title>
<h2 class="min-w-0 truncate text-title font-medium">{{ selected }}</h2>
<Badge v-if="provenance" variant="outline" class="shrink-0">{{ provenance }}</Badge>
<ApplyStatusRows kind="workflow-definitions" compact />
</template>
<template v-if="enabled !== undefined" #toolbar>
<Switch :model-value="enabled" :title="enabled ? 'Published version runs on events' : 'Published version ignores events'" aria-label="Published version enabled" @update:model-value="setEnabled" />
</template>
<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>
<Table v-else aria-label="Runs">
<TableBody>
<TableRow v-for="t in workflowRuns" :key="t.id">
<TableCell class="w-full max-w-0 truncate"><RouterLink :to="`/tasks/${t.id}`" class="hover:underline">{{ t.title || `Task ${t.id}` }}</RouterLink></TableCell>
<TableCell class="hidden font-mono text-xs text-fg-subtle sm:table-cell">{{ t.owner && t.repo ? `${t.owner}/${t.repo}${t.issue_url && t.issue_number ? ` #${t.issue_number}` : ""}` : "" }}</TableCell>
<TableCell class="text-right"><Badge :variant="statusKind(t.status ?? '')">{{ statusLabel(t.status ?? "") }}</Badge></TableCell>
</TableRow>
</TableBody>
</Table>
</template>
</WorkflowEditor>
</Card>
</div>
</div>
</template>