wip(ui/workflows): visual editor on the binary's API (#2061)

This commit is contained in:
sam committed 2026-11-22 11:48:13 +11:00
1 parent a5826156a3
commit c1b4ba2b6b
27 files changed
+895 -1308

No files matched your search

+2 -2
View File
@@ -608,13 +608,13 @@ func (m *Module) capabilities(ctx context.Context, _ *struct{}) (*httpapi.Reply[
sections := map[string]bool{"chat": signedIn, "memory": signedIn}
for _, name := range []string{
"settings", "events", "workflows", "runs", "credentials", "extensions", "secret_engines", "models", "controls", "memory_admin",
"home", "system_status", "org_config",
"home", "system_status", "org_config", "workflow_editor",
} {
sections[name] = p.InstanceAdmin()
}
for _, name := range []string{
"tasks", "work_requests", "logs", "skills", "curators", "channels",
"captures", "mappings", "bindings", "workflow_editor", "extension_catalogue", "model_aliases",
"captures", "mappings", "bindings", "extension_catalogue", "model_aliases",
"task_execution", "organisations", "tools", "plugins", "container_runtime", "agent_profiles",
"org_agents", "org_audit", "org_usage", "org_work_intake",
} {
+88 -11
View File
@@ -185,7 +185,7 @@ async function request<T = unknown>(
export const api = {
// The archie binary's module API; the wire types are below the object.
runs: (limit = 200) => request<Run[]>("/api/runs" + qs({ limit })),
runs: (limit = 200, workflow?: string) => request<Run[]>("/api/runs" + qs({ limit, workflow })),
run: (id: string) => request<RunTrail>(`/api/runs/${encodeURIComponent(id)}`),
/** Queues a parked run again from the step that parked it, or from `from`. */
retryRun: (id: string, from?: string) =>
@@ -212,9 +212,32 @@ export const api = {
workflowList: () => request<WorkflowVersion[]>("/api/workflows"),
workflow: (name: string, version?: number) =>
request<WorkflowVersion>(`/api/workflows/${encodeURIComponent(name)}` + qs({ version })),
putWorkflow: (name: string, body: string) =>
request<WorkflowVersion>(`/api/workflows/${encodeURIComponent(name)}`, { method: "PUT", body: { body } }),
workflowStepTypes: () => request<{ name: string; needs_repository: boolean; settings?: unknown }[]>("/api/workflow-step-types"),
/** Publishes a document as the next version; `expectedVersion` makes the save fail with 409 when another is stored. */
putWorkflow: (name: string, body: string, expectedVersion?: number) =>
request<WorkflowVersion>(`/api/workflows/${encodeURIComponent(name)}`, { method: "PUT", body: { body, expected_version: expectedVersion } }),
deleteWorkflow: (name: string) => request<void>(`/api/workflows/${encodeURIComponent(name)}`, { method: "DELETE", parse: false }),
setWorkflowEnabled: (name: string, enabled: boolean) =>
request<WorkflowVersion>(`/api/workflows/${encodeURIComponent(name)}/enabled`, { method: "PUT", body: { enabled } }),
runWorkflow: (name: string, input?: Record<string, unknown>) =>
request<Run>(`/api/workflows/${encodeURIComponent(name)}/runs`, { method: "POST", body: { input } }),
workflowDrafts: () => request<WorkflowDraft[]>("/api/workflow-drafts"),
/** A workflow's draft, or null when it has none. */
workflowDraft: async (name: string) => {
try {
return await request<WorkflowDraft>(`/api/workflows/${encodeURIComponent(name)}/draft`);
} catch (cause) {
if (cause instanceof ApiError && cause.status === 404) return null;
throw cause;
}
},
/** Saves a draft; `revision` is the one last read, 0 for none, and a stale one fails with 409. */
putWorkflowDraft: (name: string, body: string, revision: number) =>
request<WorkflowDraft>(`/api/workflows/${encodeURIComponent(name)}/draft`, { method: "PUT", body: { body, revision } }),
discardWorkflowDraft: (name: string) => request<void>(`/api/workflows/${encodeURIComponent(name)}/draft`, { method: "DELETE", parse: false }),
testWorkflowDraft: (name: string, input?: Record<string, unknown>) =>
request<Run>(`/api/workflows/${encodeURIComponent(name)}/draft/test-run`, { method: "POST", body: { input } }),
workflowStats: () => request<WorkflowStats[]>("/api/workflow-stats"),
workflowStepTypes: () => request<StepType[]>("/api/workflow-step-types"),
extensionKinds: () => request<ExtensionKindInfo[]>("/api/extension-kinds"),
extensions: (kind: ExtensionKind) => request<Extension[]>(`/api/${kind}`),
acceptExtension: (kind: ExtensionKind, name: string, body: ExtensionInput) =>
@@ -450,12 +473,6 @@ export const api = {
setup: <T = unknown>() => request<T>("/api/setup"),
capabilities: <T = unknown>() => request<T>("/api/capabilities"),
workflows: <T = unknown>() => request<T>("/api/workflows"),
workflowEnabled: (id: string, enabled: boolean) =>
request<void>(`/api/workflows/${encodeURIComponent(id)}/enabled`, {
method: "PUT",
body: { enabled },
parse: false,
}),
checkRepository: <T = unknown>(input: { owner: string; repository: string; identity_id: string }) => request<T>("/api/control-plane/resources/repository-policies/check", { method: "POST", body: input, timeoutMs: 35000 }),
repositories: <T = unknown>() => request<T>("/api/repositories"),
workRequest: <T = unknown>(workRequest: Payload) =>
@@ -702,6 +719,8 @@ export interface Run {
created_at: string;
finished_at?: string;
result?: unknown;
/** A test run of a draft, which changes nothing. */
dry?: boolean;
}
/** A channel account linked to the signed-in account. */
@@ -826,7 +845,28 @@ export interface RunEntry {
output?: string;
error?: string;
unknown?: boolean;
tool_calls?: { name: string; input: string }[];
/** The top-level step of the definition that made the entry. */
step?: string;
tool_calls?: { id?: string; name: string; input: string }[];
/** What a step recorded, when it is not an agent's own call. */
value?: unknown;
reasoning?: string;
/** The model request exactly as sent: messages, tools and sampling settings. */
request?: { messages?: { role: string; content?: string }[] };
usage?: { prompt_tokens?: number; completion_tokens?: number; cached_tokens?: number };
finish_reason?: string;
input?: string;
call_id?: string;
}
/** How far one top-level step of a run's definition got. */
export interface RunStage {
name: string;
type: string;
state: "pending" | "running" | "waiting" | "succeeded" | "failed" | "skipped" | "cancelled";
started_at?: string;
ended_at?: string;
error?: string;
}
export interface RunTrail {
@@ -834,6 +874,9 @@ export interface RunTrail {
origin?: { event_id?: string; source?: string; type?: string; trigger?: string; received_at?: string };
actions?: RunAction[];
entries?: RunEntry[];
/** The document the run executes: its version, or the draft a test run tested. */
definition?: string;
stages: RunStage[];
}
export interface EventRecord {
@@ -899,6 +942,40 @@ export interface WorkflowVersion {
steps?: string[];
created_at: string;
created_by?: string;
/** False for a workflow nothing may start. */
enabled: boolean;
}
/** The unpublished edit of a workflow. */
export interface WorkflowDraft {
name: string;
body: string;
/** The published version it began from, 0 for a workflow not yet published. */
base_version: number;
/** Counts the draft's writes; a save names the one it last read. */
revision: number;
updated_by: string;
updated_at: string;
}
export interface WorkflowStats {
workflow: string;
total: number;
succeeded: number;
/** Runs that failed, parked or were declined. */
failed: number;
/** Runs that have not ended. */
active: number;
/** The share of ended runs that succeeded; absent until one has ended. */
success_rate?: number;
last_run: { id: string; state: string; at: string };
}
export interface StepType {
name: string;
title: string;
needs_repository: boolean;
settings?: unknown;
}
export type ExtensionGroup = "platform" | "integration" | "agent";
-8
View File
@@ -107,14 +107,6 @@ export const routes: RouteRecordRaw[] = [
{
path: "/workflows/:id",
name: "workflow",
component: () => import("@/workflows/WorkflowPage.vue"),
meta: { label: "Workflow", nav: false, navPath: "/workflows", section: "workflows" },
},
// The visual editor, with drafts, test runs and per-step statistics; it
// needs workflow drafts and run stages the binary does not serve yet.
{
path: "/workflow-editor/:id",
name: "workflow-editor",
component: WorkflowEditorPage,
meta: { label: "Workflow", nav: false, navPath: "/workflows", section: "workflow_editor" },
},
+1 -44
View File
@@ -3,10 +3,8 @@ import { Alert, AlertDescription } from "@/components/ui/alert";
import ApplyStatusRows from "./ApplyStatusRows.vue";
import KindGate from "./KindGate.vue";
import { computed, onMounted, ref } from "vue";
import { RotateCcw } from "@lucide/vue";
import { storeToRefs } from "pinia";
import { Button } from "@/components/ui/button";
import PageHeader from "@/base/PageHeader.vue";
import { DurationInput, formatGoDuration, parseGoDuration } from "@/components/ui/duration-input";
import { Field, FieldContent, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
@@ -17,18 +15,7 @@ import {
NumberFieldIncrement,
NumberFieldInput,
} from "@/components/ui/number-field";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { cloneControlPlaneValue, resourcesForPage, useSettingsStore } from "@/stores/settings";
import { restoreShippedDefinitions, useWorkflowsStore } from "@/stores/workflows";
import { resourcesForPage, useSettingsStore } from "@/stores/settings";
import DraftHint from "./DraftHint.vue";
import HistoryLink from "./HistoryLink.vue";
@@ -71,12 +58,6 @@ function durationSeconds(text: string): number | undefined {
const ms = parseGoDuration(text);
return ms === null ? undefined : Math.round(ms / 1000);
}
const workflows = useWorkflowsStore();
const confirmRestore = ref(false);
async function restoreWorkflows(): Promise<void> {
await workflows.save(cloneControlPlaneValue(restoreShippedDefinitions(workflows.collection, workflows.shipped)));
}
</script>
<template>
@@ -170,29 +151,5 @@ async function restoreWorkflows(): Promise<void> {
</limitsForm.Field>
</FieldGroup>
<FieldGroup v-if="workflows.shipped.definitions.length" class="@container/field-group">
<Field orientation="responsive">
<FieldContent>
<FieldLabel>Workflows</FieldLabel>
<FieldDescription>Resets every shipped workflow. Custom workflows are kept.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Button variant="outline" size="sm" :disabled="workflows.state.saving" @click="confirmRestore = true"><RotateCcw data-icon="inline-start" />Restore default</Button>
</div>
</Field>
</FieldGroup>
<AlertDialog v-model:open="confirmRestore">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Restore default workflows?</AlertDialogTitle>
<AlertDialogDescription>Edits to shipped workflows are discarded.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction @click="restoreWorkflows">Restore</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Alert v-if="workflows.state.error" variant="destructive"><AlertDescription>{{ workflows.state.error }}</AlertDescription></Alert>
</div>
</template>
+120 -84
View File
@@ -1,104 +1,140 @@
import { defineStore } from "pinia";
import { computed } from "vue";
import { computed, reactive, ref } from "vue";
import { errors } from "../copy/errors/index.ts";
import { api, ApiError, describeError } from "../lib/api.ts";
import type { StepTypeInfo } from "../workflows/workflow-yaml.ts";
import { useSettingsStore } from "./settings.ts";
const KIND = "workflow-definitions";
const DRAFTS = "workflow-drafts";
export interface WorkflowDefinitionEntry {
id: string;
yaml: string;
/** The published version the yaml is. */
version: number;
enabled: boolean;
}
export interface WorkflowDefinitionCollection {
definitions: WorkflowDefinitionEntry[];
}
export function upsertWorkflowDefinition(
collection: WorkflowDefinitionCollection,
entry: WorkflowDefinitionEntry,
): WorkflowDefinitionCollection {
const found = collection.definitions.some(({ id }) => id === entry.id);
return {
definitions: found
? collection.definitions.map((definition) =>
definition.id === entry.id ? entry : definition,
)
: [...collection.definitions, entry],
};
/** A workflow's unpublished edit. */
export interface WorkflowDraftEntry {
id: string;
yaml: string;
/** The draft's revision as last read; a save names it. */
revision: number;
/** The published version the draft began from, 0 for a workflow not yet published. */
baseVersion: number;
}
// restoreShippedDefinitions resets every shipped workflow to what archie ships
// and keeps the operator's custom ones, which archie has no copy of to restore.
export function restoreShippedDefinitions(
collection: WorkflowDefinitionCollection,
shipped: WorkflowDefinitionCollection,
): WorkflowDefinitionCollection {
return shipped.definitions.reduce(upsertWorkflowDefinition, collection);
}
export function removeWorkflowDefinition(
collection: WorkflowDefinitionCollection,
id: string,
): WorkflowDefinitionCollection {
return {
definitions: collection.definitions.filter(
(definition) => definition.id !== id,
),
};
}
function parse<T>(json: string | undefined, pick: (value: Record<string, unknown>) => unknown, fallback: T): T {
if (!json) return fallback;
try {
return (pick(JSON.parse(json)) as T | undefined) ?? fallback;
} catch {
return fallback;
}
}
/** The workflow definitions: one control-plane resource, with the shipped
* copies and step vocabulary its catalog entry serves. */
/** The published workflows, their drafts and the step vocabulary the server serves. */
export const useWorkflowsStore = defineStore("workflows", () => {
const settings = useSettingsStore();
const descriptor = computed(() => settings.catalog.find((resource) => resource.kind === KIND));
const definitions = ref<WorkflowDefinitionEntry[]>([]);
const drafts = ref<WorkflowDraftEntry[]>([]);
const stepTypes = ref<StepTypeInfo[]>([]);
const loaded = ref(false);
const error = ref("");
const saving = ref(false);
const draftState = reactive({ saving: false, error: "", conflict: false });
const state = computed(() => settings.stateFor(KIND));
const collection = computed<WorkflowDefinitionCollection>(
() => (state.value.resource?.value as WorkflowDefinitionCollection | undefined) ?? { definitions: [] },
);
/** The shipped definitions the catalog offers as "restore shipped". */
const shipped = computed(() =>
parse<WorkflowDefinitionCollection>(descriptor.value?.defaults_json, (value) => value, { definitions: [] }),
);
/** The registered workflow step types, served in the definitions schema. */
const stepTypes = computed(() =>
parse<StepTypeInfo[]>(descriptor.value?.schema_json, (value) => value["x-step-types"], []),
);
const collection = computed<WorkflowDefinitionCollection>(() => ({ definitions: definitions.value }));
const state = computed(() => ({ resource: loaded.value ? collection.value : undefined, saving: saving.value, error: error.value }));
/** Unpublished edits by workflow id; only a test run runs a draft. */
const drafts = computed(
() => ((settings.stateFor(DRAFTS).resource?.value as { drafts?: WorkflowDefinitionEntry[] } | undefined)?.drafts ?? []),
);
/** Writes a workflow's draft, or removes it when yaml is undefined. */
function putDraft(id: string, yaml: string | undefined): Promise<boolean> {
const rest = drafts.value.filter((draft) => draft.id !== id);
if (yaml === undefined && rest.length === drafts.value.length) return Promise.resolve(true);
return settings.replace(DRAFTS, { drafts: yaml === undefined ? rest : [...rest, { id, yaml }] });
async function load(): Promise<void> {
try {
const [published, held, types] = await Promise.all([api.workflowList(), api.workflowDrafts(), api.workflowStepTypes()]);
definitions.value = published.map((w) => ({ id: w.name, yaml: w.body, version: w.version, enabled: w.enabled }));
drafts.value = held.map(draftEntry);
stepTypes.value = types as StepTypeInfo[];
loaded.value = true;
error.value = "";
} catch (cause) {
error.value = describeError(cause, errors.common.unknown);
}
}
return {
state,
drafts,
draftState: computed(() => settings.stateFor(DRAFTS)),
putDraft,
reloadDrafts: () => settings.loadResource(DRAFTS),
error: computed(() => settings.catalogError || state.value.error),
collection,
shipped,
stepTypes,
load: settings.load,
save: (next: WorkflowDefinitionCollection) => settings.replace(KIND, next),
};
async function reloadDrafts(): Promise<void> {
try {
drafts.value = (await api.workflowDrafts()).map(draftEntry);
} catch (cause) {
draftState.error = describeError(cause, errors.common.unknown);
}
}
// Writes to one workflow's draft run one after another, each naming the
// revision the one before it returned.
let writes: Promise<unknown> = Promise.resolve();
/** Writes a workflow's draft, or discards it when yaml is undefined. A draft
* changed elsewhere since it was read is not overwritten: the write fails
* and draftState.conflict says why. */
function putDraft(id: string, yaml: string | undefined): Promise<boolean> {
const write = writes.then(() => writeDraft(id, yaml));
writes = write.catch(() => undefined);
return write;
}
async function writeDraft(id: string, yaml: string | undefined): Promise<boolean> {
draftState.saving = true;
draftState.error = "";
draftState.conflict = false;
try {
const held = drafts.value.find((draft) => draft.id === id);
if (yaml === undefined) {
if (held) await api.discardWorkflowDraft(id);
drafts.value = drafts.value.filter((draft) => draft.id !== id);
return true;
}
const saved = draftEntry(await api.putWorkflowDraft(id, yaml, held?.revision ?? 0));
drafts.value = [...drafts.value.filter((draft) => draft.id !== id), saved];
return true;
} catch (cause) {
if (cause instanceof ApiError && cause.status === 409) draftState.conflict = true;
else draftState.error = describeError(cause, errors.common.unknown);
return false;
} finally {
draftState.saving = false;
}
}
/** Publishes yaml as the next version of workflow id. `expected` is the
* version it was edited from, so a version published since is not overwritten. */
async function publish(id: string, yaml: string, expected: number): Promise<boolean> {
saving.value = true;
error.value = "";
try {
const w = await api.putWorkflow(id, yaml, expected);
const entry = { id: w.name, yaml: w.body, version: w.version, enabled: w.enabled };
definitions.value = [...definitions.value.filter((d) => d.id !== id), entry].sort((a, b) => a.id.localeCompare(b.id));
drafts.value = drafts.value.filter((draft) => draft.id !== id);
return true;
} catch (cause) {
error.value = describeError(cause, errors.common.unknown);
return false;
} finally {
saving.value = false;
}
}
/** Deletes a published workflow with its draft; the server refuses while anything still names it. */
async function remove(id: string): Promise<boolean> {
saving.value = true;
error.value = "";
try {
await api.deleteWorkflow(id);
definitions.value = definitions.value.filter((d) => d.id !== id);
drafts.value = drafts.value.filter((draft) => draft.id !== id);
return true;
} catch (cause) {
error.value = describeError(cause, errors.common.unknown);
return false;
} finally {
saving.value = false;
}
}
return { state, drafts, draftState, putDraft, reloadDrafts, error, collection, stepTypes, load, publish, remove };
});
function draftEntry(draft: { name: string; body: string; revision: number; base_version: number }): WorkflowDraftEntry {
return { id: draft.name, yaml: draft.body, revision: draft.revision, baseVersion: draft.base_version };
}
+37 -45
View File
@@ -1,13 +1,12 @@
<script setup lang="ts">
import { ArrowUpRightIcon, BotIcon, BrainIcon, CircleAlertIcon, CircleCheckIcon, FlagIcon, FlaskConicalIcon, FoldVerticalIcon, GlobeIcon, ScrollTextIcon, SparklesIcon, SquareTerminalIcon, TargetIcon } from "@lucide/vue";
import { createReusableTemplate } from "@vueuse/core";
import { computed, onUnmounted, ref, watch } from "vue";
import { computed } from "vue";
import { Bubble, BubbleContent } from "@/components/ui/bubble";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Message, MessageContent } from "@/components/ui/message";
import { Spinner } from "@/components/ui/spinner";
import {
Trace,
TraceCollapsible,
@@ -19,12 +18,9 @@ import {
TraceTitle,
} from "@/components/ui/trace";
import ChatMarkdown from "@/chat/ChatMarkdown.vue";
import { api } from "@/lib/api";
import type { RunEntry } from "@/lib/api";
import { errors } from "@/copy/errors";
import { keepValue } from "@/lib/keep-unchanged";
import { useLiveResource } from "@/stores/session";
import { duration } from "@/tasks/timeline-event";
import type { TaskEvent } from "@/tasks/task-run";
/** One agent_transcript entry, as the State Store records it. */
interface Entry {
@@ -91,8 +87,9 @@ function toolView(tool: Entry) {
}
const [DefineTool, ToolView] = createReusableTemplate<{ tool: Entry; view: ReturnType<typeof toolView> }>();
/** One step's agent conversations for one attempt, oldest first. */
const props = defineProps<{ taskId: number | string; attempt: number; match: (event: TaskEvent) => boolean; running: boolean }>();
/** One step's agent conversation, oldest first: the entries the run trail
* attributes to the step. */
const props = defineProps<{ entries: RunEntry[] }>();
interface Step { model: Entry; tools: Entry[] }
type Row =
@@ -104,31 +101,38 @@ interface Conversation { key: string; label: string; rows: Row[]; steps: number;
const [DefineConversation, ConversationView] = createReusableTemplate<{ conversation: Conversation }>();
const events = ref<TaskEvent[]>();
const failed = ref(false);
let generation = 0;
let timer: ReturnType<typeof setInterval> | undefined;
async function load(): Promise<void> {
const current = ++generation;
try {
const view = await api.taskTranscript<{ entries?: TaskEvent[] }>(String(props.taskId), { attempt: props.attempt });
if (current !== generation) return;
events.value = keepValue(events.value, view.entries ?? []);
failed.value = false;
} catch {
if (current === generation) failed.value = true;
/** The trail's model and tool entries as the conversation they record. The
* first model request carries the system prompt and the mission. */
function conversationEntries(list: RunEntry[]): Entry[] {
const out: Entry[] = [];
let first = true;
for (const entry of list) {
if (entry.kind === "model") {
if (first) {
for (const message of entry.request?.messages ?? []) {
if (message.role === "system" || message.role === "user") out.push({ seq: entry.seq, kind: message.role, text: message.content });
}
first = false;
}
out.push({
seq: entry.seq,
kind: "model",
text: entry.text,
reasoning: entry.reasoning,
tool_calls: entry.tool_calls,
error: entry.error,
finish_reason: entry.finish_reason,
usage: entry.usage,
});
} else if (entry.kind === "compaction") {
out.push({ seq: entry.seq, kind: "compaction", error: entry.error, usage: entry.usage });
} else if (entry.kind === "tool") {
out.push({ seq: entry.seq, kind: "tool", call_id: entry.call_id, tool: entry.name, args: entry.input, output: entry.output, error: entry.error });
}
}
return out;
}
watch(() => [props.taskId, props.attempt], () => { events.value = undefined; failed.value = false; void load(); }, { immediate: true });
watch(() => props.running, (running) => {
clearInterval(timer);
if (running) timer = setInterval(() => void load(), 3000);
}, { immediate: true });
useLiveResource("tasks", () => void load(), 1000);
onUnmounted(() => { generation++; clearInterval(timer); });
function usage(entry: Entry): string {
const u = entry.usage;
const parts = [];
@@ -169,19 +173,9 @@ function conversation(key: string, label: string, entries: Entry[]): Conversatio
return { key, label, rows, steps, tools: tools.length, failed: tools.filter((tool) => tool.error).length };
}
// Each agent in the step (a fan-out branch, or a retry) keeps its own
// conversation, numbered from 1.
const conversations = computed(() => {
const byAgent = new Map<string, Entry[][]>();
for (const event of (events.value ?? []).filter(props.match)) {
const key = [event.data?.branch, event.stage].filter(Boolean).join("/");
const entry = event.data as unknown as Entry;
const runs = byAgent.get(key) ?? [];
if (!runs.length || entry.seq === 1) runs.push([]);
runs.at(-1)!.push(entry);
byAgent.set(key, runs);
}
return [...byAgent.entries()].flatMap(([label, runs]) => runs.map((entries, i) => conversation(`${label}#${i}`, label, entries)));
const recorded = conversationEntries(props.entries);
return recorded.some((entry) => entry.kind === "model") ? [conversation("agent", "agent", recorded)] : [];
});
</script>
@@ -293,9 +287,7 @@ const conversations = computed(() => {
</div>
</DefineConversation>
<p v-if="failed" role="alert" class="text-danger">{{ errors.workflows.transcript.notLoaded }}</p>
<Spinner v-else-if="!events" />
<Empty v-else-if="!conversations.length"><EmptyHeader><EmptyTitle>No transcript recorded</EmptyTitle></EmptyHeader></Empty>
<Empty v-if="!conversations.length"><EmptyHeader><EmptyTitle>No transcript recorded</EmptyTitle></EmptyHeader></Empty>
<ConversationView v-else-if="conversations.length === 1" :conversation="conversations[0]!" />
<Trace v-else>
<TraceCollapsible v-for="c in conversations" :key="c.key">
+106 -25
View File
@@ -1,47 +1,128 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { FlaskConical, Play } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import NewTaskForm from "@/tasks/NewTaskForm.vue";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { errors } from "@/copy/errors";
import { api, describeError } from "@/lib/api";
import { declaredSpecs } from "./workflow-edit";
defineProps<{
const props = defineProps<{
workflow: string;
/** The document whose inputs the run is asked for. */
yaml: string;
/** Runs the draft as a test, in which nothing that changes something runs. */
test?: boolean;
disabled?: boolean;
/** Why it is disabled, shown on the button. */
disabledReason?: string;
/** The unsaved definition to test-run; absent runs the stored one. */
draft?: string;
/** Called before a test run, which runs the saved draft. */
prepare?: () => Promise<boolean>;
/** Shows the button as an icon, for a list row. */
icon?: boolean;
}>();
const emit = defineEmits<{ started: [taskId: number] }>();
// A controlled open lets the toolbar's one menu run this when its own button
// does not fit.
const emit = defineEmits<{ started: [runId: string] }>();
const open = defineModel<boolean>("open", { default: false });
function started(taskId: number): void {
open.value = false;
emit("started", taskId);
const specs = computed(() => declaredSpecs(props.yaml, "inputs"));
const values = ref<Record<string, string | boolean>>({});
const busy = ref(false);
const failure = ref("");
watch(open, (now) => {
if (!now) return;
failure.value = "";
values.value = Object.fromEntries(specs.value.map(([name, spec]) => [name, spec.type === "bool" ? false : spec.type === "object" ? "{}" : spec.type === "array" ? "[]" : ""]));
});
/** The typed value of an input, or why the text isn't one. */
function typed(name: string, type: string, text: string | boolean): unknown {
if (type === "bool") return text === true;
const raw = String(text).trim();
if (type === "string") return raw;
if (type === "number") {
const number = Number(raw);
if (!raw || Number.isNaN(number)) throw new Error(`${name} is a number`);
return number;
}
try {
return JSON.parse(raw);
} catch {
throw new Error(`${name} is not valid JSON`);
}
}
async function start(): Promise<void> {
busy.value = true;
failure.value = "";
try {
const input: Record<string, unknown> = {};
for (const [name, spec] of specs.value) {
const text = values.value[name] ?? "";
if (!spec.required && text === "") continue;
input[name] = typed(name, spec.type ?? "any", text);
}
if (props.test && props.prepare && !(await props.prepare())) throw new Error("The draft couldn't be saved");
const run = props.test ? await api.testWorkflowDraft(props.workflow, input) : await api.runWorkflow(props.workflow, input);
open.value = false;
emit("started", run.id);
} catch (cause) {
failure.value = describeError(cause, errors.common.unknown);
} finally {
busy.value = false;
}
}
// A workflow that asks for nothing starts at once; one that does asks first.
async function click(): Promise<void> {
if (specs.value.length) open.value = true;
else await start();
}
</script>
<template>
<span class="inline-flex flex-col items-end" @click.stop @keydown.stop>
<Button
type="button"
:size="icon ? 'icon-sm' : 'sm'"
:variant="icon ? 'ghost' : 'outline'"
:aria-label="`${test ? 'Test' : 'Run'} ${workflow}`"
:disabled="disabled || busy"
:title="disabled ? disabledReason : test ? 'Runs this draft once; nothing that changes something runs' : `Run ${workflow}`"
@click="click"
>
<Spinner v-if="busy && !open" data-icon="inline-start" />
<component :is="test ? FlaskConical : Play" v-else :data-icon="icon ? undefined : 'inline-start'" />
<span v-if="!icon">{{ test ? "Test" : "Run" }}</span>
</Button>
<p v-if="failure && !open" role="alert" class="mt-1 max-w-64 text-caption text-danger">{{ failure }}</p>
</span>
<Dialog v-model:open="open">
<DialogTrigger as-child>
<Button
type="button"
size="sm"
variant="outline"
:aria-label="`${draft !== undefined ? 'Test' : 'Run'} ${workflow}`"
:disabled="disabled"
:title="disabled ? disabledReason : draft !== undefined ? 'Runs this draft once; deliveries are recorded, not sent' : undefined"
>
<component :is="draft !== undefined ? FlaskConical : Play" data-icon="inline-start" /> <span>{{ draft !== undefined ? "Test" : "Run" }}</span></Button>
</DialogTrigger>
<DialogContent class="sm:max-w-[640px]">
<DialogContent class="sm:max-w-[560px]">
<DialogHeader>
<DialogTitle>{{ draft !== undefined ? "Test" : "Run" }} {{ workflow }}</DialogTitle>
<DialogTitle>{{ test ? "Test" : "Run" }} {{ workflow }}</DialogTitle>
</DialogHeader>
<NewTaskForm v-if="open" :workflow="workflow" :draft="draft" @started="started" @cancel="open = false" />
<form id="run-workflow" class="flex min-h-0 flex-col gap-3 overflow-y-auto" @submit.prevent="start">
<div v-for="[name, spec] in specs" :key="name" class="space-y-1.5">
<Label :for="`run-${name}`" class="flex items-center gap-2 text-caption font-medium text-fg-muted">
<span class="font-mono">{{ name }}</span>
<span class="text-fg-subtle">{{ spec.type ?? "any" }}{{ spec.required ? "" : ", optional" }}</span>
</Label>
<Switch v-if="spec.type === 'bool'" :id="`run-${name}`" :model-value="values[name] === true" @update:model-value="values[name] = $event" />
<Textarea v-else-if="['object', 'array', 'any', undefined].includes(spec.type)" :id="`run-${name}`" v-model="values[name] as string" :rows="6" class="font-mono text-label" spellcheck="false" />
<Input v-else :id="`run-${name}`" v-model="values[name] as string" :type="spec.type === 'number' ? 'number' : 'text'" :required="spec.required" />
</div>
<p v-if="failure" role="alert" class="text-caption text-danger">{{ failure }}</p>
</form>
<DialogFooter>
<Button type="submit" form="run-workflow" :disabled="busy"><Spinner v-if="busy" data-icon="inline-start" />{{ test ? "Test" : "Run" }}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</template>
+2 -31
View File
@@ -3,12 +3,11 @@ 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, useId } from "vue";
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 { DurationInput } from "@/components/ui/duration-input";
import { Input } from "@/components/ui/input";
import { SuggestInput } from "@/components/ui/suggest-input";
import { Switch } from "@/components/ui/switch";
@@ -20,7 +19,6 @@ import OptionSelect from "@/components/OptionSelect.vue";
import WorkflowPicker from "./WorkflowPicker.vue";
import { stepControlsProblem, settingsProblem, type SettingsSchema, type StepTypeInfo } from "./workflow-yaml";
const uid = useId();
const props = defineProps<{ yaml: string; path: StepPath; vocabulary: StepTypeInfo[]; workflows: WorkflowDefinitionEntry[]; modelAliases: string[] }>();
const emit = defineEmits<{ "update:yaml": [string] }>();
@@ -93,12 +91,6 @@ function write(next: StepRecord): void {
function setField(key: string, value: unknown): void {
write({ ...step.value, [key]: value });
}
// Retry is one object: a field edit merges into it so attempts and backoff do
// not clobber each other, and clearing both drops the key.
function setRetry(next: { attempts?: number; backoff?: string }): void {
const policy = { ...(step.value.retry as { attempts?: number; backoff?: string }), ...next };
setField("retry", policy.attempts === undefined && !policy.backoff ? undefined : { ...policy, attempts: policy.attempts ?? 1 });
}
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;
@@ -153,7 +145,7 @@ const asYaml = (value: unknown) => (value === undefined ? "" : stringify(value).
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 task" }, { value: "continue", label: "Continue" }];
const ON_FAILURE = [{ value: "", label: "Park the run" }, { value: "continue", label: "Continue" }];
</script>
<template>
@@ -297,27 +289,6 @@ const ON_FAILURE = [{ value: "", label: "Park the task" }, { value: "continue",
<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>
<Label class="flex min-h-10 items-center gap-3 px-3 py-1.5">
<span class="flex-1 text-label">Attempts</span>
<Input
type="number"
min="1"
max="10"
placeholder="1"
class="h-8 w-20 text-right text-label"
:model-value="(step.retry as { attempts?: number } | undefined)?.attempts ?? ''"
@update:model-value="(value) => setRetry({ attempts: String(value) === '' ? undefined : Number(String(value)) })"
/>
</Label>
<div class="flex min-h-10 items-center gap-3 px-3 py-1.5">
<Label :for="`${uid}-backoff`" class="flex-1 text-label">Retry backoff</Label>
<DurationInput
:id="`${uid}-backoff`"
:model-value="(step.retry as { backoff?: string } | undefined)?.backoff ?? ''"
:units="['s', 'm', 'h']"
@update:model-value="setRetry({ backoff: $event || undefined })"
/>
</div>
</div>
</section>
</template>
+25 -140
View File
@@ -1,107 +1,30 @@
<script setup lang="ts">
import { Item, ItemGroup } from "@/components/ui/item";
import { Button } from "@/components/ui/button";
import { computed, onUnmounted, ref, watch } from "vue";
import { api } from "@/lib/api";
import { errors } from "@/copy/errors";
import { keepValue } from "@/lib/keep-unchanged";
import { useLiveResource } from "@/stores/session";
import { computed, ref } from "vue";
import { Badge } from "@/components/ui/badge";
import ChangeCapture from "@/tasks/ChangeCapture.vue";
import TaskLogs from "@/tasks/TaskLogs.vue";
import AgentTranscript from "./AgentTranscript.vue";
import { Button } from "@/components/ui/button";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
import type { RunEntry } from "@/lib/api";
import { duration } from "@/lib/format";
import { stageStatusMeta } from "@/tasks/stage-rail";
import { describeTimelineEvent, duration } from "@/tasks/timeline-event";
import type { ChangesState, LogState, TaskEvent, TaskRecord } from "@/tasks/task-run";
import AgentTranscript from "./AgentTranscript.vue";
import type { StageRun } from "./workflow-graph";
const props = defineProps<{ task: TaskRecord; attempt: number; stage: StageRun; stages: StageRun[] }>();
const events = ref<TaskEvent[]>([]);
const changes = ref<ChangesState>();
const logOpen = ref(false);
const logs = ref<LogState | null>();
const activityError = ref("");
const changesError = ref("");
const expanded = ref(false);
/** What one step of the watched run did: how it ended, what it recorded and,
* for an agent, the conversation. */
const props = defineProps<{ stage: StageRun; entries: RunEntry[] }>();
const transcriptOpen = ref(false);
const key = computed(() => `${props.task.id}/${props.attempt}/${props.stage.id ?? props.stage.name}`);
let generation = 0;
let timer: ReturnType<typeof setInterval> | undefined;
let loading = false;
let queued = false;
async function refresh(): Promise<void> {
if (!props.attempt) return;
if (loading) { queued = true; return; }
loading = true;
const current = generation;
const id = String(props.task.id);
const params = { attempt: props.attempt };
const results = await Promise.allSettled([
api.taskDebug<{ events?: TaskEvent[] }>(id, params),
api.taskChanges<ChangesState>(id, params),
api.taskLogs<LogState>(id, { ...params, stage: props.stage.name }),
]);
if (current !== generation) return;
const [activity, capture, log] = results;
activityError.value = activity.status === "rejected" ? errors.workflows.stepRun.activityNotLoaded : "";
if (activity.status === "fulfilled") events.value = keepValue(events.value, activity.value.events ?? []);
changesError.value = capture.status === "rejected" ? errors.workflows.stepRun.changesNotLoaded : "";
if (capture.status === "fulfilled") changes.value = keepValue(changes.value, capture.value);
logs.value = log.status === "fulfilled" ? keepValue(logs.value, log.value) : null;
loading = false;
if (queued) { queued = false; void refresh(); }
}
watch(key, () => {
generation++;
loading = false;
queued = false;
events.value = [];
changes.value = undefined;
logs.value = undefined;
activityError.value = "";
changesError.value = "";
expanded.value = false;
transcriptOpen.value = false;
void refresh();
}, { immediate: true });
watch(() => props.stage.status, (status) => {
clearInterval(timer);
void refresh();
// Logs can arrive between task events; read them while the stage is active.
if (status === "running") timer = setInterval(() => void refresh(), 2000);
}, { immediate: true });
useLiveResource("tasks", () => void refresh(), 300);
onUnmounted(() => { generation++; clearInterval(timer); });
const meta = computed(() => stageStatusMeta(props.stage.status));
const names = computed(() => new Set([props.stage.name, ...(props.stage.agents ?? []).map((agent) => agent.name.split("/").at(-1) ?? agent.name)]));
const nextStart = computed(() => props.stages.find((stage) => stage.name === props.stage.name && stage.started_at && props.stage.started_at && stage.started_at > props.stage.started_at)?.started_at);
function inWindow(at: string | number | Date | undefined): boolean {
if (!props.stage.started_at || !at) return props.stages.filter((stage) => stage.name === props.stage.name).length === 1;
const time = new Date(at).getTime();
return time >= Date.parse(props.stage.started_at) && (!props.stage.finished_at || time <= Date.parse(props.stage.finished_at)) && (!nextStart.value || time < Date.parse(nextStart.value));
const talked = computed(() => props.entries.some((entry) => entry.kind === "model"));
// An agent's own steps are the transcript; every other recorded step is shown by name.
const recorded = computed(() => props.entries.filter((entry) => entry.kind === "step"));
function shown(entry: RunEntry): string {
if (entry.error) return entry.error;
const value = entry.value;
return typeof value === "string" ? value : JSON.stringify(value, null, 2);
}
function inStep(event: TaskEvent): boolean {
if (Number(event.attempt) !== props.attempt) return false;
if (event.data?.step_id != null) return Number(event.data.step_id) === props.stage.id;
return names.value.has(event.stage ?? "") && inWindow(event.at);
}
const activity = computed(() => events.value.filter(inStep).sort((a, b) => String(a.at ?? "").localeCompare(String(b.at ?? ""))));
const recorded = computed(() => activity.value.filter((event) => event.kind === "delivery_recorded"));
const groups = computed(() => {
const agents = props.stage.agents ?? [];
const branches = new Set(["", ...agents.map((agent) => agent.name.includes("/") ? agent.name.split("/")[0]! : ""), ...activity.value.map((event) => String(event.data?.branch ?? ""))]);
return [...branches].map((branch) => ({
branch,
agents: agents.filter((agent) => (agent.name.includes("/") ? agent.name.split("/")[0] : "") === branch),
reports: activity.value.filter((event) => event.kind === "agent_finish" && String(event.data?.branch ?? "") === branch),
tools: activity.value.filter((event) => event.kind === "tool_call" && String(event.data?.branch ?? "") === branch),
})).filter((group) => group.agents.length || group.reports.length || group.tools.length);
});
const captures = computed(() => (changes.value?.captures ?? []).filter((capture) => capture.stage === props.stage.name && inWindow(capture.captured_at)));
const scopedLogs = computed(() => logs.value ? { ...logs.value, entries: (logs.value.entries ?? []).filter((entry) => inWindow(entry.time)) } : logs.value);
</script>
<template>
@@ -109,55 +32,17 @@ const scopedLogs = computed(() => logs.value ? { ...logs.value, entries: (logs.v
<div class="flex items-center gap-2">
<Badge :variant="meta.kind">{{ meta.label }}</Badge>
<span v-if="stage.duration_ms != null" class="text-caption text-fg-muted">{{ duration(stage.duration_ms) }}</span>
<span class="ml-auto text-caption text-fg-muted">Attempt {{ attempt }}</span>
</div>
<p v-if="stage.error" class="rounded-md bg-danger-soft p-3 break-words whitespace-pre-wrap text-danger">{{ stage.error }}</p>
<p v-if="activityError" role="alert" class="text-danger">{{ activityError }}</p>
<section v-for="group in groups" :key="group.branch" class="space-y-3">
<h3 v-if="group.branch" class="font-medium">{{ group.branch }}</h3>
<p v-else-if="groups.length > 1" class="text-caption text-fg-muted">Activity without branch attribution</p>
<div v-for="agent in group.agents" :key="agent.id" class="space-y-1">
<div class="flex items-center gap-2 text-caption"><span class="font-mono">{{ agent.name.split('/').at(-1) }}</span><Badge :variant="stageStatusMeta(agent.status).kind">{{ agent.status }}</Badge></div>
<p v-if="agent.detail" class="break-words whitespace-pre-wrap">{{ agent.detail }}</p>
</div>
<div v-for="(report, i) in group.reports" :key="i" class="space-y-1">
<p v-if="report.detail && !group.agents.some((agent) => agent.detail === report.detail)" class="break-words whitespace-pre-wrap">{{ report.detail }}</p>
<p class="text-caption text-fg-muted">Agent's own report · {{ describeTimelineEvent(report).title }}</p>
</div>
<div v-if="group.tools.length" class="space-y-1">
<h4 class="text-caption font-medium uppercase text-fg-muted">Tool calls · {{ group.tools.length }}</h4>
<ItemGroup class="gap-0">
<Item v-for="(tool, i) in expanded ? group.tools : group.tools.slice(0, 12)" :key="i" as="li" variant="outline" size="xs" class="block">
<div class="flex justify-between gap-2 text-caption"><span class="font-mono">{{ tool.data?.tool }}</span><span :class="tool.data?.failed ? 'text-danger' : 'text-fg-muted'">{{ tool.data?.failed ? 'Failed' : 'Returned' }}</span></div>
<p v-if="tool.detail" class="mt-1 break-words whitespace-pre-wrap text-caption text-fg-muted">{{ tool.detail }}</p>
</Item>
</ItemGroup>
<Button v-if="group.tools.length > 12" type="button" variant="link" size="xs" class="px-0" @click="expanded = !expanded">{{ expanded ? 'Show first 12' : `Show all ${group.tools.length}` }}</Button>
</div>
<p v-if="group.reports.length" class="text-caption text-fg-muted">{{ group.reports.map((report) => describeTimelineEvent(report).detail).filter(Boolean).join(' · ') }}</p>
<p v-else-if="group.agents.length" class="text-caption text-fg-muted">{{ group.agents.reduce((sum, agent) => sum + agent.tokens_used, 0).toLocaleString() }} tokens recorded</p>
</section>
<section v-if="stage.agents?.length || groups.some((group) => group.reports.length)" class="space-y-3">
<section v-if="talked" class="space-y-3">
<Button type="button" variant="link" size="xs" class="px-0 text-caption font-medium uppercase text-fg-muted" :aria-expanded="transcriptOpen" @click="transcriptOpen = !transcriptOpen">Transcript</Button>
<AgentTranscript v-if="transcriptOpen" :task-id="task.id" :attempt="attempt" :match="inStep" :running="stage.status === 'running'" />
<AgentTranscript v-if="transcriptOpen" :entries="entries" />
</section>
<section v-if="recorded.length" class="space-y-1">
<h3 class="text-caption font-medium uppercase text-fg-muted">Not delivered in a test run</h3>
<ul class="divide-y divide-border rounded-md border border-border">
<li v-for="(event, i) in recorded" :key="i" class="px-3 py-2 text-caption break-words whitespace-pre-wrap">{{ event.detail }}</li>
</ul>
</section>
<!-- Only a step that captured changes, or failed to read them, has this. -->
<section v-if="captures.length || changesError" class="space-y-3">
<h3 class="text-caption font-medium uppercase text-fg-muted">Captured changes</h3>
<p v-if="changesError" role="alert" class="text-danger">{{ changesError }}</p>
<ChangeCapture v-for="(capture, i) in captures" :key="i" :capture="capture" :task="task" />
</section>
<!-- The log opens on demand, like the transcript: a table this wide
crowds the card when all it needs to say is how the step went. -->
<section class="space-y-2">
<Button type="button" variant="link" size="xs" class="px-0 text-caption font-medium uppercase text-fg-muted" :aria-expanded="logOpen" @click="logOpen = !logOpen">Log</Button>
<TaskLogs v-if="logOpen" :state="scopedLogs" :attempt="attempt" :filterable="false" />
<section v-for="entry in recorded" :key="entry.seq" class="space-y-1">
<h3 class="font-mono text-caption font-medium text-fg-muted">{{ entry.name }}</h3>
<CodeBlock size="sm" :variant="entry.error ? 'destructive' : 'default'">
<CodeBlockContent wrap class="max-h-64">{{ shown(entry) }}</CodeBlockContent>
</CodeBlock>
</section>
</div>
</template>
+1 -1
View File
@@ -62,7 +62,7 @@ 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 types = computed(() => props.types ?? []);
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);
+95 -106
View File
@@ -10,11 +10,12 @@ import {
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { CircleAlert, Copy, RotateCcw, Trash2 } from "@lucide/vue";
import { CircleAlert, Copy, ExternalLink, RotateCcw, Square, Trash2 } from "@lucide/vue";
import { isSending, setTurnHooks } from "@/chat/state";
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Badge } from "@/components/ui/badge";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Spinner } from "@/components/ui/spinner";
import { MoreMenu } from "@/components/ui/more-menu";
@@ -23,30 +24,26 @@ import StepRun from "./StepRun.vue";
import { restartAt, withRuns, workflowGraph } from "./workflow-graph";
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import type { WorkflowStats } from "@/lib/api";
import { ago } from "@/lib/format";
import { statusLabel } from "@/lib/task-meta";
import { useRead } from "@/lib/use-read";
import { stateLabel } from "@/runs/state";
import StepEditor from "./StepEditor.vue";
import WorkflowSettings from "./WorkflowSettings.vue";
import TriggerSettings from "./TriggerSettings.vue";
import TriggerList from "@/events/TriggerList.vue";
import WorkflowYaml from "./WorkflowYaml.vue";
import OptionSelect from "@/components/OptionSelect.vue";
import RunWorkflowButton from "./RunWorkflowButton.vue";
import TaskRowActions from "@/tasks/TaskRowActions.vue";
import WorkflowCanvas from "./WorkflowCanvas.vue";
import WorkflowHistory from "./WorkflowHistory.vue";
import { revisionOfRun, useWorkflowHistory, type WorkflowRevision } from "./workflow-revisions";
import { deleteStep, duplicateStep, insertStep, moveStep, normalizeStepIDs, replaceStep, revertWorkflowChange, SEEDED_AGENT_ID, stepAt, stepIDs, workflowChanges, workflowField, type StepPath } from "./workflow-edit";
import { deleteStep, duplicateStep, insertStep, moveStep, normalizeStepIDs, replaceStep, revertWorkflowChange, stepAt, stepIDs, workflowChanges, type StepPath } from "./workflow-edit";
import ChangeList from "@/components/ChangeList.vue";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useWorkflowRuns } from "./workflow-runs";
import WorkflowRuns, { type StageStats } from "./WorkflowRuns.vue";
import WorkflowRuns from "./WorkflowRuns.vue";
import type { WorkflowTrigger } from "./workflow-triggers";
import { useSettingsStore } from "@/stores/settings";
import {
removeWorkflowDefinition,
upsertWorkflowDefinition,
useWorkflowsStore,
type WorkflowDefinitionCollection,
} from "@/stores/workflows";
import { useWorkflowsStore } from "@/stores/workflows";
import {
parseWorkflowYaml,
settingsProblem,
@@ -54,21 +51,16 @@ import {
validationLabel,
} from "./workflow-yaml";
const store = useSettingsStore();
const workflows = useWorkflowsStore();
const state = computed(() => workflows.state);
// Chat and agent aliases: embedding and transcription have their own purposes.
const modelAliases = computed(() =>
Object.keys((store.stateFor("model-aliases").resource?.value ?? {}) as Record<string, string>)
.filter((alias) => alias !== "embedding" && alias !== "transcription")
.sort(),
);
const models = useRead(() => api.agentModels());
onMounted(() => void models.reload());
const modelAliases = computed(() => Object.keys(models.data.value ?? {}).sort());
const collection = computed(() => workflows.collection);
// Which definition is open belongs to the page, which also lists them.
const selected = defineModel<string>("selected", { required: true });
const emit = defineEmits<{ duplicate: [id: string]; reloadTriggers: [] }>();
// Stage statistics are read by the page with the rest of the workflow stats.
const props = defineProps<{ stageStats: StageStats[]; statsKnown: boolean; statsError: string; triggers: WorkflowTrigger[]; triggersError: string }>();
const emit = defineEmits<{ duplicate: [id: string]; deleted: [] }>();
const props = defineProps<{ stats?: WorkflowStats; triggers: WorkflowTrigger[] }>();
const id = ref("");
const yaml = ref("");
const loadedYaml = ref("");
@@ -80,7 +72,7 @@ function openStepAt(path: StepPath | null): void {
}
const localError = ref("");
const { runs, error: runsError, loading: runsLoading, watched, watchedRun, stages, stagesError, attempt, pick, follow, refresh } = useWorkflowRuns(selected);
const { runs, error: runsError, loading: runsLoading, watched, watchedRun, trail, stages, stagesError, pick, follow, refresh } = useWorkflowRuns(selected);
const stepTab = ref("definition");
// A run without a pinned definition cannot be matched to the drawn steps, so
// the canvas draws the definition alone.
@@ -96,9 +88,9 @@ function toggle(key: string): void {
}
watch(watched, () => { open.value = null; restartError.value = ""; });
// A parked run restarts at a step through the retry action, keeping the
// results of the steps before it.
const restartable = computed(() => watchedRun.value?.status === "parked");
// A parked or ended run restarts at a step, keeping the results of the steps
// before it.
const restartable = computed(() => ["parked", "failed", "succeeded", "declined"].includes(watchedRun.value?.status ?? "") && !trail.value?.run.dry);
const openRestart = computed(() => restartable.value && openPath.value ? restartAt(graph.value, openPath.value) : null);
const restarting = ref(false);
const restartError = ref("");
@@ -106,7 +98,7 @@ async function restartFrom(from: string): Promise<void> {
restartError.value = "";
restarting.value = true;
try {
await api.taskAction(watched.value, "retry", { resume_from: from });
await api.retryRun(watched.value, from);
await refresh();
} catch (err) {
restartError.value = errors.workflows.editor.restartFailed(watched.value, from, describeError(err, errors.common.unknown));
@@ -114,9 +106,21 @@ async function restartFrom(from: string): Promise<void> {
restarting.value = false;
}
}
const reloadTriggers = () => emit("reloadTriggers");
const cancelling = computed(() => ["queued", "running", "waiting", "waiting_approval"].includes(watchedRun.value?.status ?? ""));
async function cancelWatched(): Promise<void> {
restartError.value = "";
try {
await api.cancelRun(watched.value);
await refresh();
} catch (err) {
restartError.value = describeError(err, errors.common.unknown);
}
}
// What the watched run recorded under one step: its transcript and results.
const entriesOf = (step: string) => (trail.value?.entries ?? []).filter((entry) => entry.step === step);
const { revisions, error: historyError, loaded: historyLoaded, reload: reloadHistory } = useWorkflowHistory(selected);
const published = computed(() => collection.value.definitions.find((entry) => entry.id === selected.value)?.version ?? 0);
const { revisions, error: historyError, loaded: historyLoaded, reload: reloadHistory } = useWorkflowHistory(selected, published);
const historyRevision = ref(0);
const historyMode = ref("yaml");
// The revision a run used, matched by the definition it pinned.
@@ -187,6 +191,8 @@ function renameAt(path: StepPath, name: string): void {
// edit, so it stops and says so instead.
const seenDraft = ref<string | undefined>();
const draftConflict = ref(false);
// The published version the open document was edited from.
const loadedVersion = ref(0);
function load(value: string): void {
const entry = collection.value.definitions.find(
(candidate) => candidate.id === value,
@@ -194,7 +200,8 @@ function load(value: string): void {
id.value = entry?.id ?? value;
seenDraft.value = workflows.drafts.find((draft) => draft.id === value)?.yaml;
draftConflict.value = false;
loadedYaml.value = seenDraft.value ?? entry?.yaml ?? `id: ${value}\nidentity: ${SEEDED_AGENT_ID}\nsteps: []\n`;
loadedVersion.value = entry?.version ?? 0;
loadedYaml.value = seenDraft.value ?? entry?.yaml ?? "steps: []\n";
yaml.value = normalizeStepIDs(loadedYaml.value);
open.value = null;
localError.value = "";
@@ -215,27 +222,21 @@ watch([collection, () => workflows.drafts], () => {
// A draft equal to the published definition is removed.
let pending: ReturnType<typeof setTimeout> | undefined;
async function writeDraft(target: string, next: string | undefined, force = false): Promise<boolean> {
for (let attempt = 0; attempt < 5; attempt++) {
const stored = workflows.drafts.find((draft) => draft.id === target)?.yaml;
if (!force && target === selected.value && stored !== seenDraft.value) {
draftConflict.value = true;
return false;
}
if (await workflows.putDraft(target, next)) {
if (target === selected.value) {
seenDraft.value = next;
draftConflict.value = false;
}
return true;
}
if (workflows.draftState.conflict) {
if (target === selected.value) draftConflict.value = true;
return false;
}
if (workflows.draftState.error) return false;
// Another write was in flight; try again once it settles.
await new Promise((resolve) => setTimeout(resolve, 300));
const stored = workflows.drafts.find((draft) => draft.id === target)?.yaml;
if (!force && target === selected.value && stored !== seenDraft.value) {
draftConflict.value = true;
return false;
}
// Replacing what another writer saved starts from the draft as stored now.
if (force) await workflows.reloadDrafts();
if (await workflows.putDraft(target, next)) {
if (target === selected.value) {
seenDraft.value = next;
draftConflict.value = false;
}
return true;
}
if (workflows.draftState.conflict && target === selected.value) draftConflict.value = true;
return false;
}
// Every edit lands in the workflow's draft shortly after it is made, so work
@@ -296,6 +297,12 @@ async function flushDraft(): Promise<void> {
unsaved = undefined;
await persistDraft(selected.value, yaml.value);
}
// A test run runs the saved draft, so the edit is written first.
async function saveDraft(): Promise<boolean> {
await flushDraft();
return workflows.drafts.find((draft) => draft.id === selected.value)?.yaml === yaml.value;
}
const enabled = computed(() => collection.value.definitions.find((entry) => entry.id === selected.value)?.enabled ?? true);
// Archie's draft replaces what the editor shows; the review then lists its
// changes against the published workflow.
async function takeProposal(): Promise<void> {
@@ -312,33 +319,16 @@ async function restorePublished(): Promise<void> {
else if (!draftConflict.value) localError.value = workflows.draftState.error || errors.workflows.editor.draftNotSaved;
}
async function save(next: WorkflowDefinitionCollection): Promise<boolean> {
localError.value = "";
return workflows.save(next);
}
async function publish(): Promise<void> {
if (publishBlocked.value || state.value.saving) return;
// The id is the one the YAML declares; renaming is editing it there.
const nextID = parsed.value.ok ? parsed.value.id : "";
if (!nextID) return;
const previous = selected.value;
// Saving replaces the entry with that id, so a rename onto another
// workflow's id would silently overwrite it.
if (previous !== nextID && collection.value.definitions.some((entry) => entry.id === nextID)) {
localError.value = `A workflow with id "${nextID}" already exists; choose another id.`;
return;
}
let next = collection.value;
if (previous && previous !== nextID)
next = removeWorkflowDefinition(next, previous);
if (
await save(upsertWorkflowDefinition(next, { id: nextID, yaml: yaml.value }))
) {
const dropped = (await dropDraft(previous)) && (previous === nextID || (await dropDraft(nextID)));
selected.value = nextID;
localError.value = "";
clearTimeout(pending);
unsaved = undefined;
if (await workflows.publish(selected.value, yaml.value, loadedVersion.value)) {
loadedYaml.value = yaml.value;
if (!dropped && !draftConflict.value) localError.value = errors.workflows.editor.draftNotRemoved;
seenDraft.value = undefined;
draftConflict.value = false;
loadedVersion.value = workflows.collection.definitions.find((entry) => entry.id === selected.value)?.version ?? loadedVersion.value;
}
}
@@ -348,16 +338,14 @@ const runOpen = defineModel<boolean>("runOpen", { default: false });
const draftOpen = ref(false);
const confirmDelete = ref(false);
const confirmDiscard = ref(false);
// A published workflow is deleted with its draft; one never published has only
// the draft to discard. The server refuses a delete while anything names it.
async function remove(): Promise<void> {
if (!selected.value) return;
if (
!(await save(removeWorkflowDefinition(collection.value, selected.value)))
)
return;
await dropDraft(selected.value);
selected.value = "";
id.value = "";
yaml.value = "";
clearTimeout(pending);
unsaved = undefined;
const done = stored.value === undefined ? await workflows.putDraft(selected.value, undefined) : await workflows.remove(selected.value);
if (done) emit("deleted");
}
// What is typed, read against the served step vocabulary (workflow-yaml.ts).
@@ -368,7 +356,7 @@ const vocabulary = computed(() => workflows.stepTypes);
// The definitions loaded but carried no step types: cards can't open and YAML
// can't be checked, which must not look like an empty, valid workflow.
const stepTypesMissing = computed(() => !!workflows.state.resource && !vocabulary.value.length);
const parsed = computed(() => parseWorkflowYaml(yaml.value, vocabulary.value));
const parsed = computed(() => parseWorkflowYaml(yaml.value, vocabulary.value, selected.value));
const stored = computed(() => collection.value.definitions.find((entry) => entry.id === selected.value)?.yaml);
const dirty = computed(() => yaml.value !== (stored.value ?? ""));
const changes = computed(() => (dirty.value ? workflowChanges(stored.value ?? "", yaml.value) : []));
@@ -406,12 +394,11 @@ function showError(path?: StepPath): void {
view.value = "canvas";
openStepAt(path);
}
const workflowSummary = computed(() => String(workflowField(canvasYaml.value, "profile") ?? ""));
const runOptions = computed(() => [
{ value: "", label: "Definition" },
...runs.value.map((run) => ({
value: String(run.id),
label: [`${run.source === "test" ? "Test" : "Run"} #${run.id}`, run.status && statusLabel(run.status), run.created_at ? ago(run.created_at) : ""].filter(Boolean).join(" · "),
label: [run.source === "test" ? "Test" : `Run ${run.id.slice(0, 8)}`, run.status && stateLabel(run.status), run.created_at ? ago(run.created_at) : ""].filter(Boolean).join(" · "),
})),
]);
</script>
@@ -425,27 +412,26 @@ const runOptions = computed(() => [
<div v-if="$slots.title" class="flex min-w-0 shrink items-center gap-2 max-lg:hidden"><slot name="title" /></div>
<TabsList class="shrink-0 justify-start">
<TabsTrigger value="canvas">Canvas</TabsTrigger>
<TabsTrigger value="yaml">YAML</TabsTrigger>
<TabsTrigger value="history">History</TabsTrigger>
<TabsTrigger v-if="stored !== undefined" value="runs">Runs <span v-if="runs.length" class="ml-1 font-mono text-caption text-fg-subtle">{{ runs.length }}</span></TabsTrigger>
</TabsList>
<div role="group" aria-label="Runs" class="workflow-run-actions ml-auto flex min-w-0 items-center gap-1 max-sm:col-span-2 max-sm:row-start-2 max-sm:ml-0">
<div v-if="stored !== undefined && (view === 'canvas' || view === 'history')" class="shrink-0">
<div v-if="view === 'canvas' || view === 'yaml' || view === 'history'" class="shrink-0">
<RunWorkflowButton
v-model:open="runOpen"
:workflow="selected"
:draft="dirty ? yaml : undefined"
:disabled="!parsed.ok"
:disabled-reason="parsed.ok ? undefined : validationLabel(parsed)"
@started="(id) => { view = 'canvas'; void follow(id); }"
:yaml="yaml"
:test="dirty || stored === undefined"
:prepare="saveDraft"
:disabled="!parsed.ok || (!dirty && stored !== undefined && !enabled)"
:disabled-reason="parsed.ok ? 'Disabled' : validationLabel(parsed)"
@started="(runId) => { view = 'canvas'; void follow(runId); }"
/>
</div>
<div v-if="runs.length && view === 'canvas'" class="flex min-w-0 items-center gap-1 max-sm:flex-1">
<OptionSelect :model-value="watched" :options="runOptions" aria-label="Run shown on the canvas" class="min-w-32 max-w-56 max-sm:w-full *:data-[slot=select-value]:block *:data-[slot=select-value]:truncate" @update:model-value="pick" />
<template v-if="watchedRun">
<!-- One run control keeps the row short; the run's other actions
are on the run, behind Open run in this menu. -->
<TaskRowActions :task="watchedRun" :only="watchedRun.actions?.slice(0, 1)" secondary class="max-md:hidden" @done="refresh" />
</template>
<Badge v-if="watchedRun?.source === 'test'" variant="outline" class="shrink-0">Test</Badge>
</div>
</div>
<div role="group" aria-label="Edit" class="workflow-edit-actions flex min-w-0 items-center gap-1 border-l pl-2 max-sm:col-start-2 max-sm:row-start-1">
@@ -464,19 +450,20 @@ const runOptions = computed(() => [
</ul>
</PopoverContent>
</Popover>
<span v-if="dirty && (view === 'canvas' || view === 'history')" class="shrink-0" :title="publishBlocked">
<span v-if="dirty && (view === 'canvas' || view === 'yaml' || view === 'history')" class="shrink-0" :title="publishBlocked">
<Button type="button" size="sm" class="disabled:bg-muted disabled:text-fg-muted disabled:opacity-100" :disabled="state.saving || !!publishBlocked" @click="publish">
<Spinner v-if="state.saving" data-icon="inline-start" />Publish</Button>
</span>
<MoreMenu>
<!-- The run's page and the version it pinned are menu items, not
row controls: the row keeps the width for the picked run. -->
<DropdownMenuItem v-if="watchedRun" as-child><RouterLink :to="`/tasks/${watchedRun.id}`">Open run</RouterLink></DropdownMenuItem>
<DropdownMenuItem v-if="watchedRun" as-child><RouterLink :to="`/runs/${watchedRun.id}`"><ExternalLink />Open run</RouterLink></DropdownMenuItem>
<DropdownMenuItem v-if="cancelling" @select="cancelWatched"><Square />Cancel run</DropdownMenuItem>
<DropdownMenuItem v-if="watchedRevision" @select="openRevision(watchedRevision.version)">Version {{ watchedRevision.version }}</DropdownMenuItem>
<DropdownMenuItem v-if="changes.length" @select="draftOpen = true">Draft changes <span class="ml-auto font-mono text-caption text-fg-subtle">{{ changes.length }}</span></DropdownMenuItem>
<DropdownMenuItem v-if="dirty" :disabled="archieWorking" @select="confirmDiscard = true"><RotateCcw />Discard changes</DropdownMenuItem>
<DropdownMenuItem v-if="stored !== undefined" @select="emit('duplicate', selected)"><Copy />Duplicate</DropdownMenuItem>
<DropdownMenuItem variant="destructive" @select="confirmDelete = true"><Trash2 />Delete workflow</DropdownMenuItem>
<DropdownMenuItem variant="destructive" @select="confirmDelete = true"><Trash2 />{{ stored === undefined ? "Discard workflow" : "Delete workflow" }}</DropdownMenuItem>
</MoreMenu>
</div>
</div>
@@ -505,8 +492,7 @@ const runOptions = computed(() => [
:readonly="!!pinnedYaml || archieWorking"
:restartable="restartable"
:problems="pinnedYaml ? undefined : nodeProblems"
:title="parsed.ok ? parsed.id : id"
:summary="workflowSummary"
:title="selected"
@toggle="toggle"
@restart="restartFrom"
@insert="insertAt"
@@ -517,14 +503,14 @@ const runOptions = computed(() => [
>
<template #body="{ data }">
<fieldset v-if="data.kind === 'workflow'" :disabled="!!pinnedYaml" class="min-w-0"><WorkflowSettings :yaml="canvasYaml" @update:yaml="yaml = $event" /></fieldset>
<fieldset v-else-if="data.kind === 'start'" :disabled="!!pinnedYaml" class="min-w-0"><TriggerSettings :yaml="canvasYaml" :triggers="props.triggers" :error="props.triggersError" @update:yaml="yaml = $event" @bound="reloadTriggers" @reload="reloadTriggers" /></fieldset>
<div v-else-if="data.kind === 'start'" class="min-w-0 p-3"><TriggerList :workflow="selected" /></div>
<template v-else-if="data.path">
<div v-if="data.run && watchedRun" class="flex items-center gap-2 border-b border-border px-3 py-2">
<Tabs v-model="stepTab"><TabsList><TabsTrigger value="run">Run</TabsTrigger><TabsTrigger value="definition">Definition</TabsTrigger></TabsList></Tabs>
<Button v-if="openRestart" type="button" size="sm" variant="outline" class="ml-auto" :disabled="restarting || openRestart.blocked" @click="restartFrom(openRestart.from)"><RotateCcw />{{ openRestart.label }}</Button>
</div>
<div v-if="data.run && watchedRun && stepTab === 'run'" class="max-h-[32rem] overflow-y-auto">
<StepRun :task="watchedRun" :attempt="attempt" :stage="data.run" :stages="stages" />
<StepRun :stage="data.run" :entries="entriesOf(data.run.name)" />
</div>
<fieldset v-else :disabled="!!pinnedYaml || archieWorking" class="min-w-0">
<StepEditor
@@ -542,11 +528,14 @@ const runOptions = computed(() => [
</WorkflowCanvas>
</div>
</TabsContent>
<TabsContent value="yaml" class="max-md:min-h-0 max-md:overflow-y-auto">
<WorkflowYaml v-model="yaml" :readonly="archieWorking" />
</TabsContent>
<TabsContent value="history" class="max-md:min-h-0 max-md:overflow-y-auto">
<WorkflowHistory v-model:selected="historyRevision" v-model:mode="historyMode" :revisions="revisions" v-model:current="yaml" :error="historyError" :loaded="historyLoaded" :locked="archieWorking" @restore="restoreRevision" @retry="reloadHistory" />
</TabsContent>
<TabsContent value="runs" class="max-md:min-h-0 max-md:overflow-y-auto">
<WorkflowRuns :runs="runs" :loading="runsLoading" :error="runsError" :stages="stageStats" :stats-known="statsKnown" :stats-error="statsError" @retry="refresh" />
<WorkflowRuns :runs="runs" :loading="runsLoading" :error="runsError" :stats="props.stats" @retry="refresh" />
</TabsContent>
</Tabs>
<Alert v-if="stepTypesMissing" variant="destructive"><AlertDescription>{{ errors.workflows.editor.stepTypesUnavailable }}</AlertDescription></Alert>
@@ -597,11 +586,11 @@ const runOptions = computed(() => [
<AlertDialog v-model:open="confirmDelete">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete the {{ selected }} workflow?</AlertDialogTitle>
<AlertDialogTitle>{{ stored === undefined ? "Discard" : "Delete" }} the {{ selected }} workflow?</AlertDialogTitle>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" @click="remove">Delete</AlertDialogAction>
<AlertDialogAction variant="destructive" @click="remove">{{ stored === undefined ? "Discard" : "Delete" }}</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
+79 -63
View File
@@ -1,112 +1,128 @@
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { toast } from "vue-sonner";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Spinner } from "@/components/ui/spinner";
import { Button } from "@/components/ui/button";
import ApplyStatusRows from "@/settings/ApplyStatusRows.vue";
import { Switch } from "@/components/ui/switch";
import { errors } from "@/copy/errors";
import { api, describeError } from "@/lib/api";
import { usePoll, useRead } from "@/lib/use-read";
import { useWorkflowsStore } from "@/stores/workflows";
import WorkflowEditor from "./WorkflowEditor.vue";
import { useWorkflowStats } from "./use-workflow-stats";
import { triggerSummary, useWorkflowTriggers } from "./workflow-triggers";
import { startedBy } from "./use-workflow-list";
import type { WorkflowTrigger } from "./workflow-triggers";
/** One workflow on the canvas: edited as a draft, published as a version, and
* watched while it runs. */
const route = useRoute();
const router = useRouter();
const { store, data, error, loading, statsKnown, load, enabledOf, setEnabled, duplicate } = useWorkflowStats();
const workflows = useWorkflowsStore();
const stats = useRead(() => api.workflowStats());
const triggers = useRead(() => api.triggers());
function reload(): void {
void stats.reload();
void triggers.reload();
}
onMounted(() => {
void workflows.load();
reload();
});
usePoll(reload);
// The path names the workflow; the editor renames or clears it by publishing
// under another id or deleting, and the URL follows.
// The path names the workflow; deleting it returns to the list.
const selected = computed({
get: () => String(route.params.id ?? ""),
set: (id: string) => void (id ? router.replace({ name: "workflow-editor", params: { id }, query: route.query }) : router.replace({ name: "workflows" })),
set: (id: string) => void (id ? router.replace({ name: "workflow", params: { id }, query: route.query }) : router.replace({ name: "workflows" })),
});
// ?view= opens a tab and ?run= opens the run dialog; a link carries them once.
const view = ref(["history", "runs"].includes(String(route.query.view)) ? String(route.query.view) : "canvas");
const VIEWS = ["yaml", "history", "runs"];
const view = ref(VIEWS.includes(String(route.query.view)) ? String(route.query.view) : "canvas");
const runOpen = ref(route.query.run !== undefined);
onMounted(() => {
if (route.query.run !== undefined) void router.replace({ query: { ...route.query, run: undefined } });
});
const stored = computed(() => store.collection.definitions);
const known = computed(
() =>
stored.value.some((d) => d.id === selected.value) ||
store.drafts.some((d) => d.id === selected.value) ||
(data.value.workflows ?? []).some((w) => w.workflow === selected.value),
);
const enabled = computed(() => enabledOf(selected.value));
const draft = computed(() => store.drafts.some((d) => d.id === selected.value));
// Whether this workflow is still the one archie ships: "Edited" when it has
// been changed, "Custom" when archie ships nothing by that name.
const provenance = computed(() => {
const shippedYAML = store.shipped.definitions.find((d) => d.id === selected.value)?.yaml;
const storedYAML = stored.value.find((d) => d.id === selected.value)?.yaml;
if (storedYAML === undefined) return "";
if (shippedYAML === undefined) return "Custom";
return shippedYAML === storedYAML ? "" : "Edited";
});
const stages = computed(() => (data.value.stages ?? []).filter((s) => s.workflow === selected.value));
const startedBy = computed(() => data.value.definitions?.find((d) => d.id === selected.value)?.started_by ?? []);
const { triggers, reload: reloadTriggers, error: triggersError } = useWorkflowTriggers(selected, startedBy);
const trigger = computed(() => triggerSummary(triggers.value));
const stored = computed(() => workflows.collection.definitions.find((d) => d.id === selected.value));
const draft = computed(() => workflows.drafts.some((d) => d.id === selected.value));
// A workflow just created has no draft until its first edit is saved.
const known = computed(() => !!stored.value || draft.value || route.query.new !== undefined);
const loaded = computed(() => !!workflows.state.resource);
async function copy(id: string) {
const next = await duplicate(id);
if (next) selected.value = next;
const own = computed(() => (triggers.data.value ?? []).filter((t) => t.workflow === selected.value));
const starts = computed(() => [...new Set(own.value.map(startedBy))]);
const startsText = computed(() => starts.value[0] ?? (triggers.data.value ? "Manual" : ""));
const startsMore = computed(() => starts.value.slice(1));
const canvasTriggers = computed<WorkflowTrigger[]>(() =>
own.value.map((t) => ({ kind: t.every ? "schedule" : "event", label: t.every ? startedBy(t) : t.name, detail: t.every ? undefined : startedBy(t) })),
);
async function setEnabled(enabled: boolean): Promise<void> {
try {
await api.setWorkflowEnabled(selected.value, enabled);
await workflows.load();
} catch (cause) {
toast.error(describeError(cause, errors.common.unknown));
}
}
// A copy starts as a draft under a free name, so nothing is published until it is.
async function copy(id: string): Promise<void> {
const source = workflows.drafts.find((d) => d.id === id)?.yaml ?? stored.value?.yaml;
if (source === undefined) return;
const taken = new Set([...workflows.collection.definitions.map((d) => d.id), ...workflows.drafts.map((d) => d.id)]);
let next = `${id}-copy`;
for (let n = 2; taken.has(next); n++) next = `${id}-copy-${n}`;
if (await workflows.putDraft(next, source)) void router.push({ name: "workflow", params: { id: next } });
else toast.error(workflows.draftState.error || errors.workflows.editor.draftNotSaved);
}
</script>
<template>
<div class="max-md:flex max-md:min-h-0 max-md:flex-1 max-md:flex-col">
<div v-if="error || store.error" class="mb-4 text-label text-danger" role="alert">
<p>{{ error || store.error }}</p>
<Button variant="outline" size="sm" @click="load(); store.load()">Retry</Button>
<div v-if="workflows.error" class="mb-4 text-label text-danger" role="alert">
<p>{{ workflows.error }}</p>
<Button variant="outline" size="sm" @click="workflows.load">Retry</Button>
</div>
<p v-if="loading || (!store.state.resource && !store.error)" class="flex items-center gap-2 text-label text-fg-muted"><Spinner />Loading workflow…</p>
<Empty v-else-if="!known && !error">
<p v-else-if="!loaded" class="flex items-center gap-2 text-label text-fg-muted"><Spinner />Loading workflow…</p>
<Empty v-else-if="!known">
<EmptyHeader>
<EmptyTitle>Workflow not found</EmptyTitle>
</EmptyHeader>
</Empty>
<!-- No card around the editor: the canvas draws its own frame. -->
<div v-else-if="known" class="min-w-0 max-md:flex max-md:h-full max-md:min-h-0 max-md:flex-col" role="region" aria-label="Workflow">
<div v-else class="min-w-0 max-md:flex max-md:h-full max-md:min-h-0 max-md:flex-col" role="region" aria-label="Workflow">
<header class="mb-2 flex shrink-0 flex-wrap items-center gap-x-3 gap-y-0.5 lg:hidden">
<h1 class="min-w-0 truncate text-title font-medium">{{ selected }}</h1>
<Switch v-if="enabled !== undefined" size="sm" :model-value="enabled" :aria-label="`${selected} enabled`" @update:model-value="setEnabled(selected, $event)" />
<Switch v-if="stored" size="sm" :model-value="stored.enabled" :aria-label="`${selected} enabled`" @update:model-value="setEnabled" />
<Badge v-if="draft" variant="outline" class="shrink-0">Draft</Badge>
<Badge v-if="provenance" variant="outline" class="shrink-0">{{ provenance }}</Badge>
<ApplyStatusRows kind="workflow-definitions" compact />
<p v-if="trigger.text || (!triggersError && !triggers.length)" class="flex min-w-0 basis-full items-center gap-1.5 text-caption text-fg-muted lg:basis-0 lg:flex-1">
<span class="truncate">{{ trigger.text || "Manual" }}</span>
<Badge v-if="trigger.more.length" variant="secondary" :title="trigger.more.join('\n')">+{{ trigger.more.length }}</Badge>
<p v-if="startsText" class="flex min-w-0 basis-full items-center gap-1.5 text-caption text-fg-muted">
<span class="truncate">{{ startsText }}</span>
<Badge v-if="startsMore.length" variant="secondary" :title="startsMore.join('\n')">+{{ startsMore.length }}</Badge>
</p>
</header>
<WorkflowEditor
v-model:selected="selected"
v-model:view="view"
v-model:run-open="runOpen"
:stage-stats="stages"
:triggers="triggers"
:triggers-error="triggersError"
:stats-known="statsKnown"
:stats-error="error ?? ''"
:stats="stats.data.value?.find((s) => s.workflow === selected)"
:triggers="canvasTriggers"
@duplicate="copy"
@reload-triggers="reloadTriggers"
@deleted="selected = ''"
>
<template #title>
<h1 class="min-w-0 truncate text-title font-medium">{{ selected }}</h1>
<Switch v-if="enabled !== undefined" size="sm" :model-value="enabled" :aria-label="`${selected} enabled`" @update:model-value="setEnabled(selected, $event)" />
<Badge v-if="draft" variant="outline" class="shrink-0">Draft</Badge>
<Badge v-if="provenance" variant="outline" class="shrink-0">{{ provenance }}</Badge>
<ApplyStatusRows kind="workflow-definitions" compact />
<p v-if="trigger.text || (!triggersError && !triggers.length)" class="flex min-w-0 max-w-64 items-center gap-1.5 text-caption text-fg-muted">
<span class="truncate">{{ trigger.text || "Manual" }}</span>
<Badge v-if="trigger.more.length" variant="secondary" :title="trigger.more.join('\n')">+{{ trigger.more.length }}</Badge>
</p>
</template>
<h1 class="min-w-0 truncate text-title font-medium">{{ selected }}</h1>
<Switch v-if="stored" size="sm" :model-value="stored.enabled" :aria-label="`${selected} enabled`" @update:model-value="setEnabled" />
<Badge v-if="draft" variant="outline" class="shrink-0">Draft</Badge>
<p v-if="startsText" class="flex min-w-0 max-w-64 items-center gap-1.5 text-caption text-fg-muted">
<span class="truncate">{{ startsText }}</span>
<Badge v-if="startsMore.length" variant="secondary" :title="startsMore.join('\n')">+{{ startsMore.length }}</Badge>
</p>
</template>
</WorkflowEditor>
</div>
</div>
-230
View File
@@ -1,230 +0,0 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useSessionStorage } from "@vueuse/core";
import { Copy, RotateCcw } from "@lucide/vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { MoreMenu } from "@/components/ui/more-menu";
import { Spinner } from "@/components/ui/spinner";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { errors } from "@/copy/errors";
import { api, describeError } from "@/lib/api";
import { usePoll, useRead } from "@/lib/use-read";
import TriggerList from "@/events/TriggerList.vue";
import RunTable from "@/runs/RunTable.vue";
import { useLiveResource } from "@/stores/session";
import { startedBy } from "./use-workflow-list";
import WorkflowCanvas from "./WorkflowCanvas.vue";
import WorkflowHistory from "./WorkflowHistory.vue";
import WorkflowYaml from "./WorkflowYaml.vue";
import type { WorkflowRevision } from "./workflow-revisions";
import type { WorkflowTrigger } from "./workflow-triggers";
/** One workflow: its graph, its document, the versions it has been published
* as, its runs and the triggers that start it. */
const route = useRoute();
const router = useRouter();
const name = computed(() => String(route.params.id));
const latest = useRead(() => api.workflow(name.value));
const triggers = useRead(() => api.triggers());
const runs = useRead(() => api.runs());
onMounted(() => {
void latest.reload();
void triggers.reload();
void runs.reload();
});
useLiveResource(null, () => void runs.reload());
usePoll(runs.reload);
watch(name, () => {
void latest.reload();
void triggers.reload();
void runs.reload();
});
// The edit is kept per browser tab until it is published or discarded, so
// leaving the page does not lose it.
const edit = useSessionStorage<{ base: number; yaml: string } | null>(() => `archie.workflow-edit.${name.value}`, null, { serializer: { read: (v) => JSON.parse(v), write: (v) => JSON.stringify(v) } });
const yaml = computed({
get: () => (edit.value && edit.value.base === latest.data.value?.version ? edit.value.yaml : (latest.data.value?.body ?? "")),
set: (value: string) => {
const base = latest.data.value?.version ?? 0;
edit.value = value === latest.data.value?.body ? null : { base, yaml: value };
},
});
const edited = computed(() => !!latest.data.value && yaml.value !== latest.data.value.body);
const busy = ref(false);
const publishError = ref("");
async function publish(): Promise<void> {
busy.value = true;
publishError.value = "";
try {
// Another writer (a person, or Archie publishing a draft) may have
// published since this copy was opened; never overwrite their version.
const current = await api.workflow(name.value);
if (current.version !== edit.value?.base) {
publishError.value = `Version ${current.version} was published after you opened version ${edit.value?.base}. Copy your changes, then discard them to load it.`;
return;
}
await api.putWorkflow(name.value, yaml.value);
edit.value = null;
await latest.reload();
} catch (cause) {
publishError.value = describeError(cause, errors.common.unknown);
} finally {
busy.value = false;
}
}
const discarding = ref(false);
function discard(): void {
edit.value = null;
publishError.value = "";
discarding.value = false;
void latest.reload();
}
async function duplicate(): Promise<void> {
const taken = new Set((await api.workflowList()).map((w) => w.name));
let next = `${name.value}-copy`;
for (let n = 2; taken.has(next); n++) next = `${name.value}-copy-${n}`;
try {
await api.putWorkflow(next, yaml.value);
void router.push(`/workflows/${next}`);
} catch (cause) {
publishError.value = describeError(cause, errors.common.unknown);
}
}
// ?view= opens a tab; a link carries it once.
const VIEWS = ["yaml", "history", "runs", "triggers"];
const view = computed({
get: () => (VIEWS.includes(String(route.query.view)) ? String(route.query.view) : "canvas"),
set: (v: string) => void router.replace({ query: { ...route.query, view: v === "canvas" ? undefined : v } }),
});
const open = ref<string | null>(null);
// Every published version, read when the history is first opened.
const revisions = useRead<WorkflowRevision[]>(async () => {
const count = latest.data.value?.version ?? 0;
const versions = await Promise.all(Array.from({ length: count }, (_, i) => api.workflow(name.value, i + 1)));
return versions
.map((w) => ({ version: w.version, change: w.version === 1 ? ("added" as const) : ("edited" as const), yaml: w.body, actor: w.created_by ?? "", source: "", at: w.created_at }))
.reverse();
});
const historyRevision = ref(0);
const historyMode = ref("yaml");
watch([view, () => latest.data.value?.version], ([v]) => v === "history" && void revisions.reload(), { immediate: true });
function restore(body: string): void {
yaml.value = body;
view.value = "yaml";
}
const own = computed(() => (runs.data.value ?? []).filter((r) => r.workflow === name.value));
const starts = computed(() => [...new Set((triggers.data.value ?? []).filter((t) => t.workflow === name.value).map(startedBy))]);
const canvasTriggers = computed<WorkflowTrigger[]>(() =>
(triggers.data.value ?? [])
.filter((t) => t.workflow === name.value)
.map((t) => ({ kind: t.every ? "schedule" : "event", label: t.every ? startedBy(t) : t.name, detail: t.every ? undefined : startedBy(t) })),
);
const startsText = computed(() => starts.value[0] ?? (triggers.data.value ? "Manual" : ""));
const startsMore = computed(() => starts.value.slice(1));
</script>
<template>
<div class="max-md:flex max-md:min-h-0 max-md:flex-1 max-md:flex-col">
<div v-if="latest.error.value" class="mb-4 text-label text-danger" role="alert">
<p>{{ latest.error.value }}</p>
<Button variant="outline" size="sm" @click="latest.reload">Retry</Button>
</div>
<p v-else-if="!latest.data.value" class="flex items-center gap-2 text-label text-fg-muted"><Spinner />Loading workflow…</p>
<div v-else class="min-w-0 max-md:flex max-md:h-full max-md:min-h-0 max-md:flex-col" role="region" aria-label="Workflow">
<header class="mb-2 flex shrink-0 flex-wrap items-center gap-x-3 gap-y-0.5 lg:hidden">
<h1 class="min-w-0 truncate text-title font-medium">{{ name }}</h1>
<Badge v-if="edited" variant="outline" class="shrink-0">Unpublished</Badge>
<p v-if="startsText" class="flex min-w-0 basis-full items-center gap-1.5 text-caption text-fg-muted">
<span class="truncate">{{ startsText }}</span>
<Badge v-if="startsMore.length" variant="secondary" :title="startsMore.join('\n')">+{{ startsMore.length }}</Badge>
</p>
</header>
<div class="space-y-4 max-md:flex max-md:min-h-0 max-md:flex-1 max-md:flex-col">
<Tabs v-model="view" class="space-y-1.5 max-md:min-h-0 max-md:flex-1">
<div class="flex shrink-0 flex-wrap items-center gap-2 max-sm:grid max-sm:grid-cols-[1fr_auto]">
<div class="flex min-w-0 shrink items-center gap-2 max-lg:hidden">
<h1 class="min-w-0 truncate text-title font-medium">{{ name }}</h1>
<span class="shrink-0 text-caption text-fg-subtle">v{{ latest.data.value.version }}</span>
<Badge v-if="edited" variant="outline" class="shrink-0">Unpublished</Badge>
<p v-if="startsText" class="flex min-w-0 max-w-64 items-center gap-1.5 text-caption text-fg-muted">
<span class="truncate">{{ startsText }}</span>
<Badge v-if="startsMore.length" variant="secondary" :title="startsMore.join('\n')">+{{ startsMore.length }}</Badge>
</p>
</div>
<TabsList class="shrink-0 justify-start">
<TabsTrigger value="canvas">Canvas</TabsTrigger>
<TabsTrigger value="yaml">YAML</TabsTrigger>
<TabsTrigger value="history">History</TabsTrigger>
<TabsTrigger value="runs">Runs <span v-if="own.length" class="ml-1 font-mono text-caption text-fg-subtle">{{ own.length }}</span></TabsTrigger>
<TabsTrigger value="triggers">Triggers</TabsTrigger>
</TabsList>
<div role="group" aria-label="Edit" class="ml-auto flex min-w-0 items-center gap-1 border-l pl-2 max-sm:col-start-2 max-sm:row-start-1">
<span v-if="edited" class="shrink-0">
<Button type="button" size="sm" :disabled="busy" @click="publish"><Spinner v-if="busy" data-icon="inline-start" />Publish</Button>
</span>
<MoreMenu>
<DropdownMenuItem v-if="edited" @select="discarding = true"><RotateCcw />Discard changes</DropdownMenuItem>
<DropdownMenuItem @select="duplicate"><Copy />Duplicate</DropdownMenuItem>
</MoreMenu>
</div>
</div>
<Alert v-if="publishError" variant="destructive"><AlertDescription>{{ publishError }}</AlertDescription></Alert>
<TabsContent value="canvas" class="space-y-2 max-md:flex max-md:min-h-0 max-md:flex-col">
<div class="relative flex h-[calc(100dvh-14rem)] min-h-[26rem] flex-col max-md:h-auto max-md:min-h-0 max-md:flex-1">
<WorkflowCanvas class="h-auto min-h-0 flex-1" :yaml="yaml" readonly :open="open" :triggers="canvasTriggers" :title="name" @toggle="open = open === $event ? null : $event" />
</div>
</TabsContent>
<TabsContent value="yaml" class="max-md:min-h-0 max-md:overflow-y-auto">
<WorkflowYaml v-model="yaml" />
</TabsContent>
<TabsContent value="history" class="max-md:min-h-0 max-md:overflow-y-auto">
<WorkflowHistory
v-model:selected="historyRevision"
v-model:mode="historyMode"
v-model:current="yaml"
:revisions="revisions.data.value ?? []"
:error="revisions.error.value"
:loaded="!!revisions.data.value"
@restore="restore"
@retry="revisions.reload"
/>
</TabsContent>
<TabsContent value="runs" class="max-md:min-h-0 max-md:overflow-y-auto">
<p v-if="runs.error.value" role="alert" class="text-label text-danger">{{ runs.error.value }}</p>
<p v-else-if="!runs.data.value" class="flex items-center gap-2 text-label text-fg-muted"><Spinner />Loading runs…</p>
<Empty v-else-if="!own.length"><EmptyHeader><EmptyTitle>No runs yet</EmptyTitle></EmptyHeader></Empty>
<RunTable v-else :rows="own" storage-key="workflow-runs" />
</TabsContent>
<TabsContent value="triggers" class="max-md:min-h-0 max-md:overflow-y-auto">
<TriggerList :workflow="name" />
</TabsContent>
</Tabs>
</div>
</div>
<AlertDialog v-model:open="discarding">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Discard the unpublished changes to {{ name }}?</AlertDialogTitle>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" @click="discard">Discard</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</template>
+18 -5
View File
@@ -1,19 +1,32 @@
<script setup lang="ts">
import { Copy, ListChecks } from "@lucide/vue";
import { Copy, ListChecks, Trash2 } from "@lucide/vue";
import { useRouter } from "vue-router";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { MoreMenu } from "@/components/ui/more-menu";
import RunWorkflowButton from "./RunWorkflowButton.vue";
/** The overflow menu for one workflow row. */
defineProps<{ id: string }>();
const emit = defineEmits<{ runs: []; duplicate: [] }>();
/** The run button and overflow menu for one workflow row. */
const props = defineProps<{ id: string; yaml: string; published: boolean; enabled: boolean }>();
const emit = defineEmits<{ runs: []; duplicate: []; delete: [] }>();
const router = useRouter();
</script>
<template>
<div class="flex items-center justify-end gap-1" @click.stop @keydown.stop>
<RunWorkflowButton
v-if="props.published"
icon
:workflow="id"
:yaml="yaml"
:disabled="!enabled"
disabled-reason="Disabled"
@started="(runId) => router.push(`/runs/${runId}`)"
/>
<MoreMenu :label="`${id} actions`">
<DropdownMenuItem @select="emit('runs')"><ListChecks />Open runs</DropdownMenuItem>
<DropdownMenuItem v-if="props.published" @select="emit('runs')"><ListChecks />Open runs</DropdownMenuItem>
<DropdownMenuItem @select="emit('duplicate')"><Copy />Duplicate</DropdownMenuItem>
<DropdownMenuItem variant="destructive" @select="emit('delete')"><Trash2 />{{ props.published ? "Delete" : "Discard" }}</DropdownMenuItem>
</MoreMenu>
</div>
</template>
+44 -93
View File
@@ -1,116 +1,67 @@
<script setup lang="ts">
import { computed } from "vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Progress } from "@/components/ui/progress";
import { Section } from "@/components/ui/section";
import { MetadataList } from "@/components/ui/metadata-list";
import { Spinner } from "@/components/ui/spinner";
import { Timestamp } from "@/components/ui/timestamp";
import { duration } from "@/lib/format";
import { statusKind, statusLabel } from "@/lib/task-meta";
import type { WorkflowStats } from "@/lib/api";
import { stateLabel, stateTone } from "@/runs/state";
import type { WorkflowRun } from "./workflow-runs";
import { computed } from "vue";
/** One stage's timing and failures across the workflow's runs. */
export interface StageStats {
workflow: string;
stage: string;
runs: number;
errors: number;
avg_ms?: number;
}
/**
* How one workflow's runs went: its recent runs, then each stage's average
* time and failures across them. The run list is the one the canvas picks
* from, so the two never disagree.
*/
const props = defineProps<{
runs: WorkflowRun[];
loading: boolean;
error: string;
stages: StageStats[];
/** Stage statistics have been read at least once. */
statsKnown: boolean;
statsError: string;
}>();
/** How one workflow's runs went: what they add up to, then the recent runs.
* The run list is the one the canvas picks from, so the two never disagree. */
const props = defineProps<{ runs: WorkflowRun[]; loading: boolean; error: string; stats?: WorkflowStats }>();
const emit = defineEmits<{ retry: [] }>();
const runColumns: DataTableColumn<WorkflowRun>[] = [
{ id: "title", label: "Run", fixed: true, width: "auto" },
{ id: "source", label: "Source", hide: "sm" },
{ id: "status", label: "Status", sort: (run) => run.status ?? "" },
{ id: "created", label: "Started", sort: (run) => run.created_at ?? "" },
const columns: DataTableColumn<WorkflowRun>[] = [
{ id: "status", label: "Status", fixed: true, width: "11rem", sort: (run) => run.status },
{ id: "source", label: "Source", hide: "sm", width: "6rem" },
{ id: "version", label: "Version", hide: "sm", width: "6rem", sort: (run) => run.version },
{ id: "created", label: "Started", sort: (run) => run.created_at },
{ id: "error", label: "Error", hide: "md", width: "24rem" },
];
// Slowest first: the stage worth looking at heads the table.
const stageRows = computed(() => [...props.stages].sort((a, b) => (b.avg_ms || 0) - (a.avg_ms || 0)));
const slowest = computed(() => Math.max(...props.stages.map((s) => s.avg_ms || 0), 1));
const stageColumns: DataTableColumn<StageStats>[] = [
{ id: "stage", label: "Stage", fixed: true },
{ id: "runs", label: "Runs", sort: (s) => s.runs },
{ id: "errors", label: "Failures", sort: (s) => s.errors },
{ id: "avg", label: "Average", sort: (s) => s.avg_ms || 0, width: "12rem" },
];
function source(run: WorkflowRun): string {
if (!run.owner || !run.repo) return "";
return `${run.owner}/${run.repo}${run.issue_url && run.issue_number ? ` #${run.issue_number}` : ""}`;
}
const totals = computed(() => {
const s = props.stats;
if (!s) return [];
return [
{ label: "Runs", value: String(s.total) },
...(s.success_rate === undefined ? [] : [{ label: "Success rate", value: `${Math.round(s.success_rate * 100)}%` }]),
...(s.failed ? [{ label: "Failed", value: String(s.failed) }] : []),
...(s.active ? [{ label: "Running", value: String(s.active) }] : []),
];
});
</script>
<template>
<div class="space-y-4">
<div>
<p v-if="loading && !runs.length" class="flex items-center gap-2 text-label text-fg-muted"><Spinner />Loading runs…</p>
<div v-else-if="error && !runs.length" role="alert" class="flex items-center gap-2 text-label text-danger">
{{ error }}
<Button variant="outline" size="sm" @click="emit('retry')">Retry</Button>
</div>
<Empty v-else-if="!runs.length"><EmptyHeader><EmptyTitle>No runs yet</EmptyTitle></EmptyHeader></Empty>
<template v-else>
<p v-if="error" role="alert" class="mb-2 text-label text-danger">{{ error }}</p>
<DataTable
:columns="runColumns"
:rows="runs"
:row-key="(run) => String(run.id)"
:row-link="(run) => `/tasks/${run.id}`"
:row-label="(run) => run.title || `Task ${run.id}`"
storage-key="workflow-runs"
>
<template #cell-title="{ row }"><span class="block truncate">{{ row.title || `Task ${row.id}` }}</span></template>
<template #cell-source="{ row }"><span class="font-mono text-caption text-fg-subtle">{{ source(row) }}</span></template>
<template #cell-status="{ row }"><Badge :variant="statusKind(row.status ?? '')">{{ statusLabel(row.status ?? "") }}</Badge></template>
<template #cell-created="{ row }"><Timestamp v-if="row.created_at" :at="row.created_at" /></template>
</DataTable>
</template>
<MetadataList v-if="totals.length" :rows="totals" />
<p v-if="loading && !runs.length" class="flex items-center gap-2 text-label text-fg-muted"><Spinner />Loading runs…</p>
<div v-else-if="error && !runs.length" role="alert" class="flex items-center gap-2 text-label text-danger">
{{ error }}
<Button variant="outline" size="sm" @click="emit('retry')">Retry</Button>
</div>
<Section v-if="runs.length" title="Stages" class="mb-0">
<p v-if="!statsKnown && statsError" role="alert" class="text-label text-danger">{{ statsError }}</p>
<p v-else-if="!statsKnown" class="flex items-center gap-2 text-label text-fg-muted"><Spinner />Loading…</p>
<Empty v-else-if="!stages.length"><EmptyHeader><EmptyTitle>No stage timings yet</EmptyTitle></EmptyHeader></Empty>
<Empty v-else-if="!runs.length"><EmptyHeader><EmptyTitle>No runs yet</EmptyTitle></EmptyHeader></Empty>
<template v-else>
<p v-if="error" role="alert" class="mb-2 text-label text-danger">{{ error }}</p>
<DataTable
v-else
:columns="stageColumns"
:rows="stageRows"
:row-key="(s) => s.stage"
storage-key="workflow-stages"
:columns="columns"
:rows="runs"
:row-key="(run) => run.id"
:row-link="(run) => `/runs/${run.id}`"
:row-label="(run) => `Run ${run.id.slice(0, 8)}`"
:initial-sort="{ id: 'created', desc: true }"
storage-key="workflow-runs"
>
<template #cell-stage="{ row }"><span class="font-medium">{{ row.stage }}</span></template>
<template #cell-runs="{ row }"><span class="font-mono">{{ row.runs }}</span></template>
<template #cell-errors="{ row }">
<Badge v-if="row.errors" variant="danger">{{ row.errors }}</Badge>
</template>
<template #cell-avg="{ row }">
<div class="flex items-center gap-2">
<span class="w-14 shrink-0 font-mono text-caption">{{ row.avg_ms ? duration(row.avg_ms) : "" }}</span>
<Progress :model-value="Math.round(((row.avg_ms || 0) / slowest) * 100)" :aria-label="`${row.stage} average time`" class="h-1.5 max-sm:hidden" />
</div>
</template>
<template #cell-status="{ row }"><Badge :variant="stateTone(row.status)">{{ stateLabel(row.status) }}</Badge></template>
<template #cell-source="{ row }"><span class="text-caption text-fg-muted">{{ row.source === "test" ? "Test" : "" }}</span></template>
<template #cell-version="{ row }"><span class="font-mono text-caption text-fg-subtle">{{ row.source === "test" ? "" : `v${row.version}` }}</span></template>
<template #cell-created="{ row }"><Timestamp :at="row.created_at" /></template>
<template #cell-error="{ row }"><span class="text-caption text-danger" :title="row.error">{{ row.error }}</span></template>
</DataTable>
</Section>
</template>
</div>
</template>
+4 -65
View File
@@ -1,19 +1,11 @@
<script setup lang="ts">
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Label } from "@/components/ui/label";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { Textarea } from "@/components/ui/textarea";
import { computed, ref, onMounted } from "vue";
import { computed } from "vue";
import { Button } from "@/components/ui/button";
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import type { Identity } from "@/stores/org";
import { useOrgStore } from "@/stores/org";
import { useSettingsStore } from "@/stores/settings";
import OptionSelect from "@/components/OptionSelect.vue";
import SpecList from "./SpecList.vue";
import { SEEDED_AGENT_ID, setWorkflowField, workflowField } from "./workflow-edit";
import { setWorkflowField, workflowField } from "./workflow-edit";
const props = defineProps<{ yaml: string }>();
const emit = defineEmits<{ "update:yaml": [string] }>();
@@ -26,41 +18,8 @@ function set(key: string, value: unknown): void {
emit("update:yaml", setWorkflowField(props.yaml, key, value));
}
// The identity a run acts as must be an agent, never a person.
const seededAgentId: string = SEEDED_AGENT_ID;
const identities = useOrgStore();
const agents = ref<Identity[]>([]);
const identitiesLoading = ref(true);
const identitiesError = ref("");
async function loadAgents(): Promise<void> {
identitiesLoading.value = true;
identitiesError.value = "";
agents.value = [];
try {
await identities.loadOrg();
const response = await api.orgAgents<{ agents: Identity[] }>(identities.homeOrg);
agents.value = response.agents.filter((agent) => agent.lifecycle === "active");
} catch (cause) {
identitiesError.value = describeError(cause, errors.common.unknown);
} finally { identitiesLoading.value = false; }
}
onMounted(loadAgents);
const identityOptions = computed(() => {
const current = text("identity");
const options = agents.value.map((agent) => ({ value: agent.id, label: agent.display_name }));
return current && !identitiesLoading.value && !agents.value.some((agent) => agent.id === current) ? [{ value: current, label: `${current} (unknown)`, disabled: true }, ...options] : options;
});
const settings = useSettingsStore();
const profileOptions = computed(() => {
const names = Object.keys((settings.stateFor("agent-profiles").resource?.value ?? {}) as Record<string, unknown>).sort();
const current = text("profile");
if (current && !names.includes(current)) names.unshift(current);
return [{ value: "", label: "Default" }, ...names.map((name) => ({ value: name, label: name }))];
});
const MODES = [
{ value: "required", label: "Repository", hint: "Clones the task's repository" },
{ value: "required", label: "Repository", hint: "Clones the run's repository" },
{ value: "optional", label: "If given", hint: "Clones one when the run names it" },
{ value: "none", label: "None", hint: "Scratch workspace, no clone" },
];
@@ -82,25 +41,6 @@ const repository = computed(() => text("repository") || "required");
</section>
<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">Runs as</span>
<OptionSelect
:key="String(identitiesLoading)"
:model-value="text('identity') || (agents.some((agent) => agent.id === seededAgentId) ? seededAgentId : '')"
:options="identityOptions"
aria-label="Execution identity"
:placeholder="identitiesLoading ? 'Loading agents…' : 'Choose an agent'"
:disabled="identitiesLoading || !!identitiesError"
class="w-44"
@update:model-value="set('identity', $event)"
/>
</Label>
<Alert v-if="identitiesError" variant="destructive" class="m-3"><AlertDescription>{{ identitiesError }} <Button variant="link" size="xs" @click="loadAgents">Retry</Button></AlertDescription></Alert>
<p v-else-if="!identitiesLoading && !agents.length" class="px-3 py-2 text-caption text-fg-subtle">No active agents in your organisation.</p>
<Label class="flex min-h-10 items-center gap-3 px-3 py-1.5">
<span class="flex-1 text-label">Container profile</span>
<OptionSelect :model-value="text('profile')" :options="profileOptions" aria-label="Container profile" class="w-44" @update:model-value="set('profile', $event || undefined)" />
</Label>
<div class="flex min-h-10 items-center gap-3 px-3 py-1.5">
<span class="flex-1 text-label">Works on</span>
<ToggleGroup
@@ -116,7 +56,6 @@ const repository = computed(() => text("repository") || "required");
</div>
</div>
<SpecList :yaml="yaml" field="outputs" @update:yaml="emit('update:yaml', $event)" />
<SpecList :yaml="yaml" field="inputs" @update:yaml="emit('update:yaml', $event)" />
</div>
</template>
+71 -32
View File
@@ -2,7 +2,7 @@
import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { useMediaQuery } from "@vueuse/core";
import { Copy, ListChecks, Plus, Search } from "@lucide/vue";
import { Copy, ListChecks, Plus, Search, Trash2 } from "@lucide/vue";
import { toast } from "vue-sonner";
import PageHeader from "@/base/PageHeader.vue";
@@ -12,9 +12,11 @@ import { Card } from "@/components/ui/card";
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from "@/components/ui/context-menu";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { Input } from "@/components/ui/input";
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";
import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Timestamp } from "@/components/ui/timestamp";
import { errors } from "@/copy/errors";
@@ -24,7 +26,6 @@ import { useWorkflowList, type WorkflowRow } from "./use-workflow-list";
import WorkflowDelivery from "./WorkflowDelivery.vue";
import WorkflowLastRun from "./WorkflowLastRun.vue";
import WorkflowRowActions from "./WorkflowRowActions.vue";
import WorkflowYaml from "./WorkflowYaml.vue";
const router = useRouter();
const { rows, error, partial, loading, reload, triggersKnown, runsKnown } = useWorkflowList();
@@ -43,38 +44,56 @@ const openRuns = (name: string) => void router.push({ path: "/runs", query: { wo
const startsText = (row: WorkflowRow) => row.starts[0] ?? "";
const startsMore = (row: WorkflowRow) => row.starts.slice(1);
const lastTo = (row: WorkflowRow) => (row.last ? `/runs/${row.last.id}` : undefined);
const versionLabel = (row: WorkflowRow) => (row.version ? `v${row.version}` : "");
const stepsLabel = (row: WorkflowRow) => `${row.steps} ${row.steps === 1 ? "step" : "steps"}`;
// A copy starts as a draft under a free name, so nothing is published until it is.
async function copy(row: WorkflowRow): Promise<void> {
const taken = new Set(rows.value.map((r) => r.name));
let next = `${row.name}-copy`;
for (let n = 2; taken.has(next); n++) next = `${row.name}-copy-${n}`;
try {
const source = await api.workflow(row.name);
await api.putWorkflow(next, source.body);
const draft = await api.workflowDraft(row.name);
await api.putWorkflowDraft(next, draft?.body ?? row.body, 0);
open(next);
} catch (cause) {
toast.error(describeError(cause, errors.common.unknown));
}
}
const creating = ref(false);
const draft = ref({ name: "", body: "steps:\n - id: first\n type: agent.run\n settings:\n mission: |\n \n" });
const busy = ref(false);
const createError = ref("");
async function create(): Promise<void> {
busy.value = true;
createError.value = "";
const name = draft.value.name.trim();
async function setEnabled(row: WorkflowRow, enabled: boolean): Promise<void> {
try {
await api.putWorkflow(name, draft.value.body);
creating.value = false;
open(name);
await api.setWorkflowEnabled(row.name, enabled);
} catch (cause) {
createError.value = describeError(cause, errors.common.unknown);
} finally {
busy.value = false;
toast.error(describeError(cause, errors.common.unknown));
}
await reload();
}
// A published workflow is deleted; one with only a draft has the draft discarded.
const deleting = ref<WorkflowRow | null>(null);
async function remove(row: WorkflowRow): Promise<void> {
try {
if (row.version) await api.deleteWorkflow(row.name);
else await api.discardWorkflowDraft(row.name);
} catch (cause) {
toast.error(describeError(cause, errors.common.unknown));
}
await reload();
}
// A new workflow is built on the canvas, as a draft.
const creating = ref(false);
const name = ref("");
const createError = ref("");
function create(): void {
const next = name.value.trim();
if (rows.value.some((row) => row.name === next)) {
createError.value = `${next} already exists`;
return;
}
creating.value = false;
void router.push({ path: `/workflows/${next}`, query: { new: "" } });
}
</script>
@@ -105,13 +124,14 @@ async function create(): Promise<void> {
<Table v-else-if="wide && shown.length" class="table-fixed" aria-label="Workflows">
<TableHeader>
<TableRow>
<TableHead class="w-[24%]">Workflow</TableHead>
<TableHead class="w-[24%]">Starts from</TableHead>
<TableHead class="w-[22%]">Workflow</TableHead>
<TableHead class="w-14"><span class="sr-only">Enabled</span></TableHead>
<TableHead class="w-[22%]">Starts from</TableHead>
<TableHead class="w-16">Steps</TableHead>
<TableHead class="w-[16%]">Last run</TableHead>
<TableHead class="w-[16%]">Runs</TableHead>
<TableHead class="w-40">Published</TableHead>
<TableHead class="w-16"><span class="sr-only">Actions</span></TableHead>
<TableHead class="w-24"><span class="sr-only">Actions</span></TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -121,9 +141,13 @@ async function create(): Promise<void> {
<TableCell class="whitespace-normal">
<span class="flex min-w-0 items-center gap-2">
<RouterLink :to="`/workflows/${row.name}`" class="min-w-0 truncate font-medium hover:underline focus-visible:outline-2 focus-visible:outline-ring" @click.stop>{{ row.name }}</RouterLink>
<span class="shrink-0 text-caption text-fg-subtle">v{{ row.version }}</span>
<span class="shrink-0 text-caption text-fg-subtle">{{ versionLabel(row) }}</span>
<Badge v-if="row.draft" variant="outline" class="shrink-0">Draft</Badge>
</span>
</TableCell>
<TableCell @click.stop @keydown.stop>
<Switch v-if="row.version" size="sm" :model-value="row.enabled" :aria-label="`${row.name} enabled`" @update:model-value="setEnabled(row, $event)" />
</TableCell>
<TableCell class="whitespace-normal">
<span v-if="startsText(row)" class="flex min-w-0 items-center gap-1.5">
<span class="truncate">{{ startsText(row) }}</span>
@@ -138,13 +162,14 @@ async function create(): Promise<void> {
<span class="flex flex-col gap-0.5"><Timestamp :at="row.published" /><span v-if="row.by" class="truncate text-caption text-fg-muted">{{ row.by }}</span></span>
</TableCell>
<TableCell class="text-right">
<WorkflowRowActions :id="row.name" @runs="openRuns(row.name)" @duplicate="copy(row)" />
<WorkflowRowActions :id="row.name" :yaml="row.body" :published="!!row.version" :enabled="row.enabled" @runs="openRuns(row.name)" @duplicate="copy(row)" @delete="deleting = row" />
</TableCell>
</TableRow>
</ContextMenuTrigger>
<ContextMenuContent class="min-w-40">
<ContextMenuItem @select="openRuns(row.name)"><ListChecks />Open runs</ContextMenuItem>
<ContextMenuItem v-if="row.version" @select="openRuns(row.name)"><ListChecks />Open runs</ContextMenuItem>
<ContextMenuItem @select="copy(row)"><Copy />Duplicate</ContextMenuItem>
<ContextMenuItem variant="destructive" @select="deleting = row"><Trash2 />{{ row.version ? "Delete" : "Discard" }}</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>
</TableBody>
@@ -157,8 +182,10 @@ async function create(): Promise<void> {
<Card class="cursor-pointer gap-2.5 px-4 py-3 transition-colors hover:bg-secondary/60" @click="open(row.name)">
<div class="flex items-center gap-2">
<RouterLink :to="`/workflows/${row.name}`" class="min-w-0 truncate text-label font-medium focus-visible:outline-2 focus-visible:outline-ring" @click.stop>{{ row.name }}</RouterLink>
<span class="shrink-0 text-caption text-fg-subtle">v{{ row.version }}</span>
<WorkflowRowActions :id="row.name" class="ml-auto" @runs="openRuns(row.name)" @duplicate="copy(row)" />
<span class="shrink-0 text-caption text-fg-subtle">{{ versionLabel(row) }}</span>
<Badge v-if="row.draft" variant="outline" class="shrink-0">Draft</Badge>
<Switch v-if="row.version" size="sm" class="ml-auto" :model-value="row.enabled" :aria-label="`${row.name} enabled`" @click.stop @update:model-value="setEnabled(row, $event)" />
<WorkflowRowActions :id="row.name" :yaml="row.body" :published="!!row.version" :enabled="row.enabled" :class="row.version ? '' : 'ml-auto'" @runs="openRuns(row.name)" @duplicate="copy(row)" @delete="deleting = row" />
</div>
<p class="flex min-w-0 items-center gap-1.5 text-caption text-fg-muted">
<span class="truncate">{{ startsText(row) || (triggersKnown ? "Manual" : "") }}</span>
@@ -174,23 +201,35 @@ async function create(): Promise<void> {
</Card>
</ContextMenuTrigger>
<ContextMenuContent class="min-w-40">
<ContextMenuItem @select="openRuns(row.name)"><ListChecks />Open runs</ContextMenuItem>
<ContextMenuItem v-if="row.version" @select="openRuns(row.name)"><ListChecks />Open runs</ContextMenuItem>
<ContextMenuItem @select="copy(row)"><Copy />Duplicate</ContextMenuItem>
<ContextMenuItem variant="destructive" @select="deleting = row"><Trash2 />{{ row.version ? "Delete" : "Discard" }}</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>
</li>
</ul>
<Dialog v-model:open="creating">
<DialogContent class="sm:max-w-2xl">
<Dialog v-model:open="creating" @update:open="(now) => { if (now) { name = ''; createError = ''; } }">
<DialogContent class="sm:max-w-md">
<DialogHeader><DialogTitle>New workflow</DialogTitle></DialogHeader>
<form id="new-workflow" class="flex min-h-0 flex-col gap-3" @submit.prevent="create">
<Input v-model="draft.name" aria-label="Name" placeholder="Name" pattern="[a-z0-9]+([.\-][a-z0-9]+)*" required />
<WorkflowYaml v-model="draft.body" class="max-h-[60dvh]" />
<Input v-model="name" aria-label="Name" placeholder="Name" pattern="[a-z0-9]+([.\-][a-z0-9]+)*" required />
<p v-if="createError" role="alert" class="text-caption text-danger">{{ createError }}</p>
</form>
<DialogFooter><Button type="submit" form="new-workflow" :disabled="busy || !draft.name">Publish</Button></DialogFooter>
<DialogFooter><Button type="submit" form="new-workflow" :disabled="!name">Create</Button></DialogFooter>
</DialogContent>
</Dialog>
<AlertDialog :open="deleting !== null" @update:open="(now: boolean) => { if (!now) deleting = null; }">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{{ deleting?.version ? "Delete" : "Discard" }} the {{ deleting?.name }} workflow?</AlertDialogTitle>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" @click="deleting && remove(deleting)">{{ deleting?.version ? "Delete" : "Discard" }}</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</template>
+44 -27
View File
@@ -1,21 +1,27 @@
import { computed, onMounted } from "vue";
import { api, type Run, type Trigger } from "@/lib/api";
import { api, type Trigger } from "@/lib/api";
import { usePoll, useRead } from "@/lib/use-read";
import { useLiveResource } from "@/stores/session";
export interface WorkflowRow {
name: string;
/** The published version; 0 for a workflow with only a draft. */
version: number;
/** The published document, which says what a run is asked for. */
body: string;
steps: number;
published: string;
by?: string;
enabled: boolean;
/** Has an unpublished edit. */
draft: boolean;
/** What starts it, one entry per distinct way. */
starts: string[];
runs: number;
succeeded: number;
running: number;
last?: Run;
last?: { id: string; state: string; created_at: string };
}
const time = (at?: string) => (at ? Date.parse(at) : 0);
@@ -37,37 +43,48 @@ export function byActivity(a: WorkflowRow, b: WorkflowRow): number {
return time(b.last?.created_at) - time(a.last?.created_at) || a.name.localeCompare(b.name);
}
/** The published workflows with what starts each and how its runs went. */
/** The workflows, published or only drafted, with what starts each and how its
* runs went. The counts come from the server, which counts every run. */
export function useWorkflowList() {
const workflows = useRead(() => api.workflowList());
const drafts = useRead(() => api.workflowDrafts());
const triggers = useRead(() => api.triggers());
const runs = useRead(() => api.runs());
const reload = () => Promise.all([workflows.reload(), triggers.reload(), runs.reload()]).then(() => undefined);
const stats = useRead(() => api.workflowStats());
const reload = () => Promise.all([workflows.reload(), drafts.reload(), triggers.reload(), stats.reload()]).then(() => undefined);
onMounted(reload);
useLiveResource(null, () => void reload());
usePoll(reload);
const rows = computed<WorkflowRow[]>(() =>
(workflows.data.value ?? [])
.map((w) => {
const own = (runs.data.value ?? []).filter((r) => r.workflow === w.name);
return {
name: w.name,
version: w.version,
steps: w.steps?.length ?? 0,
published: w.created_at,
by: w.created_by,
starts: [...new Set((triggers.data.value ?? []).filter((t) => t.workflow === w.name).map(startedBy))],
runs: own.length,
succeeded: own.filter((r) => r.state === "succeeded").length,
running: own.filter((r) => r.state === "running").length,
last: own.reduce<Run | undefined>((a, b) => (!a || time(b.created_at) > time(a.created_at) ? b : a), undefined),
};
})
.sort(byActivity),
);
/** Triggers or runs that failed to load: rows show without them, beside this. */
const partial = computed(() => triggers.error.value || runs.error.value);
const rows = computed<WorkflowRow[]>(() => {
const counted = new Map((stats.data.value ?? []).map((s) => [s.workflow, s]));
const held = new Set((drafts.data.value ?? []).map((d) => d.name));
const row = (name: string, own: Partial<WorkflowRow>): WorkflowRow => {
const s = counted.get(name);
return {
name,
version: 0,
body: "",
steps: 0,
published: "",
enabled: true,
draft: held.has(name),
starts: [...new Set((triggers.data.value ?? []).filter((t) => t.workflow === name).map(startedBy))],
runs: s?.total ?? 0,
succeeded: s?.succeeded ?? 0,
running: s?.active ?? 0,
last: s ? { id: s.last_run.id, state: s.last_run.state, created_at: s.last_run.at } : undefined,
...own,
};
};
const published = (workflows.data.value ?? []).map((w) =>
row(w.name, { version: w.version, body: w.body, steps: w.steps?.length ?? 0, published: w.created_at, by: w.created_by, enabled: w.enabled }),
);
const known = new Set(published.map((r) => r.name));
const drafted = (drafts.data.value ?? []).filter((d) => !known.has(d.name)).map((d) => row(d.name, { body: d.body, published: d.updated_at, by: d.updated_by }));
return [...published, ...drafted].sort(byActivity);
});
/** Triggers, drafts or counts that failed to load: rows show without them, beside this. */
const partial = computed(() => triggers.error.value || stats.error.value || drafts.error.value);
return {
rows,
error: workflows.error,
@@ -75,6 +92,6 @@ export function useWorkflowList() {
loading: computed(() => !workflows.data.value && !workflows.error.value),
reload,
triggersKnown: computed(() => !!triggers.data.value),
runsKnown: computed(() => !!runs.data.value),
runsKnown: computed(() => !!stats.data.value),
};
}
-102
View File
@@ -1,102 +0,0 @@
import { onMounted, ref, shallowRef } from "vue";
import { toast } from "vue-sonner";
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { keepValue } from "@/lib/keep-unchanged";
import { removeWorkflowDefinition, upsertWorkflowDefinition, useWorkflowsStore } from "@/stores/workflows";
import { useLiveResource } from "@/stores/session";
import type { StageStats } from "./WorkflowRuns.vue";
import { setWorkflowField } from "./workflow-edit";
import type { WorkflowDefinition, WorkflowStats } from "./workflow-rows";
interface WorkflowsResponse {
definitions?: WorkflowDefinition[];
workflows?: WorkflowStats[];
stages?: StageStats[];
}
/**
* The workflow list and the workflow page read the same statistics and offer
* the same Enable/Disable and Duplicate, so both take them from here.
*/
export function useWorkflowStats() {
const store = useWorkflowsStore();
const data = shallowRef<WorkflowsResponse>({});
const error = ref<string | null>(null);
const loading = ref(true);
// Statistics are known once a read has returned them; until then, or after a
// failed read, a row says nothing about its runs rather than "Never run".
const statsKnown = ref(false);
// Live reloads and actions overlap; only the newest read may land.
let generation = 0;
async function load() {
const current = ++generation;
try {
// Running count and last status come from the per-workflow statistics: a
// page of the newest tasks would show nothing for a workflow whose runs
// are older than that page.
const response = (await api.workflows<WorkflowsResponse>()) ?? {};
if (current !== generation) return;
data.value = keepValue(data.value, response);
error.value = null;
statsKnown.value = true;
} catch (err) {
if (current === generation) error.value = describeError(err, errors.common.unknown);
} finally {
if (current === generation) loading.value = false;
}
}
useLiveResource("tasks", () => void load(), 5000);
onMounted(() => Promise.all([load(), store.load()]));
// A switch shows the operator's choice at once; the server's answer replaces
// it, or the switch falls back when the change is refused.
const requested = ref<Record<string, boolean>>({});
const enabledOf = (id: string) => requested.value[id] ?? data.value.definitions?.find((d) => d.id === id)?.enabled;
async function setEnabled(id: string, value: boolean) {
requested.value = { ...requested.value, [id]: value };
try {
await api.workflowEnabled(id, value);
toast.success(`${id} ${value ? "enabled" : "disabled"}`);
await load();
} catch (err) {
const reason = describeError(err, errors.common.unknown);
toast.error(value ? errors.workflows.page.notEnabled(id, reason) : errors.workflows.page.notDisabled(id, reason));
} finally {
const rest = { ...requested.value };
delete rest[id];
requested.value = rest;
}
}
/** Saves a copy of a workflow and returns its id, or "" when it was not saved. */
async function duplicate(id: string): Promise<string> {
const stored = store.collection.definitions;
const source = stored.find((d) => d.id === id);
if (!source) return "";
let copy = `${id}-copy`;
for (let n = 2; stored.some((d) => d.id === copy); n++) copy = `${id}-copy-${n}`;
if (await store.save(upsertWorkflowDefinition(store.collection, { id: copy, yaml: setWorkflowField(source.yaml, "id", copy) }))) {
toast.success(`${copy} created`);
return copy;
}
toast.error(errors.workflows.page.notDuplicated(id, store.error || errors.workflows.page.saveFailed));
return "";
}
/** Deletes a workflow and its draft; true when it is gone. */
async function remove(id: string): Promise<boolean> {
if (!(await store.save(removeWorkflowDefinition(store.collection, id)))) {
toast.error(store.error || errors.workflows.page.saveFailed);
return false;
}
await store.putDraft(id, undefined);
toast.success(`${id} deleted`);
return true;
}
return { store, data, error, loading, statsKnown, load, enabledOf, setEnabled, duplicate, remove };
}
+2 -1
View File
@@ -252,7 +252,8 @@ export function workflowGraph(source: string, vocabulary: readonly StepTypeInfo[
const id = `step-${key}`;
// A branch step's row is named after its branch, so two branches running
// the same step are two rows rather than one shared run.
const recordName = branch ? `${branch}/${stepID || type}` : stepID || type;
// A top-level step without an id is recorded as its type and position.
const recordName = branch ? `${branch}/${stepID || type}` : stepID || `${type}@${path?.[1]}`;
nodes.push({
id,
type: "step",
+13 -44
View File
@@ -1,12 +1,11 @@
import { computed, ref, watch, type Ref } from "vue";
import { ref, watch, type Ref } from "vue";
import { parseDocument } from "yaml";
import { useSettingsStore, type ResourceRevision } from "../stores/settings.ts";
import { describeError } from "../lib/api.ts";
import { api, describeError } from "../lib/api.ts";
import { errors } from "../copy/errors/index.ts";
import { workflowGraph } from "./workflow-graph.ts";
/** One revision of the definitions that changed a single workflow. */
/** One published version of a workflow. */
export interface WorkflowRevision {
version: number;
change: "added" | "edited" | "removed";
@@ -17,36 +16,6 @@ export interface WorkflowRevision {
at?: string;
}
function entryYaml(value: unknown, id: string): string | null {
const definitions = (value as { definitions?: { id: string; yaml: string }[] } | null)?.definitions;
return definitions?.find((entry) => entry.id === id)?.yaml ?? null;
}
/**
* The revisions in which workflow `id` was added, edited or removed, newest
* first. All workflows share one resource, so a revision that left this one's
* YAML as it was is not part of its history.
*/
function workflowRevisions(id: string, revisions: ResourceRevision[]): WorkflowRevision[] {
const changes: WorkflowRevision[] = [];
let previous: string | null = null;
for (const revision of [...revisions].sort((a, b) => a.version - b.version)) {
const yaml = entryYaml(revision.value, id);
if (yaml !== previous) {
changes.push({
version: revision.version,
change: yaml === null ? "removed" : previous === null ? "added" : "edited",
yaml,
actor: revision.actor,
source: revision.source,
at: revision.at,
});
}
previous = yaml;
}
return changes.reverse();
}
/**
* The revision a run used: the newest one holding the YAML the run pinned that
* was already in place when the run was created. A test run pins a draft that
@@ -117,21 +86,23 @@ export function stepMarks(source: string, other: string, missing: "added" | "rem
return marks;
}
const KIND = "workflow-definitions";
/** The history of workflow `id`, kept current as the definitions change. */
export function useWorkflowHistory(id: Ref<string>) {
const store = useSettingsStore();
const all = ref<ResourceRevision[]>([]);
/** Every published version of workflow `name`, newest first, read again when
* a new version is published. */
export function useWorkflowHistory(name: Ref<string>, published: Ref<number>) {
const revisions = ref<WorkflowRevision[]>([]);
const error = ref("");
const loaded = ref(false);
let generation = 0;
async function reload(): Promise<void> {
const current = ++generation;
const requested = name.value;
try {
all.value = await store.history(KIND);
const versions = await Promise.all(Array.from({ length: published.value }, (_, i) => api.workflow(requested, i + 1)));
if (current !== generation) return;
revisions.value = versions
.map((w) => ({ version: w.version, change: w.version === 1 ? ("added" as const) : ("edited" as const), yaml: w.body, actor: w.created_by ?? "", source: "", at: w.created_at }))
.reverse();
error.value = "";
loaded.value = true;
} catch (err) {
@@ -139,8 +110,6 @@ export function useWorkflowHistory(id: Ref<string>) {
error.value = describeError(err, errors.workflows.history.notLoaded);
}
}
watch(() => store.stateFor(KIND).resource?.version, () => void reload(), { immediate: true });
const revisions = computed(() => workflowRevisions(id.value, all.value));
watch([name, published], () => void reload(), { immediate: true });
return { revisions, error, loaded, reload };
}
+113 -71
View File
@@ -1,57 +1,96 @@
import { computed, ref, shallowRef, watch, type Ref } from "vue";
import { computed, onScopeDispose, ref, shallowRef, watch, type Ref } from "vue";
import { api, describeError } from "@/lib/api";
import { api, describeError, type Run, type RunStage, type RunTrail } from "@/lib/api";
import { errors } from "@/copy/errors";
import { keepRows } from "@/lib/keep-unchanged";
import { keepRows, keepValue } from "@/lib/keep-unchanged";
import { useLiveResource } from "@/stores/session";
import type { StageRun } from "./workflow-graph";
import type { Task } from "@/tasks/task";
export type WorkflowRun = Task & { workflow?: string };
interface AttemptsView {
attempts?: { attempt: number; stages?: StageRun[] }[];
/** A run of one workflow, as the canvas picker and the Runs view list it. */
export interface WorkflowRun {
id: string;
status: string;
created_at: string;
version: number;
/** "test" for a test run of a draft, which changes nothing. */
source: "test" | "run";
error?: string;
detail?: string;
/** The document the run executes, once the run has been read. */
workflow_definition_yaml?: string;
}
interface DebugView {
task?: { workflow_definition_yaml?: string };
/** Whether a run is still working, so its stages keep changing. */
function going(state: string): boolean {
return ["queued", "running", "waiting", "waiting_approval"].includes(state);
}
// The API caps a page at 50; the canvas picker and the Runs view share it.
// The runs the canvas picker and the Runs view share.
const RECENT_RUNS = 50;
const STAGE_STATUS: Record<RunStage["state"], string | undefined> = {
pending: undefined,
running: "running",
waiting: "running",
succeeded: "ok",
failed: "failed",
skipped: "skipped",
cancelled: "interrupted",
};
/** What the canvas draws on a step: the stages a run has reached, in the
* vocabulary the step cards use. */
export function stageRuns(stages: RunStage[]): StageRun[] {
return stages.flatMap((stage) => {
const status = STAGE_STATUS[stage.state];
if (!status) return [];
const run: StageRun = { name: stage.name, status, started_at: stage.started_at, finished_at: stage.ended_at, error: stage.error };
if (stage.started_at && stage.ended_at) run.duration_ms = Date.parse(stage.ended_at) - Date.parse(stage.started_at);
return [run];
});
}
function workflowRun(run: Run): WorkflowRun {
return {
id: run.id,
status: run.state,
created_at: run.created_at,
version: run.workflow_version,
source: run.dry ? "test" : "run",
error: run.error,
detail: run.detail,
};
}
/**
* The recent runs of one workflow and the step states of the one being
* watched, kept current from the live task stream. The newest run is watched
* until the operator picks another.
* watched, kept current while it goes on. The newest run is watched until the
* operator picks another, and a test run started here is watched too.
*/
export function useWorkflowRuns(workflow: Ref<string>) {
const runs = shallowRef<WorkflowRun[]>([]);
const listed = shallowRef<WorkflowRun[]>([]);
// Test runs aren't listed with the workflow's runs, so the ones watched from
// this editor are kept here, newest first.
const tested = shallowRef<WorkflowRun[]>([]);
const runs = computed(() => [...tested.value, ...listed.value]);
const watched = ref("");
const stages = ref<StageRun[]>([]);
const attempt = ref(0);
// The task list leaves the pinned definition out, so the watched run's is
// read from its own record.
const pinned = ref<string | undefined>(undefined);
const trail = shallowRef<RunTrail>();
let picked = false;
const error = ref("");
const loading = ref(false);
let requestNumber = 0;
async function loadRuns(): Promise<void> {
// The server filters by workflow: filtering a global page here would miss
// every run older than that page.
const requested = workflow.value;
const request = ++requestNumber;
loading.value = true;
try {
const page = requested ? await api.taskPage<WorkflowRun>({ workflow: requested, limit: RECENT_RUNS }) : null;
const page = requested ? await api.runs(RECENT_RUNS, requested) : [];
if (workflow.value !== requested || request !== requestNumber) return;
runs.value = keepRows(runs.value, (page?.tasks ?? []).sort((a, b) => Number(b.id) - Number(a.id)));
const own = page.map(workflowRun);
listed.value = keepRows(listed.value, own);
error.value = "";
if (!picked || (watched.value && !runs.value.some((run) => String(run.id) === watched.value)))
watched.value = runs.value[0] ? String(runs.value[0].id) : "";
if (!picked || (watched.value && !runs.value.some((run) => run.id === watched.value))) watched.value = runs.value[0]?.id ?? "";
} catch (cause) {
if (workflow.value === requested && request === requestNumber) error.value = describeError(cause, errors.common.unknown);
} finally {
@@ -59,72 +98,75 @@ export function useWorkflowRuns(workflow: Ref<string>) {
}
}
// A failed attempts read is an error, not a canvas with no run states.
// A failed read of the watched run is an error, not a canvas with no run states.
const stagesError = ref("");
async function loadStages(): Promise<void> {
if (!watched.value) {
if (stages.value.length) stages.value = [];
attempt.value = 0;
pinned.value = undefined;
async function loadTrail(): Promise<void> {
const requested = watched.value;
if (!requested) {
trail.value = undefined;
stagesError.value = "";
return;
}
const requested = watched.value;
let readError = "";
const [view, debug] = await Promise.all([
api.taskAttempts<AttemptsView>(requested).catch((err) => { readError = describeError(err, errors.common.unknown); return null; }),
pinned.value === undefined ? api.taskDebug<DebugView>(requested).catch(() => null) : null,
]);
if (watched.value !== requested) return;
stagesError.value = view === null ? readError || errors.workflows.runs.stagesNotLoaded : "";
if (debug) pinned.value = debug.task?.workflow_definition_yaml ?? "";
const latest = [...(view?.attempts ?? [])].sort((a, b) => b.attempt - a.attempt)[0];
// A live refresh that changed nothing must not redraw the canvas, which
// would close any menu open on it.
const next = latest?.stages ?? [];
if (JSON.stringify(next) !== JSON.stringify(stages.value)) stages.value = next;
attempt.value = latest?.attempt ?? 0;
try {
const next = await api.run(requested);
if (watched.value !== requested) return;
// A refresh that changed nothing must not redraw the canvas, which would
// close any menu open on it.
trail.value = keepValue(trail.value, next);
if (next.run.dry) tested.value = keepRows(tested.value, [workflowRun(next.run), ...tested.value.filter((run) => run.id !== next.run.id)]);
stagesError.value = "";
} catch (cause) {
if (watched.value === requested) stagesError.value = describeError(cause, errors.workflows.runs.stagesNotLoaded);
}
}
// "Current definition" is a choice too, and a refresh must not undo it.
function pick(id: string): void {
picked = true;
watched.value = id;
}
async function refresh(): Promise<void> {
await loadRuns();
await loadStages();
await Promise.all([loadRuns(), loadTrail()]);
}
watch(workflow, () => {
picked = false;
runs.value = [];
watched.value = "";
error.value = "";
void refresh();
}, { immediate: true });
watch(
workflow,
() => {
picked = false;
listed.value = [];
tested.value = [];
watched.value = "";
trail.value = undefined;
error.value = "";
void refresh();
},
{ immediate: true },
);
watch(watched, () => {
stages.value = [];
attempt.value = 0;
pinned.value = undefined;
void loadStages();
trail.value = undefined;
void loadTrail();
});
useLiveResource("tasks", () => void refresh(), 2000);
useLiveResource(null, () => void refresh(), 1000);
const timer = setInterval(() => {
if (!document.hidden && trail.value && going(trail.value.run.state)) void refresh();
}, 1500);
onScopeDispose(() => clearInterval(timer));
const watchedRun = computed(() => {
const run = runs.value.find((run) => String(run.id) === watched.value);
return run && pinned.value ? { ...run, workflow_definition_yaml: pinned.value } : run;
const stages = computed(() => (trail.value && trail.value.run.id === watched.value ? stageRuns(trail.value.stages) : []));
const watchedRun = computed<WorkflowRun | undefined>(() => {
const read = trail.value && trail.value.run.id === watched.value ? trail.value : undefined;
const listed = runs.value.find((run) => run.id === watched.value);
if (read) return { ...workflowRun(read.run), workflow_definition_yaml: read.definition ?? "" };
return listed;
});
/** Watches a run that just started, once the task list has it. */
async function follow(id: number | string): Promise<void> {
/** Watches a run that has just started, test run or live. */
async function follow(id: string): Promise<void> {
picked = true;
// Changing the watched run loads its stages; only the list needs a read.
watched.value = String(id);
await loadRuns();
watched.value = id;
await refresh();
}
return { runs, error, loading, watched, watchedRun, stages, stagesError, attempt, pick, follow, refresh };
return { runs, error, loading, watched, watchedRun, trail, stages, stagesError, pick, follow, refresh };
}
+5 -3
View File
@@ -54,7 +54,8 @@ export function validationLabel(parsed: WorkflowParse): string {
export function parseWorkflowYaml(
source: string,
vocabulary: StepTypeInfo[] = [],
vocabulary: StepTypeInfo[],
id: string,
): WorkflowParse {
const document = parseDocument(source);
const problem = document.errors[0];
@@ -71,8 +72,9 @@ export function parseWorkflowYaml(
return { ok: false, message: errors.workflows.yaml.notMapping };
}
const id = typeof value.id === "string" ? value.id.trim() : "";
if (!id) return { ok: false, message: "workflow id is required" };
// The workflow is named by its page, so a document that names itself would be
// refused as an unknown field.
if ("id" in value) return { ok: false, message: "a workflow is named by its page, not by an id field" };
const steps = value.steps;
if (steps === undefined || steps === null || steps === "")
-45
View File
@@ -7,11 +7,6 @@ import {
commandBody,
applyStatusForKind,
} from "../src/stores/settings.ts";
import {
upsertWorkflowDefinition,
restoreShippedDefinitions,
removeWorkflowDefinition,
} from "../src/stores/workflows.ts";
test("control-plane commands keep the edited version and typed values", () => {
assert.deepEqual(
@@ -36,46 +31,6 @@ test("control-plane commands keep the edited version and typed values", () => {
);
});
test("workflow edits replace by id without dropping sibling definitions", () => {
const original = {
definitions: [
{ id: "implement", yaml: "id: implement\nsteps: []\n" },
{ id: "tdd", yaml: "id: tdd\nsteps: []\n" },
],
};
assert.deepEqual(
upsertWorkflowDefinition(original, {
id: "implement",
yaml: "id: implement\nsteps:\n - type: implement.code\n",
}),
{
definitions: [
{
id: "implement",
yaml: "id: implement\nsteps:\n - type: implement.code\n",
},
{ id: "tdd", yaml: "id: tdd\nsteps: []\n" },
],
},
);
assert.deepEqual(removeWorkflowDefinition(original, "implement"), {
definitions: [{ id: "tdd", yaml: "id: tdd\nsteps: []\n" }],
});
assert.deepEqual(
restoreShippedDefinitions(
{ definitions: [...original.definitions, { id: "mine", yaml: "id: mine\n" }] },
{ definitions: [{ id: "implement", yaml: "shipped\n" }] },
),
{
definitions: [
{ id: "implement", yaml: "shipped\n" },
{ id: "tdd", yaml: "id: tdd\nsteps: []\n" },
{ id: "mine", yaml: "id: mine\n" },
],
},
);
});
test("apply status names a process behind the stored version and one that stopped reporting", () => {
const records = [
{
+3 -4
View File
@@ -68,8 +68,7 @@ test("parallel authoring preserves branches and their YAML while guarding destru
test("existing invalid step ids become reference-safe without losing references", async () => {
const { normalizeStepIDs, earlierStepIDs } = await import("../src/workflows/workflow-edit.ts");
const { parseWorkflowYaml } = await import("../src/workflows/workflow-yaml.ts");
const original = `id: review
# Keep this comment.
const original = `# Keep this comment.
steps:
- {id: write-a-prd, type: agent.run}
- id: Write a PRD
@@ -85,7 +84,7 @@ steps:
settings:
message: "{{ steps.Write a PRD.summary }} and {{ steps.123 title.summary }}"
`;
assert.equal(parseWorkflowYaml(original).ok, false);
assert.equal(parseWorkflowYaml(original, [], "review").ok, false);
const normalized = normalizeStepIDs(original);
assert.match(normalized, /Keep this comment/);
const data = parse(normalized);
@@ -96,7 +95,7 @@ steps:
assert.equal(data.steps[3].when, "steps.write-a-prd-2.result.ready");
assert.equal(data.steps[3].settings.message, "{{ steps.write-a-prd-2.summary }} and {{ steps.step-123-title.summary }}");
assert.deepEqual(earlierStepIDs(normalized, ["steps", 3]), ["write-a-prd", "write-a-prd-2", "step-123-title"]);
assert.equal(parseWorkflowYaml(normalized).ok, true);
assert.equal(parseWorkflowYaml(normalized, [], "review").ok, true);
for (const [id, expected] of [
["UPPER", "upper"], ["under_score", "under-score"], ["123", "step-123"],
["trailing-", "trailing"], ["double--dash", "double-dash"],
+7 -9
View File
@@ -55,10 +55,9 @@ test("a branch node still resumes the run at its parallel step", () => {
});
});
test("a step the server cannot resume by name asks for an id", () => {
test("a step without an id resumes by its type and position", () => {
const graph = withRuns(
workflowGraph(`id: w
repository: none
workflowGraph(`repository: none
steps:
- {id: plan, type: agent.run, settings: {mission: p}}
- {type: agent.run, settings: {mission: a}}
@@ -67,14 +66,13 @@ steps:
`),
[
{ name: "plan", status: "succeeded" },
{ name: "agent.run", status: "succeeded" },
{ name: "agent.run", status: "succeeded" },
{ name: "agent.run@1", status: "succeeded" },
{ name: "agent.run@2", status: "succeeded" },
{ name: "last", status: "failed" },
],
);
assert.deepEqual(restartAt(graph, ["steps", 0]), { label: "Re-run from here", from: "plan" });
// A repeated name, and a step whose predecessor's name repeats, are refused.
for (const at of [1, 3]) {
assert.equal(restartAt(graph, ["steps", at])?.blocked, true, `step ${at}`);
}
// Two steps of one type are told apart by their position, so both resume.
assert.deepEqual(restartAt(graph, ["steps", 1]), { label: "Re-run from here", from: "agent.run@1" });
assert.deepEqual(restartAt(graph, ["steps", 3]), { label: "Resume from here", from: "last" });
});
+15 -17
View File
@@ -4,17 +4,16 @@ import test from "node:test";
const { parseWorkflowYaml, yamlLines } =
await import("../src/workflows/workflow-yaml.ts");
/** A definition in the shape the server writes: id, then typed steps. */
const DEFINITION = `id: bootstrap
steps:
/** A definition in the shape the server stores: typed steps, no id. */
const DEFINITION = `steps:
- type: bootstrap.prepare
- type: bootstrap.apply
settings:
mode: fast
`;
test("a definition parses into its id and its steps, in order", () => {
const parsed = parseWorkflowYaml(DEFINITION);
test("a definition parses into its name and its steps, in order", () => {
const parsed = parseWorkflowYaml(DEFINITION, [], "bootstrap");
assert.equal(parsed.ok, true);
if (!parsed.ok) return;
assert.equal(parsed.id, "bootstrap");
@@ -28,14 +27,13 @@ test("a definition parses into its id and its steps, in order", () => {
});
test("the preview reads the YAML as typed, not a regex over it", () => {
const parsed = parseWorkflowYaml(`id: x
steps:
const parsed = parseWorkflowYaml(`steps:
- type: a
settings:
nested:
- type: not-a-step
- type: b
`);
`, [], "x");
assert.equal(parsed.ok, true);
if (!parsed.ok) return;
assert.deepEqual(
@@ -46,24 +44,24 @@ steps:
test("invalid workflow structures identify the field that prevents saving", () => {
for (const [source, message] of [
["steps:\n - type: a\n", /id/],
["id: x\n", /steps/],
["id: x\nsteps:\n - type: a\n - settings: {}\n", /type/],
["id: x\nsteps:\n - type: a\n", /named by its page/],
["repository: none\n", /steps/],
["steps:\n - type: a\n - settings: {}\n", /type/],
["- a\n- b\n", /mapping/],
['"just a string"\n', /mapping/],
["id: x\nsteps: 3\n", /steps/],
["id: x\nsteps:\n - type: a\n when: what\n", /when/],
["id: x\nsteps:\n - type: a\n retry: {attempts: 2, backoff: yes}\n", /backoff/],
["id: x\nsteps:\n - type: a\n retry: {attempts: 2, backoff: -1s}\n", /backoff/],
["steps: 3\n", /steps/],
["steps:\n - type: a\n when: what\n", /when/],
["steps:\n - type: a\n retry: {attempts: 2, backoff: yes}\n", /backoff/],
["steps:\n - type: a\n retry: {attempts: 2, backoff: -1s}\n", /backoff/],
] as const) {
const parsed = parseWorkflowYaml(source);
const parsed = parseWorkflowYaml(source, [], "x");
assert.equal(parsed.ok, false, source);
if (!parsed.ok) assert.match(parsed.message, message, source);
}
});
test("a YAML syntax error is reported with the line it is on", () => {
const parsed = parseWorkflowYaml("id: x\nsteps: [unclosed\n");
const parsed = parseWorkflowYaml("steps: [unclosed\n", [], "x");
assert.equal(parsed.ok, false);
if (parsed.ok) return;
assert.ok(parsed.message.length > 0, "an error with no words says nothing");