feat(ui): author parallel workflow branches on canvas

This commit is contained in:
sam committed 2026-10-09 18:18:45 +11:00
1 parent 81121d03b0
commit c812192800
11 files changed
+262 -125

No files matched your search

+5 -3
View File
@@ -3,13 +3,15 @@ import { Handle, Position } from "@vue-flow/core";
import AddStepMenu from "./AddStepMenu.vue";
defineProps<{ data: { types: string[]; editable: boolean; onInsert: (type: string) => void } }>();
defineProps<{ data: { branch?: string; types: string[]; editable: boolean; onInsert: (type: string) => void } }>();
</script>
<template>
<div class="flex w-8 justify-center">
<div class="relative flex w-8 justify-center">
<Handle type="target" :position="Position.Top" class="!opacity-0" />
<AddStepMenu v-if="data.editable" :types="data.types" label="Add a step at the end" @pick="data.onInsert" />
<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" />
</div>
</template>
+3 -2
View File
@@ -3,8 +3,9 @@ import { computed } from "vue";
import { BaseEdge, EdgeLabelRenderer, getSmoothStepPath, type EdgeProps } from "@vue-flow/core";
import AddStepMenu from "./AddStepMenu.vue";
import type { StepPath } from "./workflow-edit";
const props = defineProps<EdgeProps<{ insertAfter?: number; types: string[]; editable: boolean; onInsert: (after: number, type: string) => void }>>();
const props = defineProps<EdgeProps<{ insertAfter?: StepPath; types: string[]; editable: boolean; onInsert: (after: StepPath, type: string) => void }>>();
const path = computed(() =>
getSmoothStepPath({
@@ -26,7 +27,7 @@ const path = computed(() =>
class="workflow-insert absolute"
:style="{ transform: `translate(-50%, -50%) translate(${path[1]}px, ${path[2]}px)`, pointerEvents: 'all' }"
>
<AddStepMenu :types="data.types" @pick="data.onInsert(data.insertAfter!, $event)" />
<AddStepMenu :types="data.types" :label="data.insertAfter.length > 2 ? `Add a step in ${data.insertAfter[3]}` : undefined" @pick="data.onInsert(data.insertAfter!, $event)" />
</div>
</EdgeLabelRenderer>
</template>
+29 -3
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import { CircleHelp, Trash2, X } from "@lucide/vue";
import { CircleHelp, Plus, Trash2, X } from "@lucide/vue";
import { parse, stringify } from "yaml";
import { Button } from "@/components/ui/button";
@@ -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 { earlierStepIDs, replaceStep, stepAt, workflowField, type StepPath, type StepRecord } from "./workflow-edit";
import { addBranch, 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,7 +21,20 @@ 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(() => (typeof step.value.type === "string" ? step.value.type : ""));
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 newBranch = ref("");
const branchError = ref("");
function changeBranch(action: "add" | "rename" | "delete", name: string, next = ""): void {
try {
const source = action === "add" ? addBranch(props.yaml, props.path, name) : action === "rename" ? renameBranch(props.yaml, props.path, name, next) : deleteBranch(props.yaml, props.path, name);
emit("update:yaml", source);
newBranch.value = "";
branchError.value = "";
} catch (error) {
branchError.value = String((error as Error).message);
}
}
const info = computed(() => props.vocabulary.find((candidate) => candidate.name === type.value));
const settings = computed<Record<string, unknown>>(() =>
typeof step.value.settings === "object" && step.value.settings !== null ? (step.value.settings as Record<string, unknown>) : {},
@@ -147,6 +160,19 @@ 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>
<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>
</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>
</div>
<p v-if="branchError" role="alert" class="text-xs text-danger">{{ branchError }}</p>
</section>
<section v-if="fields.lead" class="space-y-1.5">
<div class="flex items-center gap-1 text-xs font-medium text-muted-foreground" :title="fields.lead.schema.description">
{{ label(fields.lead.key, fields.lead.schema) }}
+2
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { computed } from "vue";
import { GitBranch } from "@lucide/vue";
import {
DropdownMenuItem,
@@ -17,6 +18,7 @@ const groups = computed(() => stepGroups(props.types));
</script>
<template>
<DropdownMenuItem v-if="types.includes('parallel')" @select="emit('pick', 'parallel')"><GitBranch /> Parallel</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])">
+18 -17
View File
@@ -39,7 +39,7 @@ const props = defineProps<{
const emit = defineEmits<{
edit: [StepPath];
settings: [];
insert: [after: number, type: string];
insert: [after: StepPath, type: string];
duplicate: [StepPath];
move: [StepPath, -1 | 1];
remove: [StepPath];
@@ -48,7 +48,9 @@ const emit = defineEmits<{
const NODE_WIDTH = 240;
const editable = computed(() => !!props.types?.length);
const types = computed(() => props.types ?? []);
const types = computed(() => [...(props.types ?? []), "parallel"]);
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 container = ref<HTMLElement | null>(null);
const graph = computed(() => withRuns(workflowGraph(props.yaml), props.stages ?? []));
@@ -57,7 +59,7 @@ const stepCount = computed(() => graph.value.nodes.filter((node) => node.data.pa
const nodes = computed(() =>
graph.value.nodes.map((node) => {
if (node.type === "add")
return { ...node, data: { types: types.value, editable: editable.value, onInsert: (type: string) => emit("insert", stepCount.value - 1, type) } };
return { ...node, data: { ...node.data, types: typesAt(node.data.insertAfter), editable: editable.value, onInsert: (type: string) => emit("insert", node.data.insertAfter!, type) } };
if (node.data.kind === "start") return { ...node, data: { ...node.data, triggers: props.triggers ?? [] } };
// Each trigger past the second makes the start node a line taller.
const drop = Math.max(0, (props.triggers?.length ?? 0) - 2) * 18;
@@ -73,7 +75,7 @@ const edges = computed(() =>
? {
...edge,
type: "insert",
data: { insertAfter, types: types.value, editable: editable.value, onInsert: (after: number, type: string) => emit("insert", after, type) },
data: { insertAfter, types: typesAt(insertAfter), editable: editable.value, onInsert: (after: StepPath, type: string) => emit("insert", after, type) },
}
: {
...edge,
@@ -126,7 +128,8 @@ function onNodeClick({ node }: NodeMouseEvent): void {
}
const menuPath = computed(() => menu.value.step?.path);
const restart = computed(() => (props.restartable && menuPath.value ? restartAt(graph.value, menuPath.value) : null));
const topIndex = computed(() => (menuPath.value?.length === 2 ? Number(menuPath.value[1]) : undefined));
const menuIndex = computed(() => Number(menuPath.value?.at(-1)));
const beforePath = computed(() => menuPath.value ? [...menuPath.value.slice(0, -1), menuIndex.value - 1] : []);
</script>
<template>
@@ -171,17 +174,15 @@ const topIndex = computed(() => (menuPath.value?.length === 2 ? Number(menuPath.
<DropdownMenuSeparator />
</template>
<DropdownMenuItem @select="emit('edit', menuPath)"><Pencil /> Edit</DropdownMenuItem>
<template v-if="topIndex !== undefined">
<DropdownMenuSub>
<DropdownMenuSubTrigger>Insert before</DropdownMenuSubTrigger>
<DropdownMenuSubContent class="w-52"><StepTypeItems :types="types" @pick="emit('insert', topIndex - 1, $event)" /></DropdownMenuSubContent>
</DropdownMenuSub>
<DropdownMenuSub>
<DropdownMenuSubTrigger>Insert after</DropdownMenuSubTrigger>
<DropdownMenuSubContent class="w-52"><StepTypeItems :types="types" @pick="emit('insert', topIndex, $event)" /></DropdownMenuSubContent>
</DropdownMenuSub>
</template>
<DropdownMenuItem @select="emit('duplicate', menuPath)"><Copy /> Duplicate</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="menu.step.type !== 'parallel'" @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 />
@@ -189,7 +190,7 @@ const topIndex = computed(() => (menuPath.value?.length === 2 ? Number(menuPath.
</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', menu.step?.kind === 'start' ? -1 : stepCount - 1, $event)" />
<StepTypeItems :types="types" @pick="emit('insert', ['steps', menu.step?.kind === 'start' ? -1 : stepCount - 1], $event)" />
</template>
</DropdownMenuContent>
</DropdownMenu>
+1 -1
View File
@@ -93,7 +93,7 @@ const { triggers, reload: reloadTriggers } = useWorkflowTriggers(selected);
// Canvas edits are edits to the YAML; a newly placed step opens for editing.
const stepTypeNames = computed(() => vocabulary.value.map((info) => info.name));
function insertAt(after: number, type: string): void {
function insertAt(after: StepPath, type: string): void {
stepTab.value = "definition";
const inserted = insertStep(yaml.value, after, type);
yaml.value = inserted.source;
+48 -17
View File
@@ -1,4 +1,4 @@
import { isMap, isSeq, parseDocument } from "yaml";
import { isMap, isScalar, isSeq, parseDocument } from "yaml";
/**
* Canvas edits as edits to the workflow's YAML document. The text stays the
@@ -27,20 +27,56 @@ export function replaceStep(source: string, path: StepPath, step: StepRecord): s
return document.toString();
}
/** Inserts a new step of the given type after the top-level step at index
* (-1 inserts first; past the end appends). Returns the new source and the
* inserted step's path. */
export function insertStep(source: string, after: number, type: string): { source: string; path: StepPath } {
/** Inserts after a step path; index -1 inserts first in that list. */
export function insertStep(source: string, after: StepPath, type: string): { source: string; path: StepPath } {
const document = parseDocument(source);
let steps = document.get("steps", true);
const list = after.slice(0, -1);
const inBranch = list.length > 1;
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)) {
document.set("steps", document.createNode([]));
steps = document.get("steps", true);
document.setIn(list, document.createNode([]));
steps = document.getIn(list, true);
}
if (!isSeq(steps)) return { source, path: [] };
const index = Math.min(Math.max(after + 1, 0), steps.items.length);
steps.items.splice(index, 0, document.createNode({ type }));
return { source: document.toString(), path: ["steps", index] };
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 } } : {}) };
steps.items.splice(index, 0, document.createNode(step));
return { source: document.toString(), path: [...list, index] };
}
function checkBranchName(name: string): void {
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.");
}
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.");
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.");
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.`);
pair.key.value = next;
return document.toString();
}
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.");
branches.delete(name);
return document.toString();
}
/** Copies a step to just after itself. The copy drops the id, which must stay
@@ -56,15 +92,10 @@ export function duplicateStep(source: string, path: StepPath): { source: string;
return { source: document.toString(), path: [...path.slice(0, -1), index + 1] };
}
/** Removes a step. A branch left empty is removed with it. */
/** Removes a step, leaving an empty branch available for authoring. */
export function deleteStep(source: string, path: StepPath): string {
const document = parseDocument(source);
document.deleteIn(path);
const branch = path.slice(0, -1);
if (branch.length > 2) {
const remaining = document.getIn(branch, true);
if (isSeq(remaining) && remaining.items.length === 0) document.deleteIn(branch);
}
return document.toString();
}
+20 -12
View File
@@ -34,6 +34,7 @@ export interface StepNodeData {
path?: (string | number)[];
selected?: boolean;
triggers?: WorkflowTrigger[];
insertAfter?: (string | number)[];
}
/** One recorded run of a step, from the task's attempts view. */
@@ -119,9 +120,8 @@ export interface GraphEdge {
sourceHandle?: string;
targetHandle?: string;
offset?: number;
/** A step inserted on this edge goes after the top-level step at this
* index (-1: first). Absent inside parallel branches. */
insertAfter?: number;
/** The predecessor path for insertion; index -1 inserts first in a list. */
insertAfter?: (string | number)[];
}
export interface WorkflowGraph {
@@ -133,6 +133,7 @@ const ROW = 140;
const COLUMN = 280;
const TYPE_TITLES: Record<string, string> = {
parallel: "Parallel",
"agent.run": "Agent",
"command.run": "Run commands",
"repo.prepare": "Prepare worktree",
@@ -243,7 +244,7 @@ export function workflowGraph(source: string): WorkflowGraph {
path?: (string | number)[],
): string => {
const record = isMapping(step) ? step : {};
const type = typeof record.type === "string" ? record.type : "";
const type = isMapping(record.parallel) ? "parallel" : 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}`;
@@ -275,7 +276,7 @@ export function workflowGraph(source: string): WorkflowGraph {
for (const ref of referencedSteps(record.settings, record.when)) pendingData.push({ from: ref, to: id });
return id;
};
const link = (from: string[], to: string, insertAfter?: number) => {
const link = (from: string[], to: string, insertAfter?: (string | number)[]) => {
// Several edges joining into one step share one insertion point.
from.forEach((source, n) =>
edges.push({
@@ -291,6 +292,9 @@ 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);
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";
@@ -298,22 +302,26 @@ export function workflowGraph(source: string): WorkflowGraph {
let depth = 0;
branches.forEach(([name, branchSteps], column) => {
const x = (column - (branches.length - 1) / 2) * COLUMN;
let tail = previous;
const entry = previous;
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]);
link(tail, id, tail === entry && column === branches.length - 1 ? i - 1 : undefined);
link(tail, id, [...path, j - 1]);
tail = [id];
depth = Math.max(depth, j + 1);
});
ends.push(...tail);
const count = Array.isArray(branchSteps) ? branchSteps.length : 0;
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] } });
link(tail, end);
ends.push(end);
});
previous = ends;
row += Math.max(depth, 1);
row += Math.max(depth, 1) + 1;
continue;
}
const id = addStep(step, String(i + 1), 0, row * ROW, undefined, undefined, ["steps", i]);
link(previous, id, i - 1);
link(previous, id, ["steps", i - 1]);
previous = [id];
row++;
}
@@ -323,7 +331,7 @@ export function workflowGraph(source: string): WorkflowGraph {
id: "add-end",
type: "add",
position: { x: 104, y: row * ROW - 24 },
data: { kind: "step", key: "add", title: "", type: "", detail: "" },
data: { kind: "step", key: "add", title: "", type: "", detail: "", insertAfter: ["steps", steps.length - 1] },
});
link(previous, "add-end");