feat(ui): the workflow canvas watches a run live: each step shows its state, duration and error, and the view follows the step in progress

This commit is contained in:
sam committed 2026-10-05 00:34:06 +11:00
1 parent dfff9f6b11
commit 720cd7a6f0
7 files changed
+270 -81

No files matched your search

+40 -2
View File
@@ -1,16 +1,43 @@
<script setup lang="ts">
import { computed } from "vue";
import { Handle, Position } from "@vue-flow/core";
import { Flag, GitBranch, Play, Repeat, SkipForward } from "@lucide/vue";
import type { StepNodeData } from "./workflow-graph";
defineProps<{ data: StepNodeData }>();
const props = defineProps<{ data: StepNodeData }>();
const STATE_CLASSES: Record<string, string> = {
ok: "border-ok/70",
failed: "border-danger/80",
interrupted: "border-warn/70",
running: "border-info step-running",
};
const stateClass = computed(() => {
if (props.data.kind === "start") return "border-primary/60";
return STATE_CLASSES[props.data.run?.status ?? ""] ?? "border-border";
});
const STATE_LABELS: Record<string, string> = {
ok: "Done",
failed: "Failed",
interrupted: "Interrupted",
running: "Running",
};
function duration(ms?: number): string {
if (ms === undefined) return "";
if (ms < 1000) return `${ms} ms`;
const seconds = Math.round(ms / 1000);
return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
}
</script>
<template>
<div
class="w-60 rounded-lg border bg-card px-3 py-2 text-left shadow-sm"
:class="data.kind === 'start' ? 'border-primary/60' : 'border-border'"
:class="[stateClass, data.run ? '' : data.kind === 'step' && 'opacity-90']"
>
<Handle v-if="data.kind !== 'start'" type="target" :position="Position.Top" />
<Handle id="data-in" type="target" :position="Position.Right" class="!opacity-0" />
@@ -34,6 +61,17 @@ defineProps<{ data: StepNodeData }>();
<SkipForward class="size-3" aria-hidden="true" />continues
</span>
</div>
<div
v-if="data.run"
class="mt-1 flex items-center gap-1.5 text-[11px]"
:class="{ 'text-ok': data.run.status === 'ok', 'text-danger': data.run.status === 'failed', 'text-info': data.run.status === 'running', 'text-warn': data.run.status === 'interrupted' }"
:title="data.run.error || undefined"
>
<span class="size-1.5 rounded-full bg-current" aria-hidden="true" />
{{ STATE_LABELS[data.run.status] ?? data.run.status }}
<span v-if="data.run.duration_ms !== undefined" class="text-fg-subtle">{{ duration(data.run.duration_ms) }}</span>
<span v-if="data.run.error" class="truncate text-danger">{{ data.run.error }}</span>
</div>
<Handle type="source" :position="Position.Bottom" />
<Handle id="data-out" type="source" :position="Position.Right" class="!opacity-0" />
</div>
+29 -8
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import { computed, ref, watch } from "vue";
import { VueFlow, type VueFlowStore } from "@vue-flow/core";
import { Background } from "@vue-flow/background";
import { Controls } from "@vue-flow/controls";
@@ -7,14 +7,14 @@ import "@vue-flow/core/dist/style.css";
import "@vue-flow/controls/dist/style.css";
import StepNode from "./StepNode.vue";
import { workflowGraph } from "./workflow-graph";
import { withRuns, workflowGraph, type StageRun } from "./workflow-graph";
const props = defineProps<{ yaml: string }>();
const props = defineProps<{ yaml: string; stages?: StageRun[] }>();
const NODE_WIDTH = 240;
const container = ref<HTMLElement | null>(null);
const graph = computed(() => workflowGraph(props.yaml));
const graph = computed(() => withRuns(workflowGraph(props.yaml), props.stages ?? []));
const nodes = computed(() => graph.value.nodes);
const edges = computed(() =>
graph.value.edges.map(({ label, offset, ...edge }) => ({
@@ -27,18 +27,31 @@ const edges = computed(() =>
})),
);
// Start at the top at a readable size; a long workflow scrolls down rather
// than shrinking until nothing on it can be read.
function place(flow: VueFlowStore): void {
const ZOOM = 0.9;
let flow: VueFlowStore | undefined;
// Start at a readable size rather than shrinking a long workflow until
// nothing on it can be read, scrolled to the furthest step the watched run has
// reached so the step that is moving stays in view.
function place(store?: VueFlowStore): void {
const animate = !store;
flow = store ?? flow;
if (!flow) return;
const width = container.value?.clientWidth ?? 800;
void flow.setViewport({ x: width / 2 - NODE_WIDTH / 2, y: 24, zoom: 0.9 });
const height = container.value?.clientHeight ?? 560;
const reached = nodes.value.filter((node) => node.data.run).at(-1);
const y = reached ? Math.min(24, height / 3 - reached.position.y * ZOOM) : 24;
void flow.setViewport({ x: width / 2 - NODE_WIDTH / 2, y, zoom: ZOOM }, { duration: animate ? 300 : 0 });
}
watch(() => nodes.value.filter((node) => node.data.run).length, () => place());
</script>
<template>
<div ref="container" class="workflow-canvas h-[560px] overflow-hidden rounded-lg border border-border bg-background">
<VueFlow
:key="yaml"
class="h-full"
:nodes="nodes"
:edges="edges"
:nodes-draggable="false"
@@ -68,6 +81,14 @@ function place(flow: VueFlowStore): void {
stroke-dasharray: 5 4;
stroke-width: 1.25;
}
@keyframes step-running {
50% {
box-shadow: 0 0 0 4px color-mix(in oklab, var(--color-info) 30%, transparent);
}
}
.step-running {
animation: step-running 1.6s ease-in-out infinite;
}
.workflow-canvas .vue-flow__controls {
box-shadow: none;
}
+19 -2
View File
@@ -9,6 +9,7 @@ import { Spinner } from "@/components/ui/spinner";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import WorkflowCanvas from "./WorkflowCanvas.vue";
import { useWorkflowRuns } from "./workflow-runs";
import {
cloneControlPlaneValue,
removeWorkflowDefinition,
@@ -39,6 +40,8 @@ const id = ref("");
const yaml = ref("");
const localError = ref("");
const { runs, watched, stages, pick } = useWorkflowRuns(selected);
const shippedEntry = computed(() =>
shipped.value.definitions.find((entry) => entry.id === id.value),
);
@@ -139,8 +142,22 @@ function syncScroll(event: Event): void {
>{{ parsed.ok ? "✓" : "✕" }} {{ validationLabel(parsed) }}</span
>
</div>
<TabsContent value="canvas">
<WorkflowCanvas :yaml="yaml" />
<TabsContent value="canvas" class="space-y-2">
<label class="flex items-center gap-2 text-sm">
<span class="text-muted-foreground">Watching</span>
<select
:value="watched"
class="h-8 max-w-md min-w-60 rounded-md border border-input bg-background px-2 text-sm"
@change="pick(($event.target as HTMLSelectElement).value)"
>
<option value="">No run, definition only</option>
<option v-for="run in runs" :key="run.id" :value="String(run.id)">
#{{ run.id }} {{ run.title || "untitled" }}{{ run.status ? ` · ${run.status}` : "" }}
</option>
</select>
<span v-if="!runs.length" class="text-xs text-fg-subtle">This workflow has not run yet.</span>
</label>
<WorkflowCanvas :yaml="yaml" :stages="stages" />
</TabsContent>
<TabsContent value="yaml">
<!--
+46 -2
View File
@@ -17,6 +17,33 @@ export interface StepNodeData {
retry?: number;
continues?: boolean;
branch?: string;
/** The name the engine records this step's run under, and which run of
* that name it is: two unnamed repo.commit steps are commit 0 and 1. */
stage?: string;
occurrence?: number;
run?: StageRun;
}
/** One recorded run of a step, from the task's attempts view. */
export interface StageRun {
name: string;
status: "ok" | "failed" | "interrupted" | "running" | "unknown" | string;
duration_ms?: number;
error?: string;
}
/** Puts each recorded stage run on the node it belongs to. */
export function withRuns(graph: WorkflowGraph, stages: StageRun[]): WorkflowGraph {
const byName = new Map<string, StageRun[]>();
for (const stage of stages) byName.set(stage.name, [...(byName.get(stage.name) ?? []), stage]);
return {
edges: graph.edges,
nodes: graph.nodes.map((node) => {
const { stage, occurrence } = node.data;
const run = stage === undefined ? undefined : byName.get(stage)?.[occurrence ?? 0];
return run ? { ...node, data: { ...node.data, run } } : node;
}),
};
}
export interface GraphNode {
@@ -127,7 +154,20 @@ export function workflowGraph(source: string): WorkflowGraph {
let previous = [start];
let row = 1;
const addStep = (step: unknown, key: string, x: number, y: number, branch?: string): string => {
const seen = new Map<string, number>();
const occurrenceOf = (stage: string): number => {
const count = seen.get(stage) ?? 0;
seen.set(stage, count + 1);
return count;
};
const addStep = (
step: unknown,
key: string,
x: number,
y: number,
branch?: string,
recorded?: { stage: string; occurrence: number },
): string => {
const record = isMapping(step) ? step : {};
const type = typeof record.type === "string" ? record.type : "";
const settings = isMapping(record.settings) ? record.settings : {};
@@ -147,6 +187,7 @@ export function workflowGraph(source: string): WorkflowGraph {
retry: isMapping(record.retry) && typeof record.retry.attempts === "number" ? record.retry.attempts : undefined,
continues: record.on_failure === "continue",
branch,
...(recorded ?? { stage: stepID || type, occurrence: occurrenceOf(stepID || type) }),
},
});
if (stepID) byStepID.set(stepID, id);
@@ -160,13 +201,16 @@ export function workflowGraph(source: string): WorkflowGraph {
for (const [i, step] of steps.entries()) {
if (isMapping(step) && isMapping(step.parallel)) {
const branches = Object.entries(step.parallel);
// Branch steps run inside the parallel step, which is what gets recorded.
const parallelName = typeof step.id === "string" ? step.id : "parallel";
const recorded = { stage: parallelName, occurrence: occurrenceOf(parallelName) };
const ends: string[] = [];
let depth = 0;
branches.forEach(([name, branchSteps], column) => {
const x = (column - (branches.length - 1) / 2) * COLUMN;
let tail = previous;
(Array.isArray(branchSteps) ? branchSteps : []).forEach((branchStep, j) => {
const id = addStep(branchStep, `${i + 1}-${name}-${j + 1}`, x, (row + j) * ROW, name);
const id = addStep(branchStep, `${i + 1}-${name}-${j + 1}`, x, (row + j) * ROW, name, recorded);
link(tail, id);
tail = [id];
depth = Math.max(depth, j + 1);
+69
View File
@@ -0,0 +1,69 @@
import { ref, watch, type Ref } from "vue";
import { api } from "@/lib/api";
import { useLiveResource } from "@/stores/live-updates";
import type { StageRun } from "./workflow-graph";
export interface WorkflowRun {
id: number | string;
title?: string;
status?: string;
workflow?: string;
}
interface AttemptsView {
attempts?: { attempt: number; stages?: StageRun[] }[];
}
const RECENT_RUNS = 20;
/**
* The recent runs of one workflow and the step states of the one being
* watched, kept current from the live task stream. The newest run is watched
* until the operator picks another.
*/
export function useWorkflowRuns(workflow: Ref<string>) {
const runs = ref<WorkflowRun[]>([]);
const watched = ref("");
const stages = ref<StageRun[]>([]);
let picked = false;
async function loadRuns(): Promise<void> {
const tasks = (await api.tasks<WorkflowRun[]>().catch(() => [])) ?? [];
runs.value = tasks
.filter((task) => task.workflow === workflow.value)
.sort((a, b) => Number(b.id) - Number(a.id))
.slice(0, RECENT_RUNS);
if (!picked || !runs.value.some((run) => String(run.id) === watched.value))
watched.value = runs.value[0] ? String(runs.value[0].id) : "";
}
async function loadStages(): Promise<void> {
if (!watched.value) {
stages.value = [];
return;
}
const view = await api.taskAttempts<AttemptsView>(watched.value).catch(() => null);
const latest = [...(view?.attempts ?? [])].sort((a, b) => b.attempt - a.attempt)[0];
stages.value = latest?.stages ?? [];
}
function pick(id: string): void {
picked = id !== "";
watched.value = id;
}
async function refresh(): Promise<void> {
await loadRuns();
await loadStages();
}
watch(workflow, () => {
picked = false;
void refresh();
}, { immediate: true });
watch(watched, () => void loadStages());
useLiveResource("tasks", () => void refresh(), 300);
return { runs, watched, stages, pick };
}