fix(ui): repair settings editing and workflow diagnostics

This commit is contained in:
sam committed 2026-10-16 23:55:58 +11:00
1 parent 3229de9b3b
commit 41cd938748
46 files changed
+708 -240

No files matched your search

@@ -14,50 +14,57 @@ const props = defineProps<{ id?: string; disabled?: boolean; units?: DurationUni
const model = defineModel<string>({ required: true });
const units = computed(() => props.units ?? DURATION_UNITS);
const amount = ref(0);
const amount = ref<string | number>(0);
const invalid = computed(() => amount.value !== "" && (!Number.isFinite(Number(amount.value)) || Number(amount.value) < 0));
const unit = ref<DurationUnit>("s");
watch(
model,
(text) => {
const ms = parseGoDuration(text ?? "");
if (ms === null) return;
if (joinDuration(amount.value, unit.value) === ms) return;
if (ms === null) { amount.value = text ?? ""; return; }
if (amount.value !== "" && !invalid.value && joinDuration(Number(amount.value), unit.value) === ms) return;
const split = splitDuration(ms);
amount.value = split.value;
unit.value = units.value.includes(split.unit) ? split.unit : "ms";
unit.value = units.value.includes(split.unit) ? split.unit : (units.value[0] ?? "s");
amount.value = ms / joinDuration(1, unit.value);
},
{ immediate: true },
);
function emitChange() {
if (!Number.isFinite(amount.value) || amount.value < 0) return;
model.value = formatGoDuration(joinDuration(amount.value, unit.value));
if (amount.value === "" || invalid.value) {
model.value = String(amount.value);
return;
}
model.value = formatGoDuration(joinDuration(Number(amount.value), unit.value));
}
</script>
<template>
<InputGroup class="w-48">
<InputGroupInput
:id="id"
v-model.number="amount"
type="number"
min="0"
inputmode="decimal"
class="font-mono"
:disabled="disabled"
@change="emitChange"
/>
<InputGroupAddon align="inline-end">
<select
v-model="unit"
aria-label="Unit"
class="bg-transparent font-mono text-xs text-muted-foreground outline-none"
<div class="w-48">
<InputGroup>
<InputGroupInput
:id="id"
:model-value="amount"
type="text"
:aria-invalid="invalid ? true : undefined"
@update:model-value="(value: string | number) => { amount = value; emitChange(); }"
inputmode="decimal"
class="font-mono"
:disabled="disabled"
@change="emitChange"
>
<option v-for="u in units" :key="u" :value="u">{{ u }}</option>
</select>
</InputGroupAddon>
</InputGroup>
/>
<InputGroupAddon align="inline-end">
<select
v-model="unit"
aria-label="Unit"
class="bg-transparent font-mono text-xs text-muted-foreground outline-none"
:disabled="disabled"
@change="emitChange"
>
<option v-for="u in units" :key="u" :value="u">{{ u }}</option>
</select>
</InputGroupAddon>
</InputGroup>
<p v-if="invalid" role="alert" class="mt-1 text-xs text-danger">Enter a number zero or greater.</p>
</div>
</template>
+5 -1
View File
@@ -3,10 +3,14 @@ import { computed } from "vue";
import { TableCell, TableRow } from "@/components/ui/table";
import { ago } from "@/lib/format";
import { useOrgStore } from "@/stores/org";
import { activityDetail } from "./activity-detail";
import { describeTimelineEvent } from "@/tasks/timeline-event";
import { useTasksStore, type ActivityEvent } from "@/stores/tasks";
const identities = useOrgStore();
identities.watchIdentities();
/**
* One row of the live activity table. A row whose event resolves to a task is
* a link to it, and has to behave like one for a keyboard: Enter and Space both
@@ -20,7 +24,7 @@ const taskID = computed(() => tasks.taskIDFor(props.event));
// The detail is cut to one line by activityDetail and clamped again in the
// cell so a long unbroken token (a path, a URL, a hash) cannot widen the column
// past the table. Unclamped, this made the dashboard 7,481px tall.
const detail = computed(() => activityDetail(props.event));
const detail = computed(() => activityDetail(props.event, identities.identityName));
function open() {
if (taskID.value > 0) emit("open", taskID.value);
+5 -1
View File
@@ -27,6 +27,7 @@ import { useSessionStore } from "@/stores/session";
import { useTasksStore } from "@/stores/tasks";
import { useAlerts } from "@/alerts/use-alerts";
import ActivityRow from "./ActivityRow.vue";
import { useOrgStore } from "@/stores/org";
import { activityDetail } from "./activity-detail";
import {
ACTIVITY_FILTERS,
@@ -37,6 +38,9 @@ import {
import { groupActivity, type ActivityGroup } from "./activity-group";
import { describeTimelineEvent } from "@/tasks/timeline-event";
const identities = useOrgStore();
identities.watchIdentities();
/**
* The last 50 events, newest first, with the stream's own state on the card and
* the All / Tasks / System filter over it. The filter and the grouping rules
@@ -82,7 +86,7 @@ function isOpen(group: ActivityGroup): boolean {
// The collapsed group row shows what its newest event would have shown, so
// expanding and collapsing moves no information.
function groupDetail(group: ActivityGroup) {
return activityDetail(group.representative);
return activityDetail(group.representative, identities.identityName);
}
function groupWhen(group: ActivityGroup) {
+8 -1
View File
@@ -19,6 +19,8 @@ const CELL_LIMIT = 160;
export interface ActivityDetailInput {
detail?: unknown;
message?: unknown;
actor_id?: string;
principal_id?: string;
}
/** The cell's content: the rendered line, the payload, and whether they differ. */
@@ -35,8 +37,13 @@ export interface ActivityDetail {
*/
export function activityDetail(
event: ActivityDetailInput | undefined,
identityName?: (id: string) => string,
): ActivityDetail {
const full = String(event?.detail || event?.message || "");
let full = String(event?.detail || event?.message || "");
if (identityName) {
for (const id of [event?.actor_id, event?.principal_id])
if (id) full = full.replaceAll(id, identityName(id));
}
if (!full) return { text: "", full: "", truncated: false };
// The first line that says something: agent output often opens with blanks.
+7 -2
View File
@@ -31,6 +31,7 @@ const policies = ref<Policy[]>([]);
const shipped = ref<string[]>([]);
const error = ref<string | null>(null);
const saving = ref(false);
const loading = ref(true);
const blank = (): Policy => ({ id: "", level: "org", text: "" });
const draft = ref<Policy>(blank());
@@ -53,6 +54,7 @@ const canSave = computed(
);
async function load(): Promise<void> {
loading.value = true;
try {
const response = await api.policies<{ policies: Policy[]; shipped: string[] }>();
policies.value = response.policies;
@@ -60,6 +62,8 @@ async function load(): Promise<void> {
error.value = null;
} catch (err) {
error.value = (err as Error).message;
} finally {
loading.value = false;
}
}
@@ -97,7 +101,7 @@ onMounted(load);
<template>
<div>
<p v-if="error" role="alert" class="mb-4 text-sm text-danger">{{ error }}</p>
<div v-if="error" role="alert" class="mb-4 text-sm text-danger"><p>{{ error }}</p><Button variant="outline" size="sm" @click="load">Retry</Button></div>
<Card class="mb-4">
<CardHeader>
@@ -107,7 +111,8 @@ onMounted(load);
</CardAction>
</CardHeader>
<CardContent class="flex flex-col gap-3">
<p v-if="!policies.length" class="text-sm text-fg-subtle">No policies yet.</p>
<p v-if="loading" role="status" class="text-sm text-fg-muted">Loading policies…</p>
<p v-else-if="!error && !policies.length" class="text-sm text-fg-subtle">No policies yet.</p>
<div
v-for="p in policies"
:key="`${p.level}/${scope(p)}/${p.id}`"
+2
View File
@@ -5,6 +5,7 @@ import { Plus, Trash2 } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useSettingsStore } from "@/stores/settings";
import SettingsSaveBar from "@/settings/SettingsSaveBar.vue";
import DraftHint from "@/settings/DraftHint.vue";
/**
@@ -92,5 +93,6 @@ const eyebrow = "mb-2 text-[11px] font-medium tracking-[0.06em] text-fg-subtle u
</form>
</div>
</template>
<SettingsSaveBar />
</div>
</template>
+3 -2
View File
@@ -73,6 +73,7 @@ function setQuery(patch: Record<string, string | undefined>) {
}
const windows: Record<string, number> = { "24h": 86_400_000, "7d": 604_800_000, "30d": 2_592_000_000 };
const actorName = (id: string) => entries.value.find((entry) => entry.actor === id)?.actor_name || id;
const actors = computed(() => [...new Set(entries.value.map((e) => e.actor))].sort());
const sectionOptions = computed(() => {
const options = catalog.value.map((r) => ({ value: r.kind, label: r.title }));
@@ -130,7 +131,7 @@ const restorable = (entry: AuditEntry) =>
<SelectTrigger class="w-48" aria-label="Changed by"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem :value="ALL">Anyone</SelectItem>
<SelectItem v-for="a in actors" :key="a" :value="a">{{ a }}</SelectItem>
<SelectItem v-for="a in actors" :key="a" :value="a">{{ actorName(a) }}</SelectItem>
</SelectContent>
</Select>
<Select v-model="since">
@@ -178,7 +179,7 @@ const restorable = (entry: AuditEntry) =>
</TableCell>
<TableCell class="font-mono text-xs">{{ entry.version }}</TableCell>
<TableCell class="truncate" :title="`${entry.actor} · ${entry.source}`">
{{ entry.actor }}<span class="text-fg-subtle"> · {{ entry.source }}</span>
{{ entry.actor_name || entry.actor }}<span class="text-fg-subtle"> · {{ entry.source }}</span>
</TableCell>
<TableCell class="py-1 text-right">
<Button
+7 -15
View File
@@ -45,7 +45,7 @@ const resources = computed(() => resourcesForPage(catalog.value, "schedules"));
const jobs = computed(() => store.drafts[KIND]?.value as Job[] | undefined);
const error = computed(() => store.pageErrorFor(KIND));
const issues = computed(() => store.issuesFor(KIND));
const jobIssue = (i: number) => issues.value.find((entry) => entry.path === `${i}.id`);
const jobIssue = (i: number) => issues.value.find((entry) => entry.path.startsWith(`${i}.`));
const whenKinds = [
{ value: "interval", label: "Every" },
@@ -67,9 +67,9 @@ const unsaved = computed(() => store.changesFor(KIND).length > 0);
function add() {
if (unsaved.value || !jobs.value) return;
jobs.value.push({
id: "",
id: crypto.randomUUID(),
kind: "workflow",
detail: "",
detail: "Scheduled task",
pool: "",
schedule: { kind: "interval", interval: "24h0m0s" },
target: {},
@@ -122,12 +122,10 @@ const whenKind = (job: Job) => job.schedule.kind || "interval";
<span v-if="job.next_run" class="text-xs text-fg-subtle">Next run {{ new Date(job.next_run).toLocaleString() }}</span>
</template>
<template #default="{ item: job, index: i }">
<SettingRow label="ID" :for="`job-${i}-id`">
<div class="flex flex-wrap items-center gap-3">
<Input :id="`job-${i}-id`" v-model="job.id" class="max-w-sm font-mono" :aria-invalid="jobIssue(i) ? true : undefined" />
<DraftHint :kind="KIND" :path="`${i}.id`" />
</div>
<p v-if="jobIssue(i)" class="mt-1.5 text-xs text-danger">{{ jobIssue(i)?.message }}</p>
<SettingRow label="Schedule name" :for="`job-${i}-name`" hint="Used as the task title for scheduled workflows.">
<Input :id="`job-${i}-name`" v-model="job.detail" class="max-w-md" />
<DraftHint :kind="KIND" :path="`${i}.detail`" />
<p v-if="jobIssue(i)" class="mt-1.5 text-xs text-danger" role="alert">{{ jobIssue(i)?.message }}</p>
</SettingRow>
<SettingRow label="Does">
<div class="flex flex-wrap items-center gap-3">
@@ -144,12 +142,6 @@ const whenKind = (job: Job) => job.schedule.kind || "interval";
<DraftHint :kind="KIND" :path="`${i}.target.chat_id`" />
</div>
</SettingRow>
<SettingRow v-else label="Task title" :for="`job-${i}-title`" hint="Empty: the ID.">
<div class="flex flex-wrap items-center gap-3">
<Input :id="`job-${i}-title`" v-model="job.detail" class="max-w-md" />
<DraftHint :kind="KIND" :path="`${i}.detail`" />
</div>
</SettingRow>
<SettingRow :label="job.kind === 'chat' ? 'Message' : 'Instructions'" :for="`job-${i}-text`">
<Textarea :id="`job-${i}-text`" v-model="job.payload.text" :rows="3" />
<DraftHint :kind="KIND" :path="`${i}.payload.text`" />
+24 -10
View File
@@ -14,7 +14,8 @@ import {
import { Spinner } from "@/components/ui/spinner";
import { Badge } from "@/components/ui/badge";
import { useSettingsStore } from "@/stores/settings";
import { formatValue } from "./changes";
import { diffValues, formatValue } from "./changes";
import type { SettingsSchema } from "@/workflows/workflow-yaml";
const store = useSettingsStore();
const { reviewing } = storeToRefs(store);
@@ -23,11 +24,24 @@ const saving = ref(false);
const titleOf = (kind: string) =>
store.catalog.find((item) => item.kind === kind)?.title ?? kind;
function fieldLabel(kind: string, path: string): string {
let schema: SettingsSchema;
try { schema = JSON.parse(store.catalog.find((item) => item.kind === kind)?.schema_json || "{}"); }
catch { schema = {}; }
return path.split(".").map((part) => {
if (/^\d+$/.test(part)) {
schema = schema.items ?? {};
return `Item ${Number(part) + 1}`;
}
schema = schema.properties?.[part] ?? schema.additionalProperties ?? {};
return schema.title || part.replaceAll("_", " ");
}).join(" · ");
}
const sections = computed(() =>
store.dirtyKinds.map((kind) => ({
kind,
title: titleOf(kind),
changes: store.changesFor(kind),
changes: store.changesFor(kind).flatMap((change) => diffValues(change.before, change.after, change.path, true)),
issues: store.issuesFor(kind),
error: store.stateFor(kind).error,
restart:
@@ -36,7 +50,7 @@ const sections = computed(() =>
})),
);
const count = computed(() =>
sections.value.reduce((n, s) => n + s.changes.length, 0),
store.dirtyKinds.reduce((n, kind) => n + store.changesFor(kind).length, 0),
);
// Invalid fields block Save, and are listed in the bar so the operator knows
// before opening the review. Both read the store's one draft diff.
@@ -63,18 +77,18 @@ async function save() {
<template>
<div
v-if="count > 0"
class="sticky bottom-4 z-30 mt-auto rounded-lg border border-border bg-popover shadow-[var(--shadow-md)]"
class="sticky bottom-24 z-30 mt-auto rounded-lg border border-border bg-popover shadow-[var(--shadow-md)]"
role="region"
aria-label="Unsaved changes"
>
<div class="flex items-center gap-3 px-4 py-3">
<div class="flex flex-wrap items-center gap-3 px-4 py-3">
<span
class="size-2 shrink-0 rounded-full"
:class="invalid.length ? 'bg-danger' : 'bg-primary'"
aria-hidden="true"
/>
<p class="min-w-0 flex-1 truncate text-sm">
<span class="font-medium">{{ count }} unsaved {{ count === 1 ? "change" : "changes" }}</span>
<p class="min-w-40 flex-1 text-sm">
<span class="font-medium">{{ count }} unsaved settings {{ count === 1 ? "change" : "changes" }}</span>
<span class="text-fg-subtle"> · {{ sections.map((s) => s.title).join(", ") }}</span>
</p>
<Button variant="ghost" size="sm" @click="discardAll">Discard</Button>
@@ -123,9 +137,9 @@ async function save() {
</header>
<ul class="divide-y divide-border font-mono text-xs">
<li v-for="change in section.changes" :key="change.path" class="px-3 py-2">
<p class="mb-1 text-fg-subtle">{{ change.path }}</p>
<p class="truncate text-danger">− {{ formatValue(change.before) }}</p>
<p class="truncate text-ok">+ {{ formatValue(change.after) }}</p>
<p class="mb-1 font-sans font-medium">{{ fieldLabel(section.kind, change.path) }}</p>
<p class="whitespace-pre-wrap break-words text-danger"><span class="font-sans">Before: </span>{{ formatValue(change.before) }}</p>
<p class="whitespace-pre-wrap break-words text-ok"><span class="font-sans">After: </span>{{ formatValue(change.after) }}</p>
</li>
</ul>
<ul
+3 -20
View File
@@ -1,11 +1,10 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { computed } from "vue";
import { useRoute } from "vue-router";
import { hiddenPaths, settingsNav } from "@/lib/nav";
import { cn } from "@/lib/utils";
import { useSessionStore } from "@/stores/session";
import { useSettingsStore } from "@/stores/settings";
import RestartPendingBanner from "./RestartPendingBanner.vue";
import SettingsSaveBar from "./SettingsSaveBar.vue";
@@ -13,22 +12,6 @@ const route = useRoute();
const session = useSessionStore();
const items = computed(() => settingsNav(hiddenPaths(session.sections)));
// Drafts live in the store, so moving between Settings pages keeps them;
// leaving Settings, or the page, with edits unsaved asks first.
const store = useSettingsStore();
const dirty = () => store.dirtyKinds.length > 0;
const removeGuard = useRouter().beforeEach((to) => {
if (to.meta.settings || !dirty()) return true;
return window.confirm("Leave Settings with unsaved changes?");
});
const warnUnload = (event: BeforeUnloadEvent) => {
if (dirty()) event.preventDefault();
};
onMounted(() => window.addEventListener("beforeunload", warnUnload));
onBeforeUnmount(() => {
removeGuard();
window.removeEventListener("beforeunload", warnUnload);
});
</script>
<template>
@@ -65,7 +48,7 @@ onBeforeUnmount(() => {
</nav>
<!-- At least a screen tall, so the sticky save bar always rests at the
viewport's bottom edge rather than under the last setting. -->
<div class="flex min-h-screen min-w-0 flex-1 flex-col">
<div class="mx-auto flex min-h-screen w-full min-w-0 max-w-[80ch] flex-1 flex-col">
<RestartPendingBanner />
<!-- Room below the last setting, so it can be scrolled up to eye level. -->
<div class="pb-[40vh]">
+7 -5
View File
@@ -23,18 +23,20 @@ const same = (a: unknown, b: unknown) =>
* array of plain values is one leaf, because its entries have no identity of
* their own. A row added or removed is a single change.
*/
export function diffValues(before: unknown, after: unknown, path = ""): Change[] {
export function diffValues(before: unknown, after: unknown, path = "", expandRows = false): Change[] {
if (same(before, after)) return [];
const at = (key: string | number) => (path ? `${path}.${key}` : String(key));
if (isRecord(before) && isRecord(after)) {
const keys = [...new Set([...Object.keys(before), ...Object.keys(after)])];
return keys.flatMap((key) => diffValues(before[key], after[key], at(key)));
if ((isRecord(before) && isRecord(after)) || (expandRows && (isRecord(before) || isRecord(after)))) {
const left = isRecord(before) ? before : {};
const right = isRecord(after) ? after : {};
const keys = [...new Set([...Object.keys(left), ...Object.keys(right)])];
return keys.flatMap((key) => diffValues(left[key], right[key], at(key), expandRows));
}
const rows = (v: unknown) => Array.isArray(v) && v.some(isRecord);
if (Array.isArray(before) && Array.isArray(after) && (rows(before) || rows(after))) {
const length = Math.max(before.length, after.length);
return Array.from({ length }, (_, i) => diffValues(before[i], after[i], at(i))).flat();
return Array.from({ length }, (_, i) => diffValues(before[i], after[i], at(i), expandRows)).flat();
}
return [{ path, before, after }];
}
+5
View File
@@ -63,6 +63,10 @@ export const useOrgStore = defineStore("org", () => {
const session = useSessionStore();
let stop: (() => void) | undefined;
function identityName(id: string): string {
return identities.value.find((actor) => actor.id === id)?.display_name || (/^[0-9a-f]+(?:-[0-9a-f]+){4}$/i.test(id) ? "Unavailable identity" : id);
}
async function loadIdentities(): Promise<void> {
try {
identities.value = (await api.identities<{ identities: Identity[] }>()).identities;
@@ -111,6 +115,7 @@ export const useOrgStore = defineStore("org", () => {
loadOrg,
viewOrg,
identities,
identityName,
identityError,
identityBusy,
watchIdentities,
+13 -1
View File
@@ -1,5 +1,5 @@
import { defineStore } from "pinia";
import { computed, onScopeDispose, reactive, ref } from "vue";
import { computed, onScopeDispose, reactive, ref, watch } from "vue";
import { useSessionStore } from "./session.ts";
import { api } from "../lib/api.ts";
import type { ConfigView } from "../settings/types.ts";
@@ -114,6 +114,7 @@ export interface ResourceRevision {
version: number;
value: unknown;
actor: string;
actor_name?: string;
source: string;
request_id: string;
at?: string;
@@ -129,6 +130,7 @@ export interface AuditEntry {
new_value: unknown;
version: number;
actor: string;
actor_name?: string;
source: string;
at?: string;
}
@@ -322,6 +324,16 @@ export const useSettingsStore = defineStore("settings", () => {
.filter((kind) => changesFor(kind).length > 0),
);
// Drafts survive in-app navigation; only unloading the document can lose them.
const warnUnload = (event: BeforeUnloadEvent) => event.preventDefault();
if (typeof window !== "undefined") {
watch(dirtyKinds, (kinds) => {
window.removeEventListener("beforeunload", warnUnload);
if (kinds.length) window.addEventListener("beforeunload", warnUnload);
});
onScopeDispose(() => window.removeEventListener("beforeunload", warnUnload));
}
/** Invalid fields across every dirty section. Derived from dirtyKinds, so a
* save can only be blocked by a section that has something to save. */
const invalidFields = computed<BlockingField[]>(() =>
+1
View File
@@ -82,6 +82,7 @@ export const useWorkflowsStore = defineStore("workflows", () => {
return {
state,
error: computed(() => settings.catalogError || state.value.error),
collection,
shipped,
stepTypes,
+3 -1
View File
@@ -127,6 +127,7 @@ const startedAt = computed(() => {
timeLimit
}}</span>
</div>
<p v-if="attempt.error" role="alert" class="mb-3 whitespace-pre-wrap break-words text-sm text-danger">{{ attempt.error }}</p>
<ol
v-if="stages.length"
:aria-label="`Stages recorded in attempt ${attempt.attempt}`"
@@ -143,7 +144,8 @@ const startedAt = computed(() => {
</ol>
<Empty v-else>
<EmptyHeader>
<EmptyTitle>No stages</EmptyTitle>
<EmptyTitle>No workflow steps recorded</EmptyTitle>
<EmptyDescription>This attempt has no recorded workflow step execution.</EmptyDescription>
</EmptyHeader>
</Empty>
</div>
+3 -3
View File
@@ -4,7 +4,7 @@ import { ArrowUpRight } from "@lucide/vue";
import { ago, compact } from "@/lib/format";
import { cn } from "@/lib/utils";
import { statusKind, statusLabel } from "@/lib/task-meta";
import { stageStatusMeta } from "./stage-rail";
import StageRail from "./StageRail.vue";
import { STATUS_FILL } from "@/lib/status";
import { useTaskRun } from "./use-task-run";
@@ -15,7 +15,7 @@ import { duration } from "./timeline-event";
const run = useTaskRun();
const attempts = computed(() => [...(run.attempts?.attempts ?? [])].reverse());
const dot = (status?: string) => STATUS_FILL[statusKind(status ?? "")];
const dot = (status?: string) => STATUS_FILL[stageStatusMeta(status).kind];
const heading = "mb-2 text-[11px] font-medium tracking-[0.06em] text-fg-subtle uppercase";
</script>
@@ -38,7 +38,7 @@ const heading = "mb-2 text-[11px] font-medium tracking-[0.06em] text-fg-subtle u
>
<span class="size-2 shrink-0 rounded-full" :class="dot(a.status)" aria-hidden="true" />
<span class="flex-1">Attempt {{ a.attempt }}</span>
<span class="text-xs text-fg-subtle">{{ a.status ? statusLabel(a.status) : "" }}</span>
<span class="text-xs text-fg-subtle">{{ a.status ? stageStatusMeta(a.status).label : "" }}</span>
</button>
<p v-if="a.started_at" class="px-3 pb-1 pl-7 text-xs text-fg-subtle">
{{ ago(a.started_at) }}<template v-if="a.duration_ms"> · {{ duration(a.duration_ms) }}</template>
+3 -2
View File
@@ -10,6 +10,7 @@
* the agent's report rather than as archie's verdict.
*/
import type { StatusKind } from "@/lib/status";
import { statusKind, statusLabel } from "@/lib/task-meta";
import { describeTimelineEvent, type TimelineLine } from "./timeline-event";
import type { TaskEvent } from "./task-run";
@@ -25,12 +26,12 @@ const STAGE_STATUS: Record<string, StageStatusMeta> = {
interrupted: { label: "interrupted", kind: "warn" },
running: { label: "running", kind: "info" },
skipped: { label: "skipped", kind: "idle" },
unknown: { label: "unknown", kind: "idle" },
unknown: { label: "Outcome not recorded", kind: "idle" },
};
export function stageStatusMeta(status?: string | null): StageStatusMeta {
return (
STAGE_STATUS[status ?? ""] || { label: status || "unknown", kind: "idle" }
STAGE_STATUS[status ?? ""] || { label: statusLabel(status || "unknown"), kind: statusKind(status || "unknown") }
);
}
+1
View File
@@ -73,6 +73,7 @@ export interface Stage {
export interface Attempt {
attempt: number;
error?: string;
status?: string;
started_at?: string;
duration_ms?: number;
+14 -7
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { computed, ref } from "vue";
import { computed, ref, useId } from "vue";
import { CircleHelp, Plus, Trash2, X } from "@lucide/vue";
import { parse, stringify } from "yaml";
@@ -16,8 +16,9 @@ import type { InputSpec } from "./bind-event";
import { inputValue } from "./work-request";
import WorkflowPicker from "./WorkflowPicker.vue";
import { stepTitle } from "./workflow-graph";
import { settingsProblem, type SettingsSchema, type StepTypeInfo } from "./workflow-yaml";
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]; close: []; remove: [] }>();
@@ -46,6 +47,7 @@ const settings = computed<Record<string, unknown>>(() =>
typeof step.value.settings === "object" && step.value.settings !== null ? (step.value.settings as Record<string, unknown>) : {},
);
const earlier = computed(() => earlierStepIDs(props.yaml, props.path));
const flowProblem = computed(() => stepControlsProblem(step.value));
const problem = computed(() =>
info.value?.settings && step.value.settings ? settingsProblem(step.value.settings, info.value.settings, "settings") : "",
);
@@ -90,7 +92,8 @@ function setField(key: string, value: unknown): void {
// 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 {
setField("retry", { ...(step.value.retry as object), ...next });
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 };
@@ -325,12 +328,15 @@ const text = (key: string) => (typeof settings.value[key] === "string" ? (settin
<section class="space-y-2">
<div class="text-xs font-medium text-muted-foreground">Flow</div>
<p class="text-xs text-fg-muted">Leave the condition empty to always run. Use a field such as inputs.enabled, !inputs.skip, or steps.plan.result.ready == true.</p>
<p v-if="flowProblem" role="alert" class="text-xs text-danger">{{ flowProblem }}</p>
<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-[13px]">Run only when</span>
<Input
class="h-7 w-48 font-mono text-xs"
placeholder="always"
placeholder="inputs.enabled"
:aria-invalid="flowProblem && flowProblem.startsWith('when') ? true : undefined"
:model-value="(step.when as string) ?? ''"
@update:model-value="(value) => setField('when', String(value))"
/>
@@ -358,14 +364,15 @@ const text = (key: string) => (typeof settings.value[key] === "string" ? (settin
@update:model-value="(value) => setRetry({ attempts: String(value) === '' ? undefined : Number(String(value)) })"
/>
</label>
<label class="flex min-h-10 items-center gap-3 px-3 py-1.5">
<span class="flex-1 text-[13px]">Retry backoff</span>
<div class="flex min-h-10 items-center gap-3 px-3 py-1.5">
<label :for="`${uid}-backoff`" class="flex-1 text-[13px]">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 })"
/>
</label>
</div>
</div>
</section>
</div>
+15 -4
View File
@@ -67,6 +67,7 @@ const selected = defineModel<string>("selected", { required: true });
defineProps<{ runsCount?: number }>();
const id = ref("");
const yaml = ref("");
const loadedYaml = ref("");
const selectedStep = ref<StepPath | null>(null);
// The slide-in panel shows one thing: a step's editor, or the workflow's settings.
const settingsOpen = ref(false);
@@ -75,7 +76,7 @@ watch(selectedStep, (path) => {
});
const localError = ref("");
const { runs, watched, watchedRun, stages, attempt, pick, follow, refresh } = useWorkflowRuns(selected);
const { runs, error: runsError, loading: runsLoading, watched, watchedRun, stages, attempt, pick, follow, refresh } = useWorkflowRuns(selected);
const stepTab = ref("definition");
const selectedNode = computed(() => withRuns(workflowGraph(yaml.value), stages.value).nodes.find((node) => JSON.stringify(node.data.path) === JSON.stringify(selectedStep.value))?.data);
function openStep(path: StepPath): void {
@@ -157,15 +158,17 @@ function load(value: string): void {
);
id.value = entry?.id ?? value;
yaml.value = entry?.yaml ?? `id: ${value}\nsteps: []\n`;
loadedYaml.value = yaml.value;
selectedStep.value = null;
localError.value = "";
}
watch(selected, load, { immediate: true });
// The collection arrives after the first render; a later live update must not
// overwrite what is being typed, so it only fills an editor still empty.
// overwrite what is being typed, so it only refreshes an editor with no local edits.
watch(collection, () => {
if (!yaml.value) load(selected.value);
const incoming = collection.value.definitions.find((entry) => entry.id === selected.value);
if (incoming && yaml.value === loadedYaml.value && incoming.yaml !== loadedYaml.value) load(selected.value);
});
async function save(next: WorkflowDefinitionCollection): Promise<boolean> {
@@ -189,8 +192,10 @@ async function saveDraft(): Promise<void> {
next = removeWorkflowDefinition(next, previous);
if (
await save(upsertWorkflowDefinition(next, { id: nextID, yaml: yaml.value }))
)
) {
selected.value = nextID;
loadedYaml.value = yaml.value;
}
}
const confirmDelete = ref(false);
@@ -292,6 +297,12 @@ function syncScroll(event: Event): void {
<Spinner v-if="state.saving" data-icon="inline-start" />Save</Button>
</template>
</div>
<p v-if="runsLoading" class="text-xs text-fg-muted" role="status">Loading recent runs…</p>
<div v-else-if="runsError" class="text-sm text-danger" role="alert">
<p>Could not load recent runs: {{ runsError }}</p>
<Button type="button" variant="outline" size="sm" @click="refresh">Retry runs</Button>
</div>
<p v-if="watchedRun && !watchedRun.workflow_definition_yaml" class="text-xs text-fg-muted" role="status">No workflow snapshot was recorded for this run. Showing the current definition.</p>
<TabsContent value="canvas" class="space-y-2">
<!-- The canvas takes the height the viewport has left, so the page
itself does not scroll; the canvas pans. -->
+32 -6
View File
@@ -58,6 +58,7 @@ const store = useWorkflowsStore();
const data = ref<WorkflowsResponse>({});
const runs = ref<RunTask[]>([]);
const error = ref<string | null>(null);
const loading = ref(true);
async function load() {
try {
@@ -68,6 +69,8 @@ async function load() {
void loadWorkflowRuns();
} catch (err) {
error.value = String((err as Error).message || err);
} finally {
loading.value = false;
}
}
useLiveResource("tasks", () => void load(), 500);
@@ -138,11 +141,25 @@ const stages = computed(() => (data.value.stages ?? []).filter((s) => s.workflow
// The selected workflow's runs come from a workflow-filtered page: the global
// list above holds only the newest tasks of every workflow.
const workflowRuns = ref<RunTask[]>([]);
const runsLoading = ref(false);
const runsError = ref("");
let runsRequest = 0;
async function loadWorkflowRuns() {
const request = ++runsRequest;
const requested = selected.value;
const page = requested ? await api.taskPage<RunTask>({ workflow: requested }).catch(() => null) : null;
if (selected.value === requested) workflowRuns.value = page?.tasks ?? [];
runsLoading.value = true;
runsError.value = "";
workflowRuns.value = [];
try {
const page = requested ? await api.taskPage<RunTask>({ workflow: requested }) : null;
if (request === runsRequest) workflowRuns.value = page?.tasks ?? [];
} catch (err) {
if (request === runsRequest) runsError.value = String((err as Error).message || err);
} finally {
if (request === runsRequest) runsLoading.value = false;
}
}
watch(selected, () => void loadWorkflowRuns(), { immediate: true });
function create() {
@@ -190,7 +207,11 @@ const rate = (deliveredRuns = 0, total = 0) => (total ? deliveredRuns / total :
</AlertDialogContent>
</AlertDialog>
<p v-if="error" class="mb-4 text-sm text-danger" role="alert">Cannot reach archied: {{ error }}</p>
<div v-if="error || store.error" class="mb-4 text-sm text-danger" role="alert">
<p>{{ error || store.error }}</p>
<Button variant="outline" size="sm" @click="load(); store.load()">Retry</Button>
</div>
<p v-if="loading || (!store.state.resource && !store.error)" class="text-sm text-fg-muted" role="status">Loading workflows…</p>
<div class="grid items-start gap-6 lg:grid-cols-[24rem_minmax(0,1fr)]">
<ul class="flex gap-1 overflow-x-auto pb-2 lg:flex-col lg:gap-0.5 lg:overflow-visible lg:pb-0" aria-label="Workflows">
@@ -220,14 +241,14 @@ const rate = (deliveredRuns = 0, total = 0) => (total ? deliveredRuns / total :
</li>
</ul>
<section v-if="!selected" class="min-w-0 rounded-lg border border-border bg-card" aria-label="Workflow">
<section v-if="!selected && !loading && store.state.resource && !error" class="min-w-0 rounded-lg border border-border bg-card" aria-label="Workflow">
<Empty>
<EmptyHeader>
<EmptyTitle>No workflows</EmptyTitle>
</EmptyHeader>
</Empty>
</section>
<section v-else class="min-w-0 rounded-lg border border-border bg-card px-3 py-4 sm:px-5" aria-label="Workflow">
<section v-else-if="selected && store.state.resource" class="min-w-0 rounded-lg border border-border bg-card px-3 py-4 sm:px-5" aria-label="Workflow">
<header class="mb-2 flex flex-wrap items-center gap-2">
<h2 class="font-mono text-[15px] font-medium">{{ selected }}</h2>
<Badge v-if="provenance" variant="outline">{{ provenance }}</Badge>
@@ -251,7 +272,12 @@ const rate = (deliveredRuns = 0, total = 0) => (total ? deliveredRuns / total :
</template>
</template>
<template #runs>
<Empty v-if="!workflowRuns.length">
<p v-if="runsLoading" role="status" class="text-sm text-fg-muted">Loading runs…</p>
<div v-else-if="runsError" role="alert" class="text-sm text-danger">
<p>{{ runsError }}</p>
<Button variant="outline" size="sm" @click="loadWorkflowRuns">Retry</Button>
</div>
<Empty v-else-if="!workflowRuns.length">
<EmptyHeader>
<EmptyTitle>No runs yet</EmptyTitle>
</EmptyHeader>
+21 -8
View File
@@ -25,18 +25,28 @@ export function useWorkflowRuns(workflow: Ref<string>) {
const stages = ref<StageRun[]>([]);
const attempt = ref(0);
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 page = requested
? await api.taskPage<WorkflowRun>({ workflow: requested, limit: RECENT_RUNS }).catch(() => null)
: null;
if (workflow.value !== requested) return;
runs.value = (page?.tasks ?? []).sort((a, b) => Number(b.id) - Number(a.id));
if (!picked || (watched.value && !runs.value.some((run) => String(run.id) === watched.value)))
watched.value = runs.value[0] ? String(runs.value[0].id) : "";
const request = ++requestNumber;
loading.value = true;
try {
const page = requested ? await api.taskPage<WorkflowRun>({ workflow: requested, limit: RECENT_RUNS }) : null;
if (workflow.value !== requested || request !== requestNumber) return;
runs.value = (page?.tasks ?? []).sort((a, b) => Number(b.id) - Number(a.id));
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) : "";
} catch (cause) {
if (workflow.value === requested && request === requestNumber) error.value = String((cause as Error).message || cause);
} finally {
if (request === requestNumber) loading.value = false;
}
}
async function loadStages(): Promise<void> {
@@ -66,6 +76,9 @@ export function useWorkflowRuns(workflow: Ref<string>) {
watch(workflow, () => {
picked = false;
runs.value = [];
watched.value = "";
error.value = "";
void refresh();
}, { immediate: true });
watch(watched, () => {
@@ -84,5 +97,5 @@ export function useWorkflowRuns(workflow: Ref<string>) {
await refresh();
}
return { runs, watched, watchedRun, stages, attempt, pick, follow, refresh };
return { runs, error, loading, watched, watchedRun, stages, attempt, pick, follow, refresh };
}
+28
View File
@@ -1,4 +1,5 @@
import { parseDocument } from "yaml";
import { parseGoDuration } from "../components/ui/duration-input/duration.ts";
import { branchingOf } from "./workflow-edit.ts";
/**
@@ -87,6 +88,8 @@ export function parseWorkflowYaml(
const declared = new Set<string>();
for (const [i, step] of steps.entries()) {
const where = `workflow ${id} step ${i + 1}`;
const controls = stepControlsProblem(step);
if (controls) return { ok: false, message: `${where}: ${controls}` };
const branching = branchingOf(step);
if (branching) {
if (branching.kind === "switch" && !branching.on)
@@ -100,6 +103,7 @@ export function parseWorkflowYaml(
for (const [j, branchStep] of branchSteps.entries()) {
const branchWhere = `${where} branch ${branch} step ${j + 1}`;
const problem =
stepControlsProblem(branchStep) ||
checkStepType(branchStep, branchWhere, known, repository) ||
laterReference(branchStep, branchWhere, visible);
if (problem) return { ok: false, message: problem };
@@ -135,6 +139,30 @@ function declareID(step: unknown, declared: Set<string>): void {
if (isMapping(step) && typeof step.id === "string") declared.add(step.id);
}
/** The shared flow controls, checked in both the step panel and YAML editor. */
export function stepControlsProblem(step: unknown): string {
if (!isMapping(step)) return "";
if (step.when !== undefined && step.when !== "") {
if (typeof step.when !== "string") return "when must be a reference";
const operator = step.when.includes("==") ? "==" : step.when.includes("!=") ? "!=" : "";
const path = operator ? step.when.split(operator, 1)[0]!.trim() : step.when.trim().replace(/^!\s*/, "");
if (!/^(task|inputs|steps)\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*$/.test(path))
return "when must name a task, inputs or steps field, optionally prefixed with ! or compared using == or !=";
}
if (step.retry !== undefined) {
if (!isMapping(step.retry)) return "retry must be a mapping";
const { attempts, backoff } = step.retry;
if (typeof attempts !== "number" || !Number.isInteger(attempts) || attempts < 1 || attempts > 10)
return "retry.attempts must be a whole number from 1 to 10";
if (backoff !== undefined && backoff !== "") {
const duration = typeof backoff === "string" ? parseGoDuration(backoff) : null;
if (duration === null || duration < 0 || !Number.isFinite(duration))
return "retry.backoff must be a non-negative duration, such as 5s or 1m";
}
}
return "";
}
/** What is wrong with one typed step, or "" when nothing the page can see. */
function checkStepType(
step: unknown,