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

297 lines
19 KiB
Vue

<script setup lang="ts">
import { describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Label } from "@/components/ui/label";
import { computed, ref } from "vue";
import { ChevronDown, CircleHelp, Plus, Trash2 } from "@lucide/vue";
import { parse, stringify } from "yaml";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { SuggestInput } from "@/components/ui/suggest-input";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { addBranch, branchingOf, deleteBranch, renameBranch, earlierStepIDs, replaceStep, stepAt, declaredSpecs, type InputSpec, type StepPath, type StepRecord } from "./workflow-edit";
import type { WorkflowDefinitionEntry } from "@/stores/workflows";
import { inputValue } from "@/tasks/work-request";
import OptionSelect from "@/components/OptionSelect.vue";
import WorkflowPicker from "./WorkflowPicker.vue";
import { stepControlsProblem, settingsProblem, type SettingsSchema, type StepTypeInfo } from "./workflow-yaml";
const props = defineProps<{ yaml: string; path: StepPath; vocabulary: StepTypeInfo[]; workflows: WorkflowDefinitionEntry[]; modelAliases: string[] }>();
const emit = defineEmits<{ "update:yaml": [string] }>();
const step = computed<StepRecord>(() => stepAt(props.yaml, props.path) ?? {});
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 {
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 = describeError(error, errors.common.unknown);
}
}
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>) : {},
);
const earlier = computed(() => earlierStepIDs(props.yaml, props.path));
const flowProblem = computed(() => stepControlsProblem(step.value));
const problem = computed(() =>
info.value?.settings && step.value.settings ? settingsProblem(step.value.settings, info.value.settings, "settings") : "",
);
type Kind = "workflow" | "select" | "text" | "line" | "boolean" | "number" | "lines" | "yaml";
const LEAD = ["mission", "workflow", "message", "body", "plan", "then", "status", "detail", "run", "rules"];
const longText = /mission|body|detail|plan|rules/;
function kindOf(key: string, schema: SettingsSchema): Kind {
if ((["workflow.call", "workflow.handoff"].includes(type.value) && key === "workflow") || (type.value === "workflow.approve" && key === "then")) return "workflow";
if (type.value === "agent.run" && key === "model") return "select";
if (schema.type === "string") return schema.enum ? "select" : longText.test(key) ? "text" : "line";
if (schema.type === "boolean") return "boolean";
if (schema.type === "integer" || schema.type === "number") return "number";
if (schema.type === "array" && schema.items?.type === "string") return "lines";
return "yaml";
}
// The setting that says what the step does leads, on its own; everything else
// waits behind More.
const fields = computed(() => {
const entries = Object.entries(info.value?.settings?.properties ?? {})
.filter(([key]) => type.value !== "workflow.call" || !["inputs", "outputs"].includes(key))
.map(([key, schema]) => ({ key, schema, kind: kindOf(key, schema), options: type.value === "agent.run" && key === "model" ? props.modelAliases : (schema.enum ?? []) }));
const lead = entries.filter((field) => LEAD.includes(field.key) && field.kind !== "boolean").sort((a, b) => LEAD.indexOf(a.key) - LEAD.indexOf(b.key))[0];
const rest = entries.filter((field) => field !== lead);
return {
lead,
compact: rest.filter((field) => ["workflow", "select", "line", "number", "boolean"].includes(field.kind)),
long: rest.filter((field) => ["text", "lines", "yaml"].includes(field.kind)),
};
});
const more = ref(!fields.value.lead && !branching.value);
const choices = (options: string[]) => [{ value: "", label: "Default" }, ...options.map((option) => ({ value: option, label: option }))];
function write(next: StepRecord): void {
// id and type lead, the way a step is read.
const { id, type: stepType, ...rest } = next;
emit("update:yaml", replaceStep(props.yaml, props.path, { id, type: stepType, ...rest }));
}
function setField(key: string, value: unknown): void {
write({ ...step.value, [key]: value });
}
function setSetting(key: string, value: unknown): void {
const next = { ...settings.value, [key]: value };
if (type.value === "workflow.call" && key === "wait" && value !== true) delete next.outputs;
write({ ...step.value, settings: next });
}
function setTarget(key: string, value: string): void {
const next = { ...settings.value, [key]: value };
if (type.value === "workflow.call" && value !== settings.value[key]) {
delete next.inputs;
delete next.outputs;
}
write({ ...step.value, settings: next });
}
const callee = computed(() => props.workflows.find((entry) => entry.name === settings.value.workflow));
const callInputs = computed(() => declaredSpecs(callee.value?.yaml ?? "", "inputs"));
const callOutputs = computed(() => declaredSpecs(callee.value?.yaml ?? "", "outputs"));
const callerInputs = computed(() => declaredSpecs(props.yaml, "inputs"));
const callerOutputs = computed(() => declaredSpecs(props.yaml, "outputs"));
const inputMap = computed(() => (settings.value.inputs ?? {}) as Record<string, unknown>);
const outputMap = computed(() => (settings.value.outputs ?? {}) as Record<string, string>);
const isReference = (value: unknown) => typeof value === "string" && value.startsWith("inputs.");
const structured = (spec: InputSpec) => ["object", "array"].includes(spec.type ?? "");
const inputText = (name: string) => inputMap.value[name] === undefined ? "" : String(inputMap.value[name]);
function setCallInput(name: string, value: string, inputType?: string): void {
setSetting("inputs", { ...inputMap.value, [name]: value === "" ? undefined : isReference(value) ? value : inputValue(value, inputType ?? "string") });
}
const matching = (list: [string, InputSpec][], spec: InputSpec, prefix: string) =>
list.filter(([, other]) => other.type === spec.type || other.type === "any" || spec.type === "any").map(([key]) => ({ value: `${prefix}.${key}`, label: key }));
// A reference goes into the text setting last focused: that is how this step
// is connected to an earlier step's result.
const focused = ref<string | null>(null);
function reference(id: string): void {
const key = focused.value ?? fields.value.lead?.key;
if (!key) return;
const current = typeof settings.value[key] === "string" ? (settings.value[key] as string) : "";
const token = `{{ steps.${id}.summary }}`;
setSetting(key, current ? `${current.trimEnd()} ${token}` : token);
}
const yamlErrors = ref<Record<string, string>>({});
function setYamlSetting(key: string, text: string): void {
try {
setSetting(key, text.trim() ? parse(text) : undefined);
yamlErrors.value = { ...yamlErrors.value, [key]: "" };
} catch (error) {
yamlErrors.value = { ...yamlErrors.value, [key]: describeError(error, errors.common.unknown).split("\n")[0] };
}
}
const asYaml = (value: unknown) => (value === undefined ? "" : stringify(value).trimEnd());
const label = (key: string, schema: SettingsSchema) =>
schema.title ?? key.replaceAll("_", " ").replace(/^./, (c) => c.toUpperCase());
const text = (key: string) => (typeof settings.value[key] === "string" ? (settings.value[key] as string) : "");
const ON_FAILURE = [{ value: "", label: "Park the run" }, { value: "continue", label: "Continue" }];
</script>
<template>
<div class="space-y-4 px-3 py-3">
<Alert v-if="problem" variant="destructive"><AlertDescription>{{ problem }}</AlertDescription></Alert>
<section v-if="branching" class="space-y-3">
<Label v-if="type === 'switch'" class="block space-y-1.5">
<span class="text-caption font-medium text-fg-muted">Switch on</span>
<SuggestInput :model-value="branching.on" class="font-mono" placeholder="steps.assess.result.fit" :options="earlier.map((id) => `steps.${id}.result.`)" @change="setOn(($event.target as HTMLInputElement).value.trim())" />
</Label>
<div class="text-caption font-medium text-fg-muted">{{ type === "switch" ? "Cases" : "Branches" }}</div>
<div v-for="name in branches" :key="name" class="flex items-center gap-2">
<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="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>
<Alert v-if="branchError" variant="destructive"><AlertDescription>{{ branchError }}</AlertDescription></Alert>
</section>
<section v-if="fields.lead" class="space-y-1.5">
<div class="flex items-center gap-1 text-caption font-medium text-fg-muted" :title="fields.lead.schema.description">
{{ label(fields.lead.key, fields.lead.schema) }}
<CircleHelp v-if="fields.lead.schema.description" class="size-3 text-fg-subtle" />
</div>
<WorkflowPicker v-if="fields.lead.kind === 'workflow'" :editable="type !== 'workflow.call'" :value="text(fields.lead.key)" :workflows="workflows" :label="label(fields.lead.key, fields.lead.schema)" @pick="setTarget(fields.lead.key, $event)" />
<OptionSelect v-else-if="fields.lead.kind === 'select'" class="w-full" :model-value="text(fields.lead.key)" :options="choices(fields.lead.options)" :aria-label="label(fields.lead.key, fields.lead.schema)" @update:model-value="setSetting(fields.lead.key, $event || undefined)" />
<Textarea
v-else-if="fields.lead.kind === 'text'"
:model-value="text(fields.lead.key)"
:aria-label="label(fields.lead.key, fields.lead.schema)"
class="min-h-32 text-label leading-relaxed"
@focus="focused = fields.lead.key"
@update:model-value="setSetting(fields.lead.key, String($event))"
/>
<Input
v-else
:model-value="text(fields.lead.key)"
:aria-label="label(fields.lead.key, fields.lead.schema)"
@focus="focused = fields.lead.key"
@update:model-value="setSetting(fields.lead.key, String($event))"
/>
<div v-if="earlier.length && fields.lead.kind !== 'select'" class="flex flex-wrap items-center gap-1 pt-0.5">
<span class="text-caption text-fg-subtle">Insert</span>
<Button v-for="id in earlier" :key="id" type="button" variant="outline" size="xs" class="font-mono" :title="`{{ steps.${id}.summary }}`" @click="reference(id)">{{ id }}</Button>
</div>
</section>
<!-- Only the chevron moves: a filled trigger changed the row's weight and
read as a different control once open. -->
<Button type="button" variant="ghost" size="xs" class="-ml-2 text-fg-muted aria-expanded:bg-transparent" :aria-expanded="more" @click="more = !more">
<ChevronDown data-icon="inline-start" class="transition-transform" :class="!more && '-rotate-90'" />More
</Button>
<template v-if="more">
<section v-if="fields.compact.length" class="divide-y divide-border rounded-md border border-border">
<div v-for="field in fields.compact" :key="field.key" class="flex min-h-10 items-center gap-3 px-3 py-1.5">
<span class="flex flex-1 items-center gap-1 text-label" :title="field.schema.description">
{{ label(field.key, field.schema) }}
<CircleHelp v-if="field.schema.description" class="size-3 text-fg-subtle" />
</span>
<WorkflowPicker v-if="field.kind === 'workflow'" :editable="type !== 'workflow.call'" class="max-w-48" :value="text(field.key)" :workflows="workflows" :label="label(field.key, field.schema)" @pick="setTarget(field.key, $event)" />
<Switch v-else-if="field.kind === 'boolean'" :model-value="settings[field.key] === true" :aria-label="label(field.key, field.schema)" @update:model-value="setSetting(field.key, $event || undefined)" />
<OptionSelect v-else-if="field.kind === 'select'" class="w-40" :model-value="text(field.key)" :options="choices(field.options)" :aria-label="label(field.key, field.schema)" @update:model-value="setSetting(field.key, $event || undefined)" />
<Input
v-else-if="field.kind === 'number'"
type="number"
class="h-8 w-24 text-right text-label"
:model-value="(settings[field.key] as number | undefined) ?? ''"
:aria-label="label(field.key, field.schema)"
@update:model-value="(value) => setSetting(field.key, String(value) === '' ? undefined : Number(String(value)))"
/>
<Input v-else class="h-8 w-40 text-label" :model-value="text(field.key)" :aria-label="label(field.key, field.schema)" @focus="focused = field.key" @update:model-value="(value) => setSetting(field.key, String(value))" />
</div>
</section>
<template v-if="type === 'workflow.call' && callee">
<section v-if="callInputs.length" class="space-y-3">
<div class="text-caption font-medium text-fg-muted">Inputs</div>
<div v-for="[name, spec] in callInputs" :key="name" class="space-y-1.5">
<div class="text-label">{{ name }}<span v-if="spec.required" class="text-danger"> *</span><span class="ml-2 text-caption text-fg-subtle">{{ spec.type }}</span></div>
<OptionSelect
v-if="!structured(spec)"
class="w-full"
:aria-label="`${name} source`"
:model-value="isReference(inputMap[name]) ? 'input' : 'value'"
:options="[{ value: 'value', label: 'Value' }, { value: 'input', label: 'Caller input' }]"
@update:model-value="setCallInput(name, $event === 'input' ? 'inputs.' : '')"
/>
<OptionSelect v-if="isReference(inputMap[name]) || structured(spec)" class="w-full" :aria-label="name" placeholder="Choose input" :model-value="inputText(name) === 'inputs.' ? '' : inputText(name)" :options="matching(callerInputs, spec, 'inputs')" @update:model-value="setCallInput(name, $event)" />
<OptionSelect v-else-if="spec.type === 'bool'" class="w-full" :aria-label="name" :model-value="inputText(name)" :options="[{ value: '', label: 'Unset' }, { value: 'true', label: 'True' }, { value: 'false', label: 'False' }]" @update:model-value="setCallInput(name, $event, spec.type)" />
<Input v-else :aria-label="name" :type="spec.type === 'number' ? 'number' : 'text'" step="any" :model-value="inputText(name)" @update:model-value="setCallInput(name, String($event), spec.type)" />
</div>
</section>
<section v-if="callOutputs.length" class="space-y-3">
<div class="text-caption font-medium text-fg-muted">Outputs</div>
<div v-for="[name, spec] in callOutputs" :key="name" class="space-y-1.5">
<div class="text-label">{{ name }}<span class="ml-2 text-caption text-fg-subtle">{{ spec.type }}</span></div>
<OptionSelect class="w-full" :aria-label="`${name} output`" :disabled="settings.wait !== true" :model-value="outputMap[name] ?? ''" :options="[{ value: '', label: 'Do not publish' }, ...matching(callerOutputs, spec, 'outputs')]" @update:model-value="setSetting('outputs', { ...outputMap, [name]: $event || undefined })" />
</div>
</section>
</template>
<section v-for="field in fields.long" :key="field.key" class="space-y-1.5">
<div class="flex items-center gap-1 text-caption font-medium text-fg-muted" :title="field.schema.description">
{{ label(field.key, field.schema) }}
<CircleHelp v-if="field.schema.description" class="size-3 text-fg-subtle" />
</div>
<Textarea v-if="field.kind === 'text'" :model-value="text(field.key)" :aria-label="label(field.key, field.schema)" class="min-h-20 text-label" @focus="focused = field.key" @update:model-value="setSetting(field.key, String($event))" />
<Textarea
v-else-if="field.kind === 'lines'"
:model-value="Array.isArray(settings[field.key]) ? (settings[field.key] as string[]).join('\n') : ''"
:aria-label="label(field.key, field.schema)"
class="min-h-16 font-mono text-caption"
placeholder="One per line"
@change="setSetting(field.key, ($event.target as HTMLTextAreaElement).value.split('\n').map((line) => line.trim()).filter(Boolean))"
/>
<template v-else>
<Textarea :model-value="asYaml(settings[field.key])" :aria-label="label(field.key, field.schema)" class="min-h-24 font-mono text-caption" placeholder="YAML" @change="setYamlSetting(field.key, ($event.target as HTMLTextAreaElement).value)" />
<span v-if="yamlErrors[field.key]" class="text-caption text-danger">{{ yamlErrors[field.key] }}</span>
</template>
</section>
<section class="space-y-1.5">
<Alert v-if="flowProblem" variant="destructive"><AlertDescription>{{ flowProblem }}</AlertDescription></Alert>
<div class="divide-y divide-border rounded-md border border-border">
<Label class="flex min-h-10 items-center gap-3 px-3 py-1.5">
<span class="flex-1 text-label">Run only when</span>
<Input
class="h-8 w-48 font-mono text-caption"
placeholder="inputs.enabled"
:aria-invalid="flowProblem && flowProblem.startsWith('when') ? true : undefined"
:model-value="(step.when as string) ?? ''"
@update:model-value="(value) => setField('when', String(value))"
/>
</Label>
<Label class="flex min-h-10 items-center gap-3 px-3 py-1.5">
<span class="flex-1 text-label">If it fails</span>
<OptionSelect class="w-36" aria-label="If it fails" :model-value="(step.on_failure as string) ?? ''" :options="ON_FAILURE" @update:model-value="setField('on_failure', $event || undefined)" />
</Label>
</div>
</section>
</template>
</div>
</template>