feat(ui): lanes for parallel and switch steps on the workflow canvas
This commit is contained in:
1 parent
79d7f2fa68
commit
522ced45ff
14 files changed
+264
-138
No files matched your search
@@ -9,7 +9,6 @@ defineProps<{ data: { branch?: string; types: string[]; editable: boolean; onIns
|
||||
<template>
|
||||
<div class="relative flex w-8 justify-center">
|
||||
<Handle type="target" :position="Position.Top" class="!opacity-0" />
|
||||
<span v-if="data.branch" class="absolute bottom-full mb-1 whitespace-nowrap text-xs text-fg-subtle">{{ data.branch }}</span>
|
||||
<AddStepMenu v-if="data.editable" :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.branch" type="source" :position="Position.Bottom" class="!opacity-0" />
|
||||
<span v-else class="size-2 rounded-full bg-border" aria-hidden="true" />
|
||||
|
||||
@@ -5,7 +5,7 @@ import { BaseEdge, EdgeLabelRenderer, getSmoothStepPath, type EdgeProps } from "
|
||||
import AddStepMenu from "./AddStepMenu.vue";
|
||||
import type { StepPath } from "./workflow-edit";
|
||||
|
||||
const props = defineProps<EdgeProps<{ trace?: string; insertAfter?: StepPath; types: string[]; editable: boolean; onInsert: (after: StepPath, type: string) => void }>>();
|
||||
const props = defineProps<EdgeProps<{ trace?: string; otherwise?: boolean; insertAfter?: StepPath; types: string[]; editable: boolean; onInsert: (after: StepPath, type: string) => void }>>();
|
||||
|
||||
const path = computed(() =>
|
||||
getSmoothStepPath({
|
||||
@@ -22,6 +22,9 @@ const path = computed(() =>
|
||||
|
||||
<template>
|
||||
<BaseEdge :id="id" :path="path[0]" :class="['workflow-flow-edge', data?.trace && `trace-${data.trace}`]" />
|
||||
<EdgeLabelRenderer v-if="data?.otherwise">
|
||||
<div class="absolute text-[11px] text-fg-subtle" :style="{ transform: `translate(8px, -50%) translate(${sourceX}px, ${sourceY}px)` }">otherwise</div>
|
||||
</EdgeLabelRenderer>
|
||||
<EdgeLabelRenderer v-if="data?.editable && data.insertAfter !== undefined">
|
||||
<div
|
||||
class="workflow-insert absolute"
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import { GitBranch, Split } from "@lucide/vue";
|
||||
|
||||
import type { StepNodeData } from "./workflow-graph";
|
||||
|
||||
defineProps<{ data: StepNodeData }>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<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-[11px] 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>
|
||||
@@ -9,7 +9,7 @@ import { Input } from "@/components/ui/input";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { stepIcon } from "./step-icons";
|
||||
import { addBranch, deleteBranch, renameBranch, earlierStepIDs, replaceStep, stepAt, workflowField, type StepPath, type StepRecord } from "./workflow-edit";
|
||||
import { addBranch, branchingOf, deleteBranch, renameBranch, earlierStepIDs, replaceStep, stepAt, workflowField, type StepPath, type StepRecord } from "./workflow-edit";
|
||||
import type { WorkflowDefinitionEntry } from "@/stores/control-plane";
|
||||
import type { InputSpec } from "./bind-event";
|
||||
import { inputValue } from "./work-request";
|
||||
@@ -21,8 +21,13 @@ const props = defineProps<{ yaml: string; path: StepPath; vocabulary: StepTypeIn
|
||||
const emit = defineEmits<{ "update:yaml": [string]; close: []; remove: [] }>();
|
||||
|
||||
const step = computed<StepRecord>(() => stepAt(props.yaml, props.path) ?? {});
|
||||
const type = computed(() => step.value.parallel ? "parallel" : typeof step.value.type === "string" ? step.value.type : "");
|
||||
const branches = computed(() => Object.keys((step.value.parallel ?? {}) as Record<string, unknown>));
|
||||
const branching = computed(() => branchingOf(step.value));
|
||||
const type = computed(() => branching.value?.kind ?? (typeof step.value.type === "string" ? step.value.type : ""));
|
||||
const branches = computed(() => branching.value?.branches.map(([name]) => name) ?? []);
|
||||
const minBranches = computed(() => (type.value === "parallel" ? 2 : 1));
|
||||
function setOn(on: string): void {
|
||||
emit("update:yaml", replaceStep(props.yaml, props.path, { ...step.value, switch: { ...(step.value.switch as StepRecord), on } }));
|
||||
}
|
||||
const newBranch = ref("");
|
||||
const branchError = ref("");
|
||||
function changeBranch(action: "add" | "rename" | "delete", name: string, next = ""): void {
|
||||
@@ -160,15 +165,22 @@ const text = (key: string) => (typeof settings.value[key] === "string" ? (settin
|
||||
<div class="flex-1 space-y-5 overflow-y-auto px-4 py-4">
|
||||
<p v-if="problem" class="rounded-md bg-danger/10 px-2.5 py-1.5 text-xs text-danger" role="alert">{{ problem }}</p>
|
||||
|
||||
<section v-if="type === 'parallel'" class="space-y-3">
|
||||
<div class="text-xs font-medium text-muted-foreground">Branches</div>
|
||||
<section v-if="branching" class="space-y-3">
|
||||
<template v-if="type === 'switch'">
|
||||
<label class="block space-y-1.5">
|
||||
<span class="text-xs font-medium text-muted-foreground" title="The value whose case runs; a case named default runs when none matches">Switch on</span>
|
||||
<Input :model-value="branching.on" class="font-mono" placeholder="steps.assess.result.fit" list="switch-on" @change="setOn(($event.target as HTMLInputElement).value.trim())" />
|
||||
<datalist id="switch-on"><option v-for="id in earlier" :key="id" :value="`steps.${id}.result.`" /></datalist>
|
||||
</label>
|
||||
</template>
|
||||
<div class="text-xs font-medium text-muted-foreground">{{ type === "switch" ? "Cases" : "Branches" }}</div>
|
||||
<div v-for="name in branches" :key="name" class="flex items-center gap-2">
|
||||
<Input :model-value="name" :aria-label="`Branch ${name}`" @change="changeBranch('rename', name, ($event.target as HTMLInputElement).value.trim())" />
|
||||
<Button type="button" variant="ghost" size="icon-sm" :aria-label="`Remove branch ${name}`" :disabled="branches.length <= 2" title="Parallel needs at least two branches" @click="changeBranch('delete', name)"><Trash2 /></Button>
|
||||
<Input :model-value="name" :class="type === 'switch' && 'font-mono'" :aria-label="`${type === 'switch' ? 'Case' : 'Branch'} ${name}`" @change="changeBranch('rename', name, ($event.target as HTMLInputElement).value.trim())" />
|
||||
<Button type="button" variant="ghost" size="icon-sm" :aria-label="`Remove ${name}`" :disabled="branches.length <= minBranches" @click="changeBranch('delete', name)"><Trash2 /></Button>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<Input v-model="newBranch" aria-label="New branch name" placeholder="Branch name" @keydown.enter.prevent="changeBranch('add', newBranch.trim())" />
|
||||
<Button type="button" size="icon-sm" variant="outline" aria-label="Add branch" :disabled="!newBranch.trim()" @click="changeBranch('add', newBranch.trim())"><Plus /></Button>
|
||||
<Input v-model="newBranch" :aria-label="type === 'switch' ? 'New case value' : 'New branch name'" :placeholder="type === 'switch' ? 'Value, or default' : 'Branch name'" @keydown.enter.prevent="changeBranch('add', newBranch.trim())" />
|
||||
<Button type="button" size="icon-sm" variant="outline" :aria-label="type === 'switch' ? 'Add case' : 'Add branch'" :disabled="!newBranch.trim()" @click="changeBranch('add', newBranch.trim())"><Plus /></Button>
|
||||
</div>
|
||||
<p v-if="branchError" role="alert" class="text-xs text-danger">{{ branchError }}</p>
|
||||
</section>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { Handle, Position } from "@vue-flow/core";
|
||||
import { Flag, GitBranch, Play, Repeat, SkipForward, Webhook, CircleDot, BookOpen, Workflow } from "@lucide/vue";
|
||||
import { Flag, Play, Repeat, SkipForward, Webhook, CircleDot, BookOpen, Workflow } from "@lucide/vue";
|
||||
|
||||
import { stepIcon } from "./step-icons";
|
||||
import type { StepNodeData } from "./workflow-graph";
|
||||
@@ -57,9 +57,6 @@ function duration(ms?: number): string {
|
||||
<component :is="stepIcon(data.type)" v-else class="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
|
||||
<span v-if="data.step" class="font-mono text-[11px] text-fg-subtle">{{ data.step }}</span>
|
||||
<span class="truncate text-sm font-medium" :title="data.title">{{ data.title }}</span>
|
||||
<span v-if="data.branch" class="ml-auto flex items-center gap-0.5 text-[11px] text-fg-subtle">
|
||||
<GitBranch class="size-3" aria-hidden="true" />{{ data.branch }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="data.type && data.type !== data.title" class="truncate font-mono text-[11px] text-fg-subtle">{{ data.type }}</div>
|
||||
<ul v-if="data.kind === 'start' && data.triggers?.length" class="mt-1 space-y-0.5">
|
||||
@@ -96,5 +93,6 @@ function duration(ms?: number): string {
|
||||
</div>
|
||||
<Handle type="source" :position="Position.Bottom" />
|
||||
<Handle id="data-out" type="source" :position="Position.Right" class="!opacity-0" />
|
||||
<Handle v-if="data.type === 'switch'" id="otherwise" type="source" :position="Position.Right" class="!opacity-0" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { GitBranch } from "@lucide/vue";
|
||||
import { GitBranch, Split } from "@lucide/vue";
|
||||
|
||||
import {
|
||||
DropdownMenuItem,
|
||||
@@ -19,6 +19,7 @@ const groups = computed(() => stepGroups(props.types));
|
||||
|
||||
<template>
|
||||
<DropdownMenuItem v-if="types.includes('parallel')" @select="emit('pick', 'parallel')"><GitBranch />Parallel</DropdownMenuItem>
|
||||
<DropdownMenuItem v-if="types.includes('switch')" @select="emit('pick', 'switch')"><Split />Switch</DropdownMenuItem>
|
||||
<template v-for="group in groups" :key="group.title">
|
||||
<!-- A group of one is its step: no submenu to open for a single choice. -->
|
||||
<DropdownMenuItem v-if="group.types.length === 1" @select="emit('pick', group.types[0])">
|
||||
|
||||
@@ -22,7 +22,8 @@ import AddNode from "./AddNode.vue";
|
||||
import InsertEdge from "./InsertEdge.vue";
|
||||
import StepNode from "./StepNode.vue";
|
||||
import StepTypeItems from "./StepTypeItems.vue";
|
||||
import type { StepPath } from "./workflow-edit";
|
||||
import { inParallel, type StepPath } from "./workflow-edit";
|
||||
import LaneNode from "./LaneNode.vue";
|
||||
import { restartAt, stepTitle, withRuns, workflowGraph, type StageRun, type StepNodeData } from "./workflow-graph";
|
||||
import type { WorkflowTrigger } from "./workflow-triggers";
|
||||
|
||||
@@ -48,9 +49,9 @@ const emit = defineEmits<{
|
||||
|
||||
const NODE_WIDTH = 240;
|
||||
const editable = computed(() => !!props.types?.length);
|
||||
const types = computed(() => [...(props.types ?? []), "parallel"]);
|
||||
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 && path.length > 2 ? branchTypes.value : types.value;
|
||||
const typesAt = (path?: StepPath) => (path && inParallel(path) ? branchTypes.value : types.value);
|
||||
|
||||
const container = ref<HTMLElement | null>(null);
|
||||
const graph = computed(() => withRuns(workflowGraph(props.yaml), props.stages ?? []));
|
||||
@@ -64,6 +65,7 @@ const nodes = computed(() =>
|
||||
// Each trigger past the second makes the start node a line taller.
|
||||
const drop = Math.max(0, (props.triggers?.length ?? 0) - 2) * 18;
|
||||
if (drop) node = { ...node, position: { ...node.position, y: node.position.y + drop } };
|
||||
if (node.type === "lane") return node;
|
||||
return JSON.stringify(node.data.path ?? null) === selectedKey.value && props.selected
|
||||
? { ...node, data: { ...node.data, selected: true } }
|
||||
: node;
|
||||
@@ -73,12 +75,13 @@ const nodes = computed(() =>
|
||||
// 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])));
|
||||
const edges = computed(() =>
|
||||
graph.value.edges.map(({ label, offset, insertAfter, ...edge }) =>
|
||||
graph.value.edges.map(({ label, offset, insertAfter, otherwise, ...edge }) =>
|
||||
edge.kind === "flow"
|
||||
? {
|
||||
...edge,
|
||||
type: "insert",
|
||||
data: { trace: runs.value.get(edge.target), insertAfter, types: typesAt(insertAfter), editable: editable.value, onInsert: (after: StepPath, type: string) => emit("insert", after, type) },
|
||||
...(otherwise ? { sourceHandle: "otherwise" } : {}),
|
||||
data: { trace: runs.value.get(edge.target), otherwise, insertAfter, types: typesAt(insertAfter), editable: editable.value, onInsert: (after: StepPath, type: string) => emit("insert", after, type) },
|
||||
}
|
||||
: {
|
||||
...edge,
|
||||
@@ -121,7 +124,7 @@ function openMenu(event: MouseEvent, step?: StepNodeData): void {
|
||||
menu.value = { open: true, x: event.clientX - (box?.left ?? 0), y: event.clientY - (box?.top ?? 0), step };
|
||||
}
|
||||
function onNodeMenu({ event, node }: NodeMouseEvent): void {
|
||||
if (node.type === "add") return;
|
||||
if (node.type !== "step") return;
|
||||
openMenu(event as MouseEvent, node.data as StepNodeData);
|
||||
}
|
||||
function onNodeClick({ node }: NodeMouseEvent): void {
|
||||
@@ -155,6 +158,9 @@ const beforePath = computed(() => menuPath.value ? [...menuPath.value.slice(0, -
|
||||
<template #node-step="nodeProps">
|
||||
<StepNode v-bind="nodeProps" />
|
||||
</template>
|
||||
<template #node-lane="nodeProps">
|
||||
<LaneNode v-bind="nodeProps" />
|
||||
</template>
|
||||
<template #node-add="nodeProps">
|
||||
<AddNode v-bind="nodeProps" />
|
||||
</template>
|
||||
@@ -185,7 +191,7 @@ const beforePath = computed(() => menuPath.value ? [...menuPath.value.slice(0, -
|
||||
<DropdownMenuSubTrigger>Insert after</DropdownMenuSubTrigger>
|
||||
<DropdownMenuSubContent class="w-52"><StepTypeItems :types="typesAt(menuPath)" @pick="emit('insert', menuPath, $event)" /></DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
<DropdownMenuItem v-if="menu.step.type !== 'parallel'" @select="emit('duplicate', menuPath)"><Copy />Duplicate</DropdownMenuItem>
|
||||
<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 />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Bot, FileSearch, GitBranch, MessageSquare, ShieldCheck, Terminal, UserCheck, Workflow } from "@lucide/vue";
|
||||
import { Bot, FileSearch, GitBranch, MessageSquare, ShieldCheck, Split, Terminal, UserCheck, Workflow } from "@lucide/vue";
|
||||
import type { Component } from "vue";
|
||||
|
||||
const GROUP_ICONS: Record<string, Component> = {
|
||||
@@ -25,6 +25,8 @@ const GROUP_TITLES: Record<string, string> = {
|
||||
|
||||
/** The icon for a step type, by the area its name starts with. */
|
||||
export function stepIcon(type: string): Component {
|
||||
if (type === "parallel") return GitBranch;
|
||||
if (type === "switch") return Split;
|
||||
return GROUP_ICONS[type.split(".")[0]] ?? Workflow;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,11 +7,39 @@ import { isMap, isScalar, isSeq, parseDocument } from "yaml";
|
||||
*/
|
||||
|
||||
/** Where a step lives in the document: ["steps", 2], or
|
||||
* ["steps", 1, "parallel", "docs", 0] for a step inside a branch. */
|
||||
* ["steps", 1, "parallel", "docs", 0] for a step inside a branch, or
|
||||
* ["steps", 1, "switch", "cases", "false", 0] for a step inside a case. */
|
||||
export type StepPath = (string | number)[];
|
||||
|
||||
export type StepRecord = Record<string, unknown>;
|
||||
|
||||
/** A step's nested step lists: parallel branches, which all run, or switch
|
||||
* cases, of which one runs. base is where the lists sit under the step. */
|
||||
export interface Branching {
|
||||
kind: "parallel" | "switch";
|
||||
base: string[];
|
||||
on?: string;
|
||||
branches: [string, unknown[]][];
|
||||
}
|
||||
|
||||
const isRecord = (value: unknown): value is StepRecord => typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
const lists = (value: unknown): [string, unknown[]][] =>
|
||||
isRecord(value) ? Object.entries(value).map(([name, steps]) => [name, Array.isArray(steps) ? steps : []]) : [];
|
||||
|
||||
export function branchingOf(step: unknown): Branching | undefined {
|
||||
if (!isRecord(step)) return undefined;
|
||||
if (isRecord(step.parallel)) return { kind: "parallel", base: ["parallel"], branches: lists(step.parallel) };
|
||||
if (isRecord(step.switch))
|
||||
return { kind: "switch", base: ["switch", "cases"], on: typeof step.switch.on === "string" ? step.switch.on : "", branches: lists(step.switch.cases) };
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Parallel branches share a worktree, so only read-only agents and calls run
|
||||
* there. A switch case runs alone and takes any step. */
|
||||
export function inParallel(path: StepPath): boolean {
|
||||
return path.slice(2).includes("parallel");
|
||||
}
|
||||
|
||||
/** A step as plain data, or undefined when the path names none. */
|
||||
export function stepAt(source: string, path: StepPath): StepRecord | undefined {
|
||||
const node = parseDocument(source).getIn(path, true);
|
||||
@@ -31,7 +59,7 @@ export function replaceStep(source: string, path: StepPath, step: StepRecord): s
|
||||
export function insertStep(source: string, after: StepPath, type: string): { source: string; path: StepPath } {
|
||||
const document = parseDocument(source);
|
||||
const list = after.slice(0, -1);
|
||||
const inBranch = list.length > 1;
|
||||
const inBranch = inParallel(list);
|
||||
if (inBranch && !["agent.run", "workflow.call"].includes(type)) throw new Error("Branches allow only read-only agents and workflow calls.");
|
||||
let steps = document.getIn(list, true);
|
||||
if (!isSeq(steps)) {
|
||||
@@ -40,30 +68,42 @@ export function insertStep(source: string, after: StepPath, type: string): { sou
|
||||
}
|
||||
if (!isSeq(steps)) return { source, path: [] };
|
||||
const index = Math.min(Math.max(Number(after.at(-1)) + 1, 0), steps.items.length);
|
||||
const step = type === "parallel" ? { parallel: { "branch-1": [], "branch-2": [] } } : { type, ...(inBranch && type === "agent.run" ? { settings: { read_only: true } } : {}) };
|
||||
const step = type === "parallel" ? { parallel: { "branch-1": [], "branch-2": [] } }
|
||||
: type === "switch" ? { switch: { on: "", cases: { "true": [], default: [] } } } : { type, ...(inBranch && type === "agent.run" ? { settings: { read_only: true } } : {}) };
|
||||
steps.items.splice(index, 0, document.createNode(step));
|
||||
return { source: document.toString(), path: [...list, index] };
|
||||
}
|
||||
|
||||
function checkBranchName(name: string): void {
|
||||
function checkBranchName(name: string, kind: Branching["kind"]): void {
|
||||
if (kind === "switch") {
|
||||
if (!name || name.includes("/")) throw new Error("A case is the value it matches, without a slash.");
|
||||
return;
|
||||
}
|
||||
if (!/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/.test(name)) throw new Error("Use a lowercase branch name with letters, digits, dots or dashes.");
|
||||
}
|
||||
|
||||
/** The map of a step's branches or cases, with what kind of step holds it. */
|
||||
function branchMap(document: ReturnType<typeof parseDocument>, path: StepPath) {
|
||||
const step = document.getIn(path, true);
|
||||
const branching = branchingOf(isMap(step) ? step.toJSON() : undefined);
|
||||
const branches = branching ? document.getIn([...path, ...branching.base], true) : undefined;
|
||||
if (!branching || !isMap(branches)) throw new Error("This step has no branches.");
|
||||
return { kind: branching.kind, branches };
|
||||
}
|
||||
|
||||
export function addBranch(source: string, path: StepPath, name: string): string {
|
||||
checkBranchName(name);
|
||||
const document = parseDocument(source);
|
||||
const branches = document.getIn([...path, "parallel"], true);
|
||||
if (!isMap(branches)) throw new Error("This step has no branches.");
|
||||
const { kind, branches } = branchMap(document, path);
|
||||
checkBranchName(name, kind);
|
||||
if (branches.has(name)) throw new Error(`Branch ${name} already exists.`);
|
||||
branches.set(name, document.createNode([]));
|
||||
return document.toString();
|
||||
}
|
||||
|
||||
export function renameBranch(source: string, path: StepPath, name: string, next: string): string {
|
||||
checkBranchName(next);
|
||||
const document = parseDocument(source);
|
||||
const branches = document.getIn([...path, "parallel"], true);
|
||||
if (!isMap(branches)) throw new Error("This step has no branches.");
|
||||
const { kind, branches } = branchMap(document, path);
|
||||
checkBranchName(next, kind);
|
||||
if (name !== next && branches.has(next)) throw new Error(`Branch ${next} already exists.`);
|
||||
const pair = branches.items.find((pair) => isScalar(pair.key) && pair.key.value === name);
|
||||
if (!pair || !isScalar(pair.key)) throw new Error(`Branch ${name} does not exist.`);
|
||||
@@ -73,8 +113,9 @@ export function renameBranch(source: string, path: StepPath, name: string, next:
|
||||
|
||||
export function deleteBranch(source: string, path: StepPath, name: string): string {
|
||||
const document = parseDocument(source);
|
||||
const branches = document.getIn([...path, "parallel"], true);
|
||||
if (!isMap(branches) || branches.items.length <= 2) throw new Error("Parallel needs at least two branches.");
|
||||
const { kind, branches } = branchMap(document, path);
|
||||
if (kind === "parallel" && branches.items.length <= 2) throw new Error("Parallel needs at least two branches.");
|
||||
if (branches.items.length <= 1) throw new Error("A switch needs at least one case.");
|
||||
branches.delete(name);
|
||||
return document.toString();
|
||||
}
|
||||
@@ -124,15 +165,13 @@ export function earlierStepIDs(source: string, path: StepPath): string[] {
|
||||
if (typeof step !== "object" || step === null) return;
|
||||
const record = step as StepRecord;
|
||||
if (typeof record.id === "string") ids.push(record.id);
|
||||
if (typeof record.parallel === "object" && record.parallel !== null)
|
||||
for (const branch of Object.values(record.parallel as Record<string, unknown[]>))
|
||||
if (Array.isArray(branch)) branch.forEach(collect);
|
||||
for (const [, branch] of branchingOf(record)?.branches ?? []) branch.forEach(collect);
|
||||
};
|
||||
steps.slice(0, top).forEach(collect);
|
||||
if (path.length === 5) {
|
||||
const branch = (steps[top] as StepRecord | undefined)?.parallel as Record<string, unknown[]> | undefined;
|
||||
const own = branch?.[path[3] as string];
|
||||
if (Array.isArray(own)) own.slice(0, path[4] as number).forEach(collect);
|
||||
if (path.length > 2) {
|
||||
const name = path.at(-2) as string;
|
||||
const own = branchingOf(steps[top])?.branches.find(([branch]) => branch === name)?.[1];
|
||||
own?.slice(0, path.at(-1) as number).forEach(collect);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { parseDocument } from "yaml";
|
||||
|
||||
import { branchingOf } from "./workflow-edit.ts";
|
||||
import type { WorkflowTrigger } from "./workflow-triggers";
|
||||
|
||||
/**
|
||||
@@ -26,6 +27,8 @@ export interface StepNodeData {
|
||||
retry?: number;
|
||||
continues?: boolean;
|
||||
branch?: string;
|
||||
/** Whether the branch is one of several that all run, or a switch case. */
|
||||
lane?: "parallel" | "switch";
|
||||
/** 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;
|
||||
@@ -45,7 +48,7 @@ export interface StepNodeData {
|
||||
export type StepRole = "work" | "decision" | "waiting" | "exit";
|
||||
|
||||
function stepRole(type: string): StepRole {
|
||||
if (type.startsWith("gate.")) return "decision";
|
||||
if (type.startsWith("gate.") || type === "switch") return "decision";
|
||||
if (type === "human.approve") return "waiting";
|
||||
if (type === "workflow.finish" || type === "workflow.handoff") return "exit";
|
||||
return "work";
|
||||
@@ -119,7 +122,10 @@ export function restartAt(graph: WorkflowGraph, path: (string | number)[]): Rest
|
||||
|
||||
export interface GraphNode {
|
||||
id: string;
|
||||
type: "step" | "add";
|
||||
type: "step" | "add" | "lane";
|
||||
/** A lane's size, drawn behind its steps. */
|
||||
style?: { width: string; height: string };
|
||||
zIndex?: number;
|
||||
position: { x: number; y: number };
|
||||
data: StepNodeData;
|
||||
}
|
||||
@@ -130,6 +136,8 @@ export interface GraphEdge {
|
||||
target: string;
|
||||
/** "flow" is run order; "data" is a reference to an earlier result. */
|
||||
kind: "flow" | "data";
|
||||
/** A flow edge that skips past a switch none of whose cases matched. */
|
||||
otherwise?: boolean;
|
||||
label?: string;
|
||||
sourceHandle?: string;
|
||||
targetHandle?: string;
|
||||
@@ -148,6 +156,7 @@ const COLUMN = 280;
|
||||
|
||||
const TYPE_TITLES: Record<string, string> = {
|
||||
parallel: "Parallel",
|
||||
switch: "Switch",
|
||||
"agent.run": "Agent",
|
||||
"command.run": "Run commands",
|
||||
"repo.prepare": "Prepare worktree",
|
||||
@@ -231,6 +240,7 @@ export function workflowGraph(source: string): WorkflowGraph {
|
||||
const edges: GraphEdge[] = [];
|
||||
const byStepID = new Map<string, string>();
|
||||
const pendingData: { from: string; to: string }[] = [];
|
||||
const otherwise = new Set<string>();
|
||||
|
||||
const start = "start";
|
||||
nodes.push({
|
||||
@@ -256,9 +266,11 @@ export function workflowGraph(source: string): WorkflowGraph {
|
||||
branch?: string,
|
||||
resume?: string,
|
||||
path?: (string | number)[],
|
||||
lane?: "parallel" | "switch",
|
||||
): string => {
|
||||
const record = isMapping(step) ? step : {};
|
||||
const type = isMapping(record.parallel) ? "parallel" : typeof record.type === "string" ? record.type : "";
|
||||
const branching = branchingOf(record);
|
||||
const type = branching?.kind ?? (typeof record.type === "string" ? record.type : "");
|
||||
const settings = isMapping(record.settings) ? record.settings : {};
|
||||
const stepID = typeof record.id === "string" ? record.id : "";
|
||||
const id = `step-${key}`;
|
||||
@@ -276,12 +288,13 @@ export function workflowGraph(source: string): WorkflowGraph {
|
||||
type,
|
||||
role: stepRole(type),
|
||||
step: path?.length === 2 ? String(Number(path[1]) + 1).padStart(2, "0") : undefined,
|
||||
detail: stepDetail(type, settings),
|
||||
detail: branching?.on ? `on ${branching.on.replace(/^steps\./, "")}` : stepDetail(type, settings),
|
||||
summary: stepSummary(settings),
|
||||
when: typeof record.when === "string" ? record.when : undefined,
|
||||
retry: isMapping(record.retry) && typeof record.retry.attempts === "number" ? record.retry.attempts : undefined,
|
||||
continues: record.on_failure === "continue",
|
||||
branch,
|
||||
lane,
|
||||
path,
|
||||
stage: recordName,
|
||||
occurrence: occurrenceOf(recordName),
|
||||
@@ -289,7 +302,8 @@ export function workflowGraph(source: string): WorkflowGraph {
|
||||
},
|
||||
});
|
||||
if (stepID) byStepID.set(stepID, id);
|
||||
for (const ref of referencedSteps(record.settings, record.when)) pendingData.push({ from: ref, to: id });
|
||||
const on = branching?.on ? `{{ ${branching.on} }}` : "";
|
||||
for (const ref of referencedSteps([record.settings, on], record.when)) pendingData.push({ from: ref, to: id });
|
||||
return id;
|
||||
};
|
||||
const link = (from: string[], to: string, insertAfter?: (string | number)[]) => {
|
||||
@@ -300,38 +314,61 @@ export function workflowGraph(source: string): WorkflowGraph {
|
||||
source,
|
||||
target: to,
|
||||
kind: "flow",
|
||||
...(otherwise.has(source) ? { otherwise: true } : {}),
|
||||
insertAfter: n === from.length - 1 ? insertAfter : undefined,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
for (const [i, step] of steps.entries()) {
|
||||
if (isMapping(step) && isMapping(step.parallel)) {
|
||||
const branches = Object.entries(step.parallel);
|
||||
const branching = branchingOf(step);
|
||||
if (branching) {
|
||||
const { kind, base, branches } = branching;
|
||||
const parent = addStep(step, String(i + 1), 0, row * ROW, undefined, undefined, ["steps", i]);
|
||||
link(previous, parent, ["steps", i - 1]);
|
||||
row++;
|
||||
// Each branch step records its own row under the parallel step, so the
|
||||
// canvas lights every branch node from its own run.
|
||||
const parallelName = typeof step.id === "string" ? step.id : "parallel";
|
||||
// Each branch step records its own row under the parallel or switch
|
||||
// step, so the canvas lights every branch node from its own run.
|
||||
const parentName = isMapping(step) && typeof step.id === "string" ? step.id : kind;
|
||||
// A switch with no default case lets the run go straight on when no
|
||||
// case matches; that way out is drawn as a lane of its own.
|
||||
const passes = kind === "switch" && !branches.some(([name]) => name === "default");
|
||||
const lanes = branches.length + (passes ? 1 : 0);
|
||||
const ends: string[] = [];
|
||||
let depth = 0;
|
||||
branches.forEach(([name, branchSteps], column) => {
|
||||
const x = (column - (branches.length - 1) / 2) * COLUMN;
|
||||
const x = (column - (lanes - 1) / 2) * COLUMN;
|
||||
let tail = [parent];
|
||||
const path = ["steps", i, "parallel", name];
|
||||
(Array.isArray(branchSteps) ? branchSteps : []).forEach((branchStep, j) => {
|
||||
const id = addStep(branchStep, `${i + 1}-${name}-${j + 1}`, x, (row + j) * ROW, name, parallelName, ["steps", i, "parallel", name, j]);
|
||||
const path = ["steps", i, ...base, name];
|
||||
branchSteps.forEach((branchStep, j) => {
|
||||
const id = addStep(branchStep, `${i + 1}-${name}-${j + 1}`, x, (row + j) * ROW, name, parentName, [...path, j], kind);
|
||||
link(tail, id, [...path, j - 1]);
|
||||
tail = [id];
|
||||
depth = Math.max(depth, j + 1);
|
||||
});
|
||||
const count = Array.isArray(branchSteps) ? branchSteps.length : 0;
|
||||
depth = Math.max(depth, branchSteps.length);
|
||||
const end = `add-${i}-${name}`;
|
||||
nodes.push({ id: end, type: "add", position: { x: x + 104, y: (row + count) * ROW }, data: { kind: "step", key: end, title: "", type: "", detail: "", branch: name, insertAfter: [...path, count - 1] } });
|
||||
nodes.push({ id: end, type: "add", position: { x: x + 104, y: (row + branchSteps.length) * ROW }, data: { kind: "step", key: end, title: "", type: "", detail: "", branch: name, lane: kind, insertAfter: [...path, branchSteps.length - 1] } });
|
||||
link(tail, end);
|
||||
ends.push(end);
|
||||
});
|
||||
const height = (Math.max(depth, 1) + 1) * ROW - 24;
|
||||
branches.forEach(([name], column) => {
|
||||
const x = (column - (lanes - 1) / 2) * COLUMN;
|
||||
nodes.push({
|
||||
id: `lane-${i}-${name}`,
|
||||
type: "lane",
|
||||
position: { x: x - 12, y: row * ROW - 40 },
|
||||
style: { width: `${COLUMN - 16}px`, height: `${height}px` },
|
||||
zIndex: -1,
|
||||
data: { kind: "step", key: name, title: name, type: "", detail: "", lane: kind },
|
||||
});
|
||||
});
|
||||
if (passes) {
|
||||
// The run's way past an unmatched switch: an edge from the switch to
|
||||
// the step after it, drawn down the last column.
|
||||
ends.push(parent);
|
||||
otherwise.add(parent);
|
||||
}
|
||||
previous = ends;
|
||||
row += Math.max(depth, 1) + 1;
|
||||
continue;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { computed, onMounted, ref, type Ref } from "vue";
|
||||
import { parse } from "yaml";
|
||||
|
||||
import { api } from "@/lib/api";
|
||||
import { branchingOf } from "./workflow-edit.ts";
|
||||
import { useControlPlaneStore } from "@/stores/control-plane";
|
||||
import type { Binding } from "@/bindings/binding-draft";
|
||||
|
||||
@@ -72,7 +73,7 @@ export function triggersFor(id: string, sources: TriggerSources): WorkflowTrigge
|
||||
function startsVia(value: unknown, target: string): string {
|
||||
const steps = isMapping(value) && Array.isArray(value.steps) ? value.steps : [];
|
||||
const all = steps.flatMap((step) =>
|
||||
isMapping(step) && isMapping(step.parallel) ? Object.values(step.parallel).flat() : [step],
|
||||
branchingOf(step)?.branches.flatMap(([, branch]) => branch) ?? [step],
|
||||
);
|
||||
for (const step of all) {
|
||||
if (!isMapping(step) || !isMapping(step.settings)) continue;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { parseDocument } from "yaml";
|
||||
import { branchingOf } from "./workflow-edit.ts";
|
||||
|
||||
/**
|
||||
* The workflow YAML editor's reading of what is typed.
|
||||
@@ -86,10 +87,15 @@ export function parseWorkflowYaml(
|
||||
const declared = new Set<string>();
|
||||
for (const [i, step] of steps.entries()) {
|
||||
const where = `workflow ${id} step ${i + 1}`;
|
||||
if (isMapping(step) && isMapping(step.parallel)) {
|
||||
for (const [branch, branchSteps] of Object.entries(step.parallel)) {
|
||||
if (!Array.isArray(branchSteps) || !branchSteps.length)
|
||||
return { ok: false, message: `${where}: branch ${branch} needs a list of steps` };
|
||||
const branching = branchingOf(step);
|
||||
if (branching) {
|
||||
if (branching.kind === "switch" && !branching.on)
|
||||
return { ok: false, message: `${where}: switch.on names nothing` };
|
||||
if (branching.on && !declared.has(branching.on.split(".")[1] ?? "") && branching.on.startsWith("steps."))
|
||||
return { ok: false, message: `${where}: no earlier step has id "${branching.on.split(".")[1]}"` };
|
||||
for (const [branch, branchSteps] of branching.branches) {
|
||||
if (!branchSteps.length)
|
||||
return { ok: false, message: `${where}: ${branching.kind === "switch" ? "case" : "branch"} ${branch} needs a list of steps` };
|
||||
const visible = new Set(declared);
|
||||
for (const [j, branchStep] of branchSteps.entries()) {
|
||||
const branchWhere = `${where} branch ${branch} step ${j + 1}`;
|
||||
@@ -102,7 +108,7 @@ export function parseWorkflowYaml(
|
||||
for (const branchStep of branchSteps) declareID(branchStep, declared);
|
||||
}
|
||||
declareID(step, declared);
|
||||
chips.push({ index: i + 1, type: "parallel" });
|
||||
chips.push({ index: i + 1, type: branching.kind });
|
||||
continue;
|
||||
}
|
||||
const problem = checkStepType(step, where, known, repository) || laterReference(step, where, declared);
|
||||
|
||||
Reference in new issue
Block a user