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

461 lines
21 KiB
Vue

<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { computed, nextTick, ref, watch } from "vue";
import { Handle, Position, VueFlow, type NodeMouseEvent, type VueFlowStore } from "@vue-flow/core";
import { Background } from "@vue-flow/background";
import { useWorkflowsStore } from "@/stores/workflows";
import { useMediaQuery, usePreferredReducedMotion, useResizeObserver, useTransition } from "@vueuse/core";
import { ArrowDown, ArrowUp, Copy, GitBranch, Maximize, Minus, Pencil, Plus, RotateCcw, Split, Trash2 } from "@lucide/vue";
import "@vue-flow/core/dist/style.css";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import AddStepMenu from "./AddStepMenu.vue";
import InsertEdge from "./InsertEdge.vue";
import StepNode, { type StepCardData } from "./StepNode.vue";
import StepTypeItems from "./StepTypeItems.vue";
import { inParallel, type StepPath } from "./workflow-edit";
import { restartAt, stepTitle, withRuns, workflowGraph, type GraphNode, type StageRun, type StepNodeData } from "./workflow-graph";
import type { WorkflowTrigger } from "./workflow-triggers";
const props = defineProps<{
yaml: string;
stages?: StageRun[];
/** The card open in place: "workflow", "start", or a step's path as JSON. */
open?: string | null;
triggers?: WorkflowTrigger[];
/** Step type names; when given, the canvas offers editing. */
types?: string[];
readonly?: boolean;
/** The watched run is parked, so its steps offer to restart it. */
restartable?: boolean;
/** Steps that differ from the definition being compared, by node id. */
marks?: Record<string, "added" | "removed" | "changed">;
/** What is wrong with each step, by its path as JSON. */
problems?: Record<string, string>;
/** The workflow card's title and one-line summary. */
title?: string;
summary?: string;
}>();
const emit = defineEmits<{
toggle: [key: string];
insert: [after: StepPath, type: string];
duplicate: [StepPath];
move: [StepPath, -1 | 1];
remove: [StepPath];
rename: [StepPath, string];
restart: [from: string];
}>();
const NODE_WIDTH = 240;
const OPEN_WIDTH = 416;
const TOP = -140;
const editable = computed(() => !!props.types?.length && !props.readonly);
const types = computed(() => [...(props.types ?? []), "parallel", "switch"]);
const branchTypes = computed(() => types.value.filter((type) => ["agent.run", "workflow.call"].includes(type)));
const typesAt = (path?: StepPath) => (path && inParallel(path) ? branchTypes.value : types.value);
const keyOf = (data: StepNodeData) => (data.kind === "step" ? JSON.stringify(data.path ?? null) : data.kind);
const container = ref<HTMLElement | null>(null);
const viewport = ref<HTMLElement | null>(null);
const phone = useMediaQuery("(max-width: 767px)");
const workflows = useWorkflowsStore();
const graph = computed(() => {
const laid = withRuns(workflowGraph(props.yaml, workflows.stepTypes), props.stages ?? []);
if (!props.types?.length) return laid;
// Workflow-wide settings sit on a card above the trigger.
const workflow: GraphNode = { id: "workflow", type: "step", position: { x: 0, y: TOP }, data: { kind: "workflow", key: "workflow", title: "Settings", type: "", detail: props.summary ?? "" } };
return { nodes: [workflow, ...laid.nodes], edges: [{ id: "flow-workflow-start", source: "workflow", target: "start", kind: "flow" as const }, ...laid.edges] };
});
const stepCount = computed(() => graph.value.nodes.filter((node) => node.data.path?.length === 2).length);
// Rows are laid out for cards BASE tall. A taller card pushes everything below
// it down by the difference, measured rather than guessed, and an open card
// grows where it sits while the cards below slide down with it.
const BASE = 72;
const heights = ref<Record<string, number>>({});
const closedHeights = ref<Record<string, number>>({});
const anchor = computed(() => graph.value.nodes.find((node) => node.type === "step" && keyOf(node.data) === props.open));
function resized(id: string, height: number): void {
heights.value = { ...heights.value, [id]: height };
if (anchor.value?.id !== id) closedHeights.value = { ...closedHeights.value, [id]: height };
}
const growth = computed(() => {
const id = phone.value ? undefined : anchor.value?.id;
return id && heights.value[id] ? Math.max(0, heights.value[id] - (closedHeights.value[id] ?? heights.value[id])) : 0;
});
const motion = usePreferredReducedMotion();
const shift = useTransition(growth, { duration: computed(() => (motion.value === "reduce" ? 0 : 200)) });
const rows = computed(() => {
const excess = new Map<number, number>();
for (const node of graph.value.nodes) {
if (node.type !== "step") continue;
const height = (node.id === anchor.value?.id ? closedHeights.value[node.id] : undefined) ?? heights.value[node.id];
if (height !== undefined) excess.set(node.position.y, Math.max(excess.get(node.position.y) ?? -BASE, height - BASE));
}
return [...excess];
});
const pushed = (y: number) => rows.value.reduce((sum, [row, excess]) => (row < y ? sum + excess : sum), 0);
function card(node: GraphNode): GraphNode {
const data = node.data;
const key = keyOf(data);
const path = data.path;
const extra: Partial<StepCardData> = {
triggers: data.kind === "start" ? (props.triggers ?? []) : data.triggers,
expanded: !phone.value && key === props.open,
editable: editable.value,
problem: path ? props.problems?.[key] : undefined,
onResize: (height: number) => resized(node.id, height),
};
if (props.types?.length) extra.onToggle = () => emit("toggle", key);
if (editable.value) {
if (path) {
extra.onRename = (name: string) => emit("rename", path, name);
extra.onRemove = () => emit("remove", path);
extra.onMenu = (event: MouseEvent) => openMenu(event, data);
extra.renameRequested = renaming.value === key;
extra.onRenameDone = () => (renaming.value = null);
}
}
return { ...node, data: { ...data, ...extra } };
}
// An open card widens about its centre, and every column to either side moves
// out by half the growth so no neighbour sits under it.
const WIDEN = OPEN_WIDTH - NODE_WIDTH;
const holdsOpen = (node: GraphNode) => {
const open = anchor.value;
if (phone.value || !open || !node.style?.width) return false;
return node.position.x <= open.position.x && node.position.x + parseFloat(String(node.style.width)) >= open.position.x + NODE_WIDTH;
};
function spread(node: GraphNode): number {
const open = anchor.value;
if (phone.value || !open) return 0;
if (node.id === open.id || holdsOpen(node)) return -WIDEN / 2;
const centre = open.position.x + NODE_WIDTH / 2;
const width = node.style?.width ? parseFloat(String(node.style.width)) : node.type === "step" ? NODE_WIDTH : 32;
const mid = node.position.x + width / 2;
// The open card's own column stays put; insertion glyphs sit near its centre.
if (Math.abs(mid - centre) < NODE_WIDTH / 2) return 0;
return mid < centre ? -WIDEN / 2 : WIDEN / 2;
}
const nodes = computed(() => {
const open = anchor.value;
return graph.value.nodes.map((node) => {
const original = node;
if (node.type === "add")
node = { ...node, data: { ...node.data, types: typesAt(node.data.insertAfter), editable: editable.value, onInsert: (type: string) => emit("insert", node.data.insertAfter!, type) } as StepNodeData };
else if (node.type === "step") node = card(node);
const mark = props.marks?.[node.id];
if (mark) node = { ...node, data: { ...node.data, mark } };
const x = node.position.x + spread(node);
const opened = (at: number) => (open && at > open.position.y ? shift.value : 0);
const y = node.position.y + pushed(node.position.y) + opened(node.position.y);
if (original === open) return { ...node, position: { x, y }, zIndex: 10 };
// A lane grows with the cards inside it.
if (node.type === "lane" && node.style) {
const top = node.position.y;
const bottom = top + parseFloat(node.style.height);
const height = bottom + pushed(bottom) + opened(bottom) - y;
const width = parseFloat(String(node.style.width)) + (holdsOpen(node) ? WIDEN : 0);
return { ...node, position: { x, y }, style: { ...node.style, width: `${width}px`, height: `${height}px` } };
}
return { ...node, position: { x, y } };
});
});
// The run's trace: an edge lights once the run has reached its target, in the
// colour of how that step went, and moves while the step is running.
const runs = computed(() => new Map(graph.value.nodes.map((node) => [node.id, node.data.run?.status])));
// Data edges bundle into noise, so only the hovered or open step's show.
const hovered = ref<string | null>(null);
const focusId = computed(() => hovered.value ?? anchor.value?.id);
const edges = computed(() =>
graph.value.edges
.filter((edge) => edge.kind === "flow" || edge.source === focusId.value || edge.target === focusId.value)
.map(({ label, offset, insertAfter, otherwise, ...edge }) =>
edge.kind === "flow"
? {
...edge,
type: "insert",
...(otherwise ? { sourceHandle: "otherwise" } : {}),
data: { trace: runs.value.get(edge.target), insertAfter, types: typesAt(insertAfter), editable: editable.value, onInsert: (after: StepPath, type: string) => emit("insert", after, type) },
}
: {
...edge,
type: "smoothstep",
pathOptions: { offset: offset ?? 20, borderRadius: 8 },
class: "workflow-data-edge",
// Vue Flow draws edge.label; it never reads data.label.
label,
labelBgPadding: [4, 2] as [number, number],
labelBgBorderRadius: 4,
},
),
);
const ZOOM = 0.9;
// Clearance from the canvas edges for the graph, so a fitted graph does not
// touch them.
const PAD = 20;
let flow: VueFlowStore | undefined;
const top = computed(() => (props.types?.length ? TOP : 0));
// The graph's horizontal extent, in canvas units: a lane is wider than the card
// it holds, and a card opened in place is wider still.
function extent(): { left: number; width: number } {
let left = Infinity;
let right = -Infinity;
for (const node of nodes.value) {
// An insertion point is a glyph, not a card, and it sits inside the extent
// of the cards around it.
if (node.type !== "step" && node.type !== "lane") continue;
const width = node.style?.width ? parseFloat(String(node.style.width)) : !phone.value && node.id === anchor.value?.id ? OPEN_WIDTH : NODE_WIDTH;
left = Math.min(left, node.position.x);
right = Math.max(right, node.position.x + width);
}
return Number.isFinite(left) ? { left, width: right - left } : { left: 0, width: NODE_WIDTH };
}
// The scale and left offset that place the graph's whole extent inside the
// canvas with clearance at both edges, at no more than the readable size.
function framing(width: number): { x: number; zoom: number } {
const { left, width: span } = extent();
const zoom = Math.max(0.01, Math.min(ZOOM, (width - PAD * 2) / span));
return { x: width / 2 - (left + span / 2) * zoom, zoom };
}
// Start at a readable size rather than shrinking a long workflow until
// nothing on it can be read, with the top of the graph at the top.
function place(store?: VueFlowStore): void {
flow = store ?? flow;
if (!flow) return;
const width = viewport.value?.clientWidth;
if (!width) return;
const { x, zoom } = framing(width);
void flow.setViewport({ x, y: 24 - top.value * zoom, zoom });
}
useResizeObserver(viewport, () => place());
watch([() => props.title, () => graph.value.nodes.map((node) => `${node.id}:${node.position.x}:${node.position.y}`).join(",")], async () => {
await nextTick();
place();
});
// A card opened low on the canvas scrolls up so its form is in view, and one
// opened wider than the canvas allows is framed so its edges stay reachable.
watch(anchor, async (node) => {
await nextTick();
// A hidden canvas has no size to animate across; it is placed when shown.
const width = viewport.value?.clientWidth;
if (phone.value || !node || !flow || !width) return;
const { y } = flow.getViewport();
const height = viewport.value?.clientHeight ?? 560;
const { x, zoom } = framing(width);
const screenTop = (node.position.y + pushed(node.position.y)) * zoom + y;
const away = screenTop < 8 || screenTop > height / 2;
void flow.setViewport({ x, y: away ? y - screenTop + 24 : y, zoom }, { duration: 250 });
});
// The right-click menu opens at the pointer, for the step under it or for the
// canvas itself.
// Each opening is a fresh menu (seq keys it): a right-click elsewhere while
// one is closing would otherwise reopen it at the old anchor.
const menu = ref<{ open: boolean; x: number; y: number; step?: StepNodeData; seq: number }>({ open: false, x: 0, y: 0, seq: 0 });
function openMenu(event: MouseEvent, step?: StepNodeData): void {
if (!editable.value) return;
event.preventDefault();
const box = container.value?.getBoundingClientRect();
// A keyboard press has no pointer position: the menu opens under the button.
let { clientX: x, clientY: y } = event;
if (!x && !y && event.currentTarget instanceof HTMLElement) {
const button = event.currentTarget.getBoundingClientRect();
x = button.left;
y = button.bottom;
}
menu.value = { open: true, x: x - (box?.left ?? 0), y: y - (box?.top ?? 0), step, seq: menu.value.seq + 1 };
}
// The step the menu's Rename asked to rename; its card shows the name field.
const renaming = ref<string | null>(null);
function onNodeMenu({ event, node }: NodeMouseEvent): void {
if (node.type !== "step" || (node.data as StepNodeData).kind === "workflow") return;
openMenu(event as MouseEvent, node.data as StepNodeData);
}
const menuPath = computed(() => menu.value.step?.path);
const restart = computed(() => (props.restartable && menuPath.value ? restartAt(graph.value, menuPath.value) : null));
const menuIndex = computed(() => Number(menuPath.value?.at(-1)));
const beforePath = computed(() => menuPath.value ? [...menuPath.value.slice(0, -1), menuIndex.value - 1] : []);
</script>
<template>
<div ref="container" class="workflow-canvas relative flex h-full min-h-0 flex-col overflow-hidden rounded-lg border border-border bg-background">
<div ref="viewport" class="min-h-0 flex-1">
<VueFlow
class="h-full"
:nodes="nodes"
:edges="edges"
:nodes-draggable="false"
:nodes-connectable="false"
:elements-selectable="false"
:min-zoom="0.01"
:max-zoom="1.5"
pan-on-scroll
@pane-ready="place"
@node-mouse-enter="hovered = $event.node.id"
@node-mouse-leave="hovered = null"
@node-context-menu="onNodeMenu"
@pane-context-menu="openMenu($event as MouseEvent)"
>
<template #node-step="nodeProps">
<StepNode v-bind="nodeProps"><slot name="body" :data="nodeProps.data" /></StepNode>
</template>
<!-- A branch's dashed lane, labelled with its name or case. -->
<template #node-lane="{ data }">
<div class="pointer-events-none size-full rounded-xl border border-dashed border-border bg-muted/30">
<div class="flex items-center gap-1 px-2.5 pt-1.5 text-caption text-fg-subtle">
<template v-if="data.lane === 'switch'">
<Split class="size-3" aria-hidden="true" />
<span v-if="data.title === 'default'">otherwise</span>
<span v-else class="font-mono">= {{ data.title }}</span>
</template>
<template v-else>
<GitBranch class="size-3" aria-hidden="true" />{{ data.title }}
</template>
</div>
</div>
</template>
<!-- The end of a lane or of the workflow: where a step is appended. -->
<template #node-add="{ data }">
<div class="relative flex w-8 justify-center">
<Handle type="target" :position="Position.Top" class="!opacity-0" />
<AddStepMenu v-if="data.editable && data.insertAfter" :types="data.types" :label="data.branch ? `Add a step to ${data.branch}` : 'Add a step at the end'" @pick="data.onInsert" />
<Handle v-if="data.lane" type="source" :position="Position.Bottom" class="!opacity-0" />
<span v-if="!(data.editable && data.insertAfter)" class="size-2 rounded-full bg-border" aria-hidden="true" />
</div>
</template>
<template #edge-insert="edgeProps">
<InsertEdge v-bind="edgeProps" />
</template>
<Background :gap="20" />
</VueFlow>
</div>
<div role="group" aria-label="Zoom" class="absolute top-2 right-2 z-10 flex flex-col gap-0.5 rounded-md border border-border bg-card p-0.5 shadow-[var(--shadow-sm)]">
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon-sm" aria-label="Zoom in" @click="flow?.zoomIn()"><Plus /></Button>
</TooltipTrigger>
<TooltipContent side="left">Zoom in</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon-sm" aria-label="Zoom out" @click="flow?.zoomOut()"><Minus /></Button>
</TooltipTrigger>
<TooltipContent side="left">Zoom out</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon-sm" aria-label="Fit view" @click="place()"><Maximize /></Button>
</TooltipTrigger>
<TooltipContent side="left">Fit view</TooltipContent>
</Tooltip>
</div>
<Dialog :open="phone && !!anchor" @update:open="!$event && anchor && emit('toggle', keyOf(anchor.data))">
<DialogContent v-if="anchor" class="max-h-[calc(100dvh-2rem)] overflow-y-auto" :aria-describedby="undefined">
<DialogHeader><DialogTitle class="pr-8">{{ anchor.data.title }}</DialogTitle></DialogHeader>
<slot name="body" :data="anchor.data" />
</DialogContent>
</Dialog>
<DropdownMenu :key="menu.seq" v-model:open="menu.open" :modal="false">
<DropdownMenuTrigger as-child>
<span class="pointer-events-none absolute size-0" :style="{ left: `${menu.x}px`, top: `${menu.y}px` }" />
</DropdownMenuTrigger>
<DropdownMenuContent class="w-56" align="start">
<template v-if="menu.step?.kind === 'step' && menuPath">
<DropdownMenuLabel class="truncate">{{ menu.step.title || stepTitle(menu.step.type, workflows.stepTypes) }}</DropdownMenuLabel>
<template v-if="restart">
<DropdownMenuItem :disabled="restart.blocked" @select="emit('restart', restart.from)"><RotateCcw />{{ restart.label }}</DropdownMenuItem>
<DropdownMenuSeparator />
</template>
<DropdownMenuItem @select="emit('toggle', JSON.stringify(menuPath))"><Pencil />Edit</DropdownMenuItem>
<DropdownMenuItem @select="renaming = JSON.stringify(menuPath)"><Pencil />Rename</DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger>Insert before</DropdownMenuSubTrigger>
<DropdownMenuSubContent class="w-52"><StepTypeItems :types="typesAt(menuPath)" @pick="emit('insert', beforePath, $event)" /></DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSub>
<DropdownMenuSubTrigger>Insert after</DropdownMenuSubTrigger>
<DropdownMenuSubContent class="w-52"><StepTypeItems :types="typesAt(menuPath)" @pick="emit('insert', menuPath, $event)" /></DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuItem v-if="!['parallel', 'switch'].includes(menu.step.type)" @select="emit('duplicate', menuPath)"><Copy />Duplicate</DropdownMenuItem>
<DropdownMenuItem @select="emit('move', menuPath, -1)"><ArrowUp />Move up</DropdownMenuItem>
<DropdownMenuItem @select="emit('move', menuPath, 1)"><ArrowDown />Move down</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" @select="emit('remove', menuPath)"><Trash2 />Delete</DropdownMenuItem>
</template>
<template v-else>
<DropdownMenuLabel>{{ menu.step?.kind === "start" ? "Add the first step" : "Add a step at the end" }}</DropdownMenuLabel>
<StepTypeItems :types="types" @pick="emit('insert', ['steps', menu.step?.kind === 'start' ? -1 : stepCount - 1], $event)" />
</template>
</DropdownMenuContent>
</DropdownMenu>
</div>
</template>
<style>
.workflow-flow-edge path {
stroke: var(--color-muted-foreground);
stroke-width: 1.5;
}
.workflow-flow-edge.trace-ok path {
stroke: var(--color-ok);
}
.workflow-flow-edge.trace-failed path {
stroke: var(--color-danger);
}
.workflow-flow-edge.trace-interrupted path {
stroke: var(--color-warn);
}
.workflow-flow-edge.trace-running path {
stroke: var(--color-info);
stroke-dasharray: 6 4;
animation: edge-trace 0.8s linear infinite;
}
@keyframes edge-trace {
to {
stroke-dashoffset: -10;
}
}
@media (prefers-reduced-motion: reduce) {
.workflow-flow-edge.trace-running path,
.step-running {
animation: none;
}
}
.workflow-data-edge path {
stroke: var(--color-primary);
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;
}
</style>