feat(workflow): serve which workflows start each one; the trigger card stops re-deriving it (#1960)
This commit is contained in:
7 files changed
+122
-48
No files matched your search
@@ -0,0 +1,80 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
)
|
||||
|
||||
// StartedBy reports, for each workflow named in sources (id to YAML), the
|
||||
// other workflows whose steps start it. It reads the same settings the engine
|
||||
// follows: a call's workflow, a handoff's target (or every value an agent
|
||||
// result's enum allows when the target is templated from one), and an
|
||||
// approval's then. A definition that does not parse starts nothing.
|
||||
func StartedBy(sources map[string]string) map[string][]task.Starter {
|
||||
type edge struct {
|
||||
target string
|
||||
starter task.Starter
|
||||
}
|
||||
seen := map[edge]bool{}
|
||||
starters := map[string][]task.Starter{}
|
||||
for _, id := range slices.Sorted(maps.Keys(sources)) {
|
||||
var definition YAMLDefinition
|
||||
if err := yaml.Unmarshal([]byte(sources[id]), &definition); err != nil {
|
||||
continue
|
||||
}
|
||||
// The visitor never fails, so walkSteps has no error to report.
|
||||
_ = walkSteps(definition.Steps, id, func(_ string, step StepRecord) error {
|
||||
for target, via := range stepTargets(definition, step) {
|
||||
e := edge{target: target, starter: task.Starter{Workflow: id, Via: via}}
|
||||
if target == id || seen[e] {
|
||||
continue
|
||||
}
|
||||
seen[e] = true
|
||||
starters[target] = append(starters[target], e.starter)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
// Map order would reorder the list between reads; sorted, it holds still.
|
||||
for _, list := range starters {
|
||||
slices.SortFunc(list, func(a, b task.Starter) int {
|
||||
return strings.Compare(a.Workflow+string(a.Via), b.Workflow+string(b.Via))
|
||||
})
|
||||
}
|
||||
return starters
|
||||
}
|
||||
|
||||
// stepTargets is every workflow one step can start, with how it starts it.
|
||||
func stepTargets(definition YAMLDefinition, step StepRecord) map[string]task.StartedVia {
|
||||
switch step.Type {
|
||||
case WorkflowCallStepName:
|
||||
settings, err := decodeCallSettings(step)
|
||||
if err != nil || strings.TrimSpace(settings.Workflow) == "" {
|
||||
return nil
|
||||
}
|
||||
return map[string]task.StartedVia{strings.TrimSpace(settings.Workflow): task.StartedViaCall}
|
||||
case HandoffStepName, ApproveStepName:
|
||||
target, ok, err := controlTarget(step)
|
||||
if err != nil || !ok || target == "" {
|
||||
return nil
|
||||
}
|
||||
via := task.StartedViaHandoff
|
||||
if step.Type == ApproveStepName {
|
||||
via = task.StartedViaApprove
|
||||
}
|
||||
if !referencePattern.MatchString(target) {
|
||||
return map[string]task.StartedVia{target: via}
|
||||
}
|
||||
targets := map[string]task.StartedVia{}
|
||||
for _, name := range targetEnum(definition, target) {
|
||||
targets[name] = via
|
||||
}
|
||||
return targets
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -236,8 +236,30 @@ type Definition struct {
|
||||
// editor can offer the inputs to assign and whether to name a repository.
|
||||
Inputs map[string]InputSpec `json:"inputs,omitempty"`
|
||||
Repository RepositoryMode `json:"repository,omitempty"`
|
||||
// StartedBy lists the other workflows whose steps start this one.
|
||||
StartedBy []Starter `json:"started_by,omitempty"`
|
||||
}
|
||||
|
||||
// Starter is a workflow whose steps start another, and the step kind that
|
||||
// does it.
|
||||
type Starter struct {
|
||||
Workflow string `json:"workflow"`
|
||||
Via StartedVia `json:"via"`
|
||||
}
|
||||
|
||||
// StartedVia is how one workflow starts another.
|
||||
type StartedVia string
|
||||
|
||||
const (
|
||||
// StartedViaCall is a workflow.call step.
|
||||
StartedViaCall StartedVia = "call"
|
||||
// StartedViaHandoff is a workflow.handoff step, including one whose
|
||||
// target an agent picks from a fixed set.
|
||||
StartedViaHandoff StartedVia = "handoff"
|
||||
// StartedViaApprove is a workflow.approve step's then target.
|
||||
StartedViaApprove StartedVia = "approve"
|
||||
)
|
||||
|
||||
// HasRepository reports whether the task works on a repository. A task a
|
||||
// binding started for a workflow with repository none (or optional, with no
|
||||
// repository named) has neither owner nor repo and runs in a scratch
|
||||
|
||||
@@ -339,9 +339,14 @@ func (a *workflowsAPI) workflowDefinitions(ctx context.Context) ([]task.Definiti
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sources := make(map[string]string, len(collection.Definitions))
|
||||
for _, entry := range collection.Definitions {
|
||||
sources[entry.ID] = entry.YAML
|
||||
}
|
||||
startedBy := workflow.StartedBy(sources)
|
||||
definitions := make([]task.Definition, 0, len(collection.Definitions))
|
||||
for _, entry := range collection.Definitions {
|
||||
definition := task.Definition{ID: entry.ID, Name: entry.ID, Origin: "database", Enabled: enablement.Enabled(org.OrgFromContext(ctx), entry.ID), Repository: task.RepositoryRequired}
|
||||
definition := task.Definition{ID: entry.ID, Name: entry.ID, Origin: "database", Enabled: enablement.Enabled(org.OrgFromContext(ctx), entry.ID), Repository: task.RepositoryRequired, StartedBy: startedBy[entry.ID]}
|
||||
if iface, err := task.ParseWorkflowInterface(entry.YAML); err == nil {
|
||||
definition.Inputs, definition.Repository = iface.Inputs, iface.RepositoryMode()
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, toRef, watch } from "vue";
|
||||
import { CircleAlert, Copy, RotateCcw, Trash2 } from "@lucide/vue";
|
||||
import { isSending, setTurnHooks } from "@/chat/state";
|
||||
|
||||
@@ -71,7 +71,7 @@ const collection = computed(() => workflows.collection);
|
||||
const selected = defineModel<string>("selected", { required: true });
|
||||
const emit = defineEmits<{ duplicate: [id: string] }>();
|
||||
// Stage statistics are read by the page with the rest of the workflow stats.
|
||||
defineProps<{ stageStats: StageStats[]; statsKnown: boolean; statsError: string }>();
|
||||
const props = defineProps<{ stageStats: StageStats[]; statsKnown: boolean; statsError: string; startedBy: { workflow: string; via: string }[] }>();
|
||||
const id = ref("");
|
||||
const yaml = ref("");
|
||||
const loadedYaml = ref("");
|
||||
@@ -117,7 +117,7 @@ async function restartFrom(from: string): Promise<void> {
|
||||
restarting.value = false;
|
||||
}
|
||||
}
|
||||
const { triggers, reload: reloadTriggers, error: triggersError } = useWorkflowTriggers(selected);
|
||||
const { triggers, reload: reloadTriggers, error: triggersError } = useWorkflowTriggers(selected, toRef(() => props.startedBy));
|
||||
|
||||
const { revisions, error: historyError, loaded: historyLoaded, reload: reloadHistory } = useWorkflowHistory(selected);
|
||||
const historyRevision = ref(0);
|
||||
|
||||
@@ -267,7 +267,7 @@ const rate = (deliveredRuns = 0, total = 0) => (total ? deliveredRuns / total :
|
||||
<Badge v-if="provenance" variant="outline" class="shrink-0">{{ provenance }}</Badge>
|
||||
<ApplyStatusRows kind="workflow-definitions" compact />
|
||||
</header>
|
||||
<WorkflowEditor v-model:selected="selected" v-model:view="view" v-model:run-open="runOpen" @duplicate="duplicate" :stage-stats="stages" :stats-known="statsKnown" :stats-error="error ?? ''">
|
||||
<WorkflowEditor v-model:selected="selected" v-model:view="view" v-model:run-open="runOpen" @duplicate="duplicate" :stage-stats="stages" :started-by="data.definitions?.find((d) => d.id === selected)?.started_by ?? []" :stats-known="statsKnown" :stats-error="error ?? ''">
|
||||
<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>
|
||||
|
||||
@@ -31,6 +31,8 @@ export interface WorkflowDefinition {
|
||||
inputs?: Record<string, { type: string; required?: boolean }>;
|
||||
/** none, optional or required; a workflow that declares none needs a repository. */
|
||||
repository?: string;
|
||||
/** The other workflows whose steps start this one, and how. */
|
||||
started_by?: { workflow: string; via: string }[];
|
||||
}
|
||||
|
||||
/** One table row: a definition, its statistics, or both. */
|
||||
|
||||
@@ -3,7 +3,6 @@ import { parse } from "yaml";
|
||||
|
||||
import { api, describeError } from "@/lib/api";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { branchingOf } from "./workflow-edit.ts";
|
||||
import { useSettingsStore } from "@/stores/settings";
|
||||
import { useWorkflowsStore } from "@/stores/workflows";
|
||||
import type { Binding } from "@/bindings/binding-draft";
|
||||
@@ -22,7 +21,8 @@ export interface TriggerSources {
|
||||
routes: Record<string, string>;
|
||||
bindings: Binding[];
|
||||
playbooks: { id: string; yaml: string }[];
|
||||
definitions: { id: string; yaml: string }[];
|
||||
/** The workflows that start this one, as the server works them out. */
|
||||
startedBy: { workflow: string; via: string }[];
|
||||
/** Schedules by id, to name schedule triggers. */
|
||||
schedules: { id: string; name: string }[];
|
||||
}
|
||||
@@ -92,53 +92,18 @@ export function triggersFor(id: string, sources: TriggerSources): WorkflowTrigge
|
||||
const labels = Array.isArray(trigger.labels) ? trigger.labels.join(", ") : "";
|
||||
triggers.push({ kind: "playbook", label: playbook.id, detail: [trigger.kind, labels].filter(Boolean).join(" · ") });
|
||||
}
|
||||
for (const definition of sources.definitions) {
|
||||
if (definition.id === id) continue;
|
||||
const how = startsVia(parseQuietly(definition.yaml), id);
|
||||
if (how) triggers.push({ kind: "workflow", label: definition.id, detail: how });
|
||||
for (const starter of sources.startedBy) {
|
||||
triggers.push({ kind: "workflow", label: starter.workflow, detail: STARTED_VIA[starter.via] ?? starter.via });
|
||||
}
|
||||
return triggers;
|
||||
}
|
||||
|
||||
/** How a workflow's steps start the target: a call, a handoff (including one
|
||||
* whose target an earlier agent picks from a fixed list), or an approval. */
|
||||
function startsVia(value: unknown, target: string): string {
|
||||
const steps = isMapping(value) && Array.isArray(value.steps) ? value.steps : [];
|
||||
const all = steps.flatMap((step) =>
|
||||
branchingOf(step)?.branches.flatMap(([, branch]) => branch) ?? [step],
|
||||
);
|
||||
for (const step of all) {
|
||||
if (!isMapping(step) || !isMapping(step.settings)) continue;
|
||||
const settings = step.settings;
|
||||
switch (step.type) {
|
||||
case "workflow.call":
|
||||
if (settings.workflow === target) return "calls it";
|
||||
break;
|
||||
case "workflow.handoff":
|
||||
if (settings.workflow === target || resultChoices(all, settings.workflow).includes(target)) return "hands off to it";
|
||||
break;
|
||||
case "workflow.approve":
|
||||
if (settings.then === target) return "runs it once approved";
|
||||
break;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/** The fixed choices an agent's result field allows, for a reference like
|
||||
* {{ steps.classify.result.workflow }}. */
|
||||
function resultChoices(steps: unknown[], reference: unknown): string[] {
|
||||
const match = typeof reference === "string" ? /\{\{\s*steps\.([\w-]+)\.result\.([\w-]+)\s*\}\}/.exec(reference) : null;
|
||||
if (!match) return [];
|
||||
const source = steps.find((step) => isMapping(step) && step.id === match[1]);
|
||||
const result = isMapping(source) && isMapping(source.settings) ? source.settings.result : undefined;
|
||||
const field = isMapping(result) && isMapping(result.properties) ? result.properties[match[2]] : undefined;
|
||||
return isMapping(field) && Array.isArray(field.enum) ? field.enum.map(String) : [];
|
||||
}
|
||||
// The words for the server's start kinds.
|
||||
const STARTED_VIA: Record<string, string> = { call: "calls it", handoff: "hands off to it", approve: "runs it once approved" };
|
||||
|
||||
/** The triggers of the workflow named id, from the routes and definitions the
|
||||
* control plane serves, the stored playbooks, and the event bindings. */
|
||||
export function useWorkflowTriggers(id: Ref<string>) {
|
||||
export function useWorkflowTriggers(id: Ref<string>, startedBy: Readonly<Ref<{ workflow: string; via: string }[]>>) {
|
||||
const store = useSettingsStore();
|
||||
const workflows = useWorkflowsStore();
|
||||
const bindings = ref<TriggerSources["bindings"]>([]);
|
||||
@@ -166,7 +131,7 @@ export function useWorkflowTriggers(id: Ref<string>) {
|
||||
routes: workflows.intakeRoutes,
|
||||
bindings: bindings.value,
|
||||
playbooks: (store.stateFor("eda-playbooks").resource?.value as { playbooks?: TriggerSources["playbooks"] } | undefined)?.playbooks ?? [],
|
||||
definitions: workflows.collection.definitions,
|
||||
startedBy: startedBy.value,
|
||||
schedules: schedules.value,
|
||||
}),
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user