Merge branch 'main' into worktree-org-config

# Conflicts:
#	ui/src/schedules/SchedulesPage.vue
This commit is contained in:
sam committed 2026-11-22 11:24:30 +11:00
commit aefe2b81e9
32 files changed
+942 -817

No files matched your search

+6 -1
View File
@@ -109,7 +109,12 @@ func (m *Module) putSource(ctx context.Context, in *putSourceInput) (*httpapi.Re
// if there is one. It returns the new token when one was issued.
func (m *Module) sourceToSave(in *putSourceInput, stored *store.Source) (store.Source, string, error) {
explicit := in.Body.Verification != ""
src := store.Source{OrgID: m.orgID, Name: in.Name, Connector: in.Body.Connector, Verification: in.Body.Verification}
// The secret column is NOT NULL, so a source without a secret carries an
// empty value: the driver writes a nil slice as NULL.
src := store.Source{
OrgID: m.orgID, Name: in.Name, Connector: in.Body.Connector,
Verification: in.Body.Verification, HMACSecretSealed: []byte{},
}
switch {
case !explicit && stored != nil:
// Omitting the scheme keeps the stored one with its token or secret, so
+54
View File
@@ -0,0 +1,54 @@
package events
import (
"testing"
"filippo.io/age"
"github.com/samcharles93/archie-core/internal/platform/seal"
"github.com/samcharles93/archie-core/modules/events/internal/store"
)
// TestSavedSourceSecretIsSetOnlyForHMAC guards the NOT NULL hmac_secret_sealed
// column: a nil secret is written as NULL and fails the save, so token and none
// sources must carry an empty, non-nil secret and only HMAC a sealed one.
func TestSavedSourceSecretIsSetOnlyForHMAC(t *testing.T) {
id, err := age.GenerateX25519Identity()
if err != nil {
t.Fatal(err)
}
sealer, err := seal.New(id.String(), nil)
if err != nil {
t.Fatal(err)
}
m := &Module{orgID: "org", sealer: sealer}
tests := []struct {
name string
verify string
wantSecret bool
}{
{"none", store.None, false},
{"token", store.Token, false},
{"hmac", store.HMAC, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
in := &putSourceInput{Name: "hook"}
in.Body.Connector = "c"
in.Body.Verification = tt.verify
in.Body.HMACHeader = "X-Signature"
in.Body.HMACSecret = "not-a-real-secret" //nolint:gosec // fixture secret to be sealed
src, _, err := m.sourceToSave(in, nil)
if err != nil {
t.Fatal(err)
}
if src.HMACSecretSealed == nil {
t.Fatal("secret is nil, which the store writes as NULL")
}
if got := len(src.HMACSecretSealed) > 0; got != tt.wantSecret {
t.Fatalf("secret set = %v, want %v", got, tt.wantSecret)
}
})
}
}
+3 -3
View File
@@ -82,9 +82,9 @@ const queryKey = computed(() => JSON.stringify(query.value));
const columns: DataTableColumn<AuditRecord>[] = [
{ id: "event", label: "Event", fixed: true, class: "whitespace-normal" },
{ id: "target", label: "Target", fixed: true, class: "hidden sm:table-cell" },
{ id: "actor", label: "Actor", fixed: true, class: "hidden sm:table-cell" },
{ id: "when", label: "When", fixed: true, class: "hidden sm:table-cell" },
{ id: "target", label: "Target", fixed: true, hide: "sm", width: "14rem" },
{ id: "actor", label: "Actor", fixed: true, hide: "sm", width: "12rem" },
{ id: "when", label: "When", fixed: true, hide: "sm", width: "9rem" },
];
const status = ref("");
+7 -7
View File
@@ -19,13 +19,13 @@ const store = useDenialsStore();
const { denials, filters, more, loading, error } = storeToRefs(store);
const columns: DataTableColumn<Denial>[] = [
{ id: "at", label: "When", fixed: true, sort: (d) => d.at },
{ id: "principal", label: "Principal", fixed: true, class: "whitespace-normal" },
{ id: "action", label: "Action" },
{ id: "resource", label: "Resource", class: "whitespace-normal" },
{ id: "level", label: "Level" },
{ id: "policies", label: "Deciding policies", class: "hidden md:table-cell whitespace-normal" },
{ id: "count", label: "Count", sort: (d) => d.count },
{ id: "at", label: "When", fixed: true, width: "9rem", sort: (d) => d.at },
{ id: "principal", label: "Principal", fixed: true, width: "auto", class: "whitespace-normal" },
{ id: "action", label: "Action", width: "12rem" },
{ id: "resource", label: "Resource", width: "14rem", class: "whitespace-normal" },
{ id: "level", label: "Level", width: "6rem" },
{ id: "policies", label: "Deciding policies", hide: "md", width: "14rem", class: "whitespace-normal" },
{ id: "count", label: "Count", width: "6rem", sort: (d) => d.count },
];
onMounted(() => void store.load());
+6 -6
View File
@@ -35,12 +35,12 @@ const props = withDefaults(
const position = computed(() => new Map(props.entries.map((entry, i) => [entry, i])));
const columns: DataTableColumn<LogEntry>[] = [
{ id: "time", label: "Time", fixed: true, class: "w-0 whitespace-nowrap", sort: (e) => position.value.get(e) ?? 0 },
{ id: "level", label: "Level", fixed: true, class: "w-0" },
{ id: "service", label: "Service", hidden: !props.services, class: "w-0 whitespace-nowrap" },
{ id: "component", label: "Component", hidden: !props.services, class: "w-0 whitespace-nowrap" },
{ id: "stage", label: "Stage", hidden: props.services, class: "w-0 whitespace-nowrap" },
{ id: "message", label: "Message", fixed: true, class: "whitespace-normal" },
{ id: "time", label: "Time", fixed: true, width: "9rem", sort: (e) => position.value.get(e) ?? 0 },
{ id: "level", label: "Level", fixed: true, width: "6rem" },
{ id: "service", label: "Service", hidden: !props.services, width: "8rem" },
{ id: "component", label: "Component", hidden: !props.services, width: "9rem" },
{ id: "stage", label: "Stage", hidden: props.services, width: "9rem" },
{ id: "message", label: "Message", fixed: true, width: "auto", class: "whitespace-normal" },
];
// received_at restates the time; the rest have columns.
const shown = new Set(["received_at", "stage", "service", "component", ...props.omit]);
+36 -8
View File
@@ -11,13 +11,16 @@ import {
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils";
import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from "@/components/ui/context-menu";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import type { DataTableColumn } from "./types";
/**
* A table whose optional columns the operator chooses, remembered per browser
* under `storageKey`. Cells render through `#cell-<id>` slots, given the row;
* `#actions` fills a trailing cell and `#empty` replaces the body when there
* `#menu` fills a right-click menu with ContextMenuItems, `#actions` fills a
* trailing cell and `#empty` replaces the body when there
* are no rows. With `rowLink`, the whole row opens that route, so controls
* inside a cell must stop their click and keydown events. With a `#detail`
* slot and no `rowLink`, a row opens in place to show its detail beneath it.
@@ -35,7 +38,7 @@ const props = defineProps<{
/** The sort the table opens with, on a column that has one. */
initialSort?: { id: string; desc: boolean };
}>();
const slots = defineSlots<Record<string, (props: { row: Row }) => unknown> & { empty?: () => unknown; actions?: (props: { row: Row }) => unknown; detail?: (props: { row: Row }) => unknown }>();
const slots = defineSlots<Record<string, (props: { row: Row }) => unknown> & { empty?: () => unknown; actions?: (props: { row: Row }) => unknown; detail?: (props: { row: Row }) => unknown; menu?: (props: { row: Row }) => unknown }>();
const router = useRouter();
const chosen = useLocalStorage<string[]>(
@@ -72,6 +75,22 @@ const sorted = computed(() => {
const ariaSort = (id: string) => (sortBy.value?.id !== id ? "none" : sortBy.value.desc ? "descending" : "ascending");
const sortIcon = (id: string) => (sortBy.value?.id !== id ? ArrowUpDown : sortBy.value.desc ? ArrowDown : ArrowUp);
// A fixed layout: the first column takes what the others leave.
const grows = computed(() => (props.columns.some((c) => c.width === "auto") ? "auto" : props.columns[0]?.id));
const width = (column: DataTableColumn<Row>) =>
column.width === "auto" || (!column.width && grows.value === column.id) ? undefined : { width: column.width ?? "10rem" };
// The table never squeezes the growing column below 8rem: it scrolls instead.
// Each breakpoint sums only the columns it still shows.
const rem = (column: DataTableColumn<Row>) => (column.width === "auto" || (!column.width && grows.value === column.id) ? 8 : parseFloat(column.width ?? "10"));
const minimum = (keep: (column: DataTableColumn<Row>) => boolean) =>
`${shown.value.filter(keep).reduce((sum, c) => sum + rem(c), trailing.value ? 3 : 0)}rem`;
const minimums = computed(() => ({
"--min-lg": minimum(() => true),
"--min-md": minimum((c) => c.hide !== "md"),
"--min-sm": minimum((c) => !c.hide),
}));
const hidden = (column: DataTableColumn<Row>) => (column.hide ? (column.hide === "sm" ? "max-sm:hidden" : "max-md:hidden") : undefined);
const expandable = computed(() => !props.rowLink && !!slots.detail);
const expanded = ref(new Set<string>());
function open(row: Row): void {
@@ -90,13 +109,17 @@ function open(row: Row): void {
<template>
<!-- A sticky header sticks to the page's scrolling frame, so the table
must not be a scroll container of its own. -->
<Table :container-class="stickyHeader && 'overflow-visible'">
<Table class="table-fixed min-w-(--min-lg) max-md:min-w-(--min-md) max-sm:min-w-(--min-sm)" :style="minimums" :container-class="stickyHeader && 'overflow-visible'">
<colgroup>
<col v-for="column in shown" :key="column.id" :class="hidden(column)" :style="width(column)" />
<col v-if="trailing" class="w-12" />
</colgroup>
<TableHeader :class="stickyHeader && 'sticky top-0 z-10 bg-card shadow-[inset_0_-1px_0_var(--color-border)]'">
<TableRow>
<TableHead
v-for="column in shown"
:key="column.id"
:class="column.class"
:class="cn('truncate', hidden(column), column.class)"
:aria-sort="column.sort ? ariaSort(column.id) : undefined"
>
<Button v-if="column.sort" variant="ghost" size="sm" class="-ml-2.5" @click="cycleSort(column.id)">
@@ -104,7 +127,7 @@ function open(row: Row): void {
</Button>
<template v-else>{{ column.label }}</template>
</TableHead>
<TableHead v-if="trailing" class="w-0 text-right">
<TableHead v-if="trailing" class="text-right">
<DropdownMenu v-if="optional.length">
<DropdownMenuTrigger as-child>
<Button variant="ghost" size="icon-sm" aria-label="Columns" title="Columns"><Columns3 /></Button>
@@ -128,21 +151,23 @@ function open(row: Row): void {
<TableCell :colspan="shown.length + (trailing ? 1 : 0)"><slot name="empty" /></TableCell>
</TableRow>
<template v-for="row in sorted" :key="rowKey(row)">
<ContextMenu>
<ContextMenuTrigger as-child :disabled="!slots.menu">
<TableRow
:data-row-key="rowKey(row)"
:tabindex="expandable ? 0 : undefined"
:aria-expanded="expandable ? expanded.has(rowKey(row)) : undefined"
:class="['align-top', (rowLink || expandable) && 'cursor-pointer', rowClass?.(row)]"
:class="['align-middle', (rowLink || expandable) && 'cursor-pointer', rowClass?.(row)]"
@click="open(row)"
@keydown.enter.self.prevent="open(row)"
@keydown.space.self.prevent="open(row)"
>
<TableCell v-for="(column, cellIndex) in shown" :key="column.id" :class="column.class">
<TableCell v-for="(column, cellIndex) in shown" :key="column.id" :class="cn('overflow-hidden text-ellipsis', hidden(column), column.class)">
<RouterLink
v-if="cellIndex === 0 && rowLink"
:to="rowLink(row)"
:aria-label="rowLabel ? rowLabel(row) : undefined"
class="rounded-sm focus-visible:outline-2 focus-visible:outline-ring"
class="block truncate rounded-sm focus-visible:outline-2 focus-visible:outline-ring"
@click.stop
><slot :name="`cell-${column.id}`" :row="row"
/></RouterLink>
@@ -150,6 +175,9 @@ function open(row: Row): void {
</TableCell>
<TableCell v-if="trailing"><slot name="actions" :row="row" /></TableCell>
</TableRow>
</ContextMenuTrigger>
<ContextMenuContent v-if="slots.menu" class="min-w-40"><slot name="menu" :row="row" /></ContextMenuContent>
</ContextMenu>
<TableRow v-if="expandable && expanded.has(rowKey(row))" class="hover:bg-transparent">
<TableCell :colspan="shown.length + (trailing ? 1 : 0)" class="bg-muted/40 whitespace-normal">
<slot name="detail" :row="row" />
+6
View File
@@ -5,6 +5,12 @@ export interface DataTableColumn<Row = never> {
fixed?: boolean;
/** Hidden until the operator turns it on. */
hidden?: boolean;
/** A CSS length, or "auto" for the column that takes the space the others
* leave. The table lays columns out at fixed widths: a column without one
* is 10rem wide, and the first column grows unless another is "auto". */
width?: string;
/** Hides the column, header and cells, below this breakpoint. */
hide?: "sm" | "md";
class?: string;
/** Makes the header sort the loaded rows by this value. */
sort?: (row: Row) => string | number;
+39 -21
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { RouterLink } from "vue-router";
import { computed, onMounted, ref } from "vue";
import { RouterLink, useRoute, useRouter } from "vue-router";
import PageHeader from "@/base/PageHeader.vue";
import { Badge } from "@/components/ui/badge";
@@ -9,12 +9,13 @@ import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { MoreMenu } from "@/components/ui/more-menu";
import { ReadError } from "@/components/ui/read-error";
import { Section } from "@/components/ui/section";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Timestamp } from "@/components/ui/timestamp";
import { errors } from "@/copy/errors";
import { api, describeError, type ActionClass, type Judge } from "@/lib/api";
import { useRead } from "@/lib/use-read";
import { stateLabel } from "@/runs/state";
import ActionClassDetail from "./ActionClassDetail.vue";
import PolicyText from "./PolicyText.vue";
@@ -27,18 +28,28 @@ onMounted(() => {
void classes.reload();
});
const route = useRoute();
const router = useRouter();
const TABS = [
{ id: "rules", label: "Rules" },
{ id: "guards", label: "Guards" },
{ id: "classes", label: "Action classes" },
];
const tab = computed(() => (TABS.some((t) => t.id === route.query.tab) ? String(route.query.tab) : "rules"));
const show = (id: unknown) => void router.replace({ query: { ...route.query, tab: id === "rules" ? undefined : String(id) } });
const judgeColumns: DataTableColumn<Judge>[] = [
{ id: "name", label: "Guard", fixed: true, sort: (j) => j.name },
{ id: "mode", label: "Mode", fixed: true },
{ id: "latest", label: "Last evaluation" },
{ id: "name", label: "Guard", fixed: true, width: "auto", sort: (j) => j.name },
{ id: "mode", label: "Mode", fixed: true, width: "8rem" },
{ id: "latest", label: "Last evaluation", hide: "md", width: "28rem" },
];
const classColumns: DataTableColumn<ActionClass>[] = [
{ id: "action", label: "Action", fixed: true, sort: (c) => `${c.connector}.${c.action}` },
{ id: "target", label: "Target", sort: (c) => c.target_kind ?? "" },
{ id: "level", label: "Level", fixed: true, sort: (c) => c.level },
{ id: "count", label: "Approved in a row", sort: (c) => c.count },
{ id: "decisions", label: "Decisions", hidden: true, sort: (c) => c.decisions },
{ id: "last", label: "Last decided", sort: (c) => (c.last_decided_at ? Date.parse(c.last_decided_at) : 0) },
{ id: "action", label: "Action", fixed: true, width: "auto", sort: (c) => `${c.connector}.${c.action}` },
{ id: "target", label: "Target", hide: "md", width: "14rem", sort: (c) => c.target_kind ?? "" },
{ id: "level", label: "Level", fixed: true, width: "13rem", sort: (c) => c.level },
{ id: "count", label: "Approved in a row", hide: "md", width: "11rem", sort: (c) => c.count },
{ id: "decisions", label: "Decisions", hidden: true, hide: "md", width: "7rem", sort: (c) => c.decisions },
{ id: "last", label: "Last decided", hide: "sm", width: "9rem", sort: (c) => (c.last_decided_at ? Date.parse(c.last_decided_at) : 0) },
];
const resetError = ref("");
@@ -56,9 +67,16 @@ async function reset(c: ActionClass): Promise<void> {
<template>
<div>
<PageHeader title="Controls" />
<PolicyText kind="hard-rules" title="Hard rules" />
<PolicyText kind="change-request" title="Change-request rules" />
<Section title="Guards">
<Tabs :model-value="tab" class="mb-4" @update:model-value="show">
<TabsList variant="line" class="w-full justify-start">
<TabsTrigger v-for="t in TABS" :key="t.id" :value="t.id" class="flex-none px-3">{{ t.label }}</TabsTrigger>
</TabsList>
</Tabs>
<template v-if="tab === 'rules'">
<PolicyText kind="hard-rules" title="Hard rules" />
<PolicyText kind="change-request" title="Change-request rules" />
</template>
<div v-else-if="tab === 'guards'">
<ReadError v-if="judges.error.value" :message="judges.error.value" retry-label="Retry" @retry="judges.reload" />
<Skeleton v-else-if="!judges.data.value" class="h-16 w-full" />
<DataTable v-else :columns="judgeColumns" :rows="judges.data.value" :row-key="(j) => j.name" storage-key="judges">
@@ -75,8 +93,8 @@ async function reset(c: ActionClass): Promise<void> {
<template #empty><Empty><EmptyHeader><EmptyTitle>No guards</EmptyTitle></EmptyHeader></Empty></template>
</DataTable>
<p class="mt-2 text-caption text-fg-muted"><RouterLink class="underline" :to="{ path: '/settings/extensions', query: { kind: 'guards' } }">Manage guards</RouterLink></p>
</Section>
<Section title="Action classes">
</div>
<div v-else>
<p v-if="resetError" role="alert" class="mb-2 text-caption text-danger">{{ resetError }}</p>
<ReadError v-if="classes.error.value" :message="classes.error.value" retry-label="Retry" @retry="classes.reload" />
<Skeleton v-else-if="!classes.data.value" class="h-16 w-full" />
@@ -84,8 +102,8 @@ async function reset(c: ActionClass): Promise<void> {
<template #cell-action="{ row }"><span class="font-mono text-caption">{{ row.connector }}.{{ row.action }}</span></template>
<template #cell-target="{ row }">{{ row.target_kind }}<span v-if="row.environment" class="text-caption text-fg-muted"> · {{ row.environment }}</span></template>
<template #cell-level="{ row }">
<Badge variant="outline" :title="row.tightened_because || undefined">{{ row.level }}</Badge>
<span v-if="row.level !== row.default" class="text-caption text-fg-muted"> from {{ row.default }}</span>
<Badge variant="outline" :title="row.tightened_because || undefined">{{ stateLabel(row.level) }}</Badge>
<span v-if="row.level !== row.default" class="text-caption text-fg-muted"> from {{ stateLabel(row.default) }}</span>
</template>
<template #cell-count="{ row }">{{ row.count }}</template>
<template #cell-decisions="{ row }">{{ row.decisions }}</template>
@@ -93,11 +111,11 @@ async function reset(c: ActionClass): Promise<void> {
<template #detail="{ row }"><ActionClassDetail :id="row.id" /></template>
<template #actions="{ row }">
<MoreMenu :label="`${row.connector}.${row.action} actions`">
<DropdownMenuItem :disabled="row.level === row.default" @select="reset(row)">Reset to {{ row.default }}</DropdownMenuItem>
<DropdownMenuItem :disabled="row.level === row.default" @select="reset(row)">Reset to {{ stateLabel(row.default) }}</DropdownMenuItem>
</MoreMenu>
</template>
<template #empty><Empty><EmptyHeader><EmptyTitle>No action classes</EmptyTitle></EmptyHeader></Empty></template>
</DataTable>
</Section>
</div>
</div>
</template>
+9 -9
View File
@@ -44,12 +44,12 @@ const linked = computed(() => String(route.query.event ?? ""));
const time = (at?: string) => (at ? Date.parse(at) : 0);
const columns: DataTableColumn<EventRecord>[] = [
{ id: "received", label: "Received", fixed: true, sort: (e) => time(e.received_at) },
{ id: "source", label: "Source", fixed: true, sort: (e) => e.source },
{ id: "type", label: "Type", fixed: true, sort: (e) => e.type },
{ id: "matched", label: "Matched", sort: (e) => (e.matched ? 1 : 0) },
{ id: "occurred", label: "Occurred", hidden: true, sort: (e) => time(e.occurred_at) },
{ id: "linked", label: "Same as", hidden: true },
{ id: "type", label: "Type", fixed: true, width: "auto", sort: (e) => e.type },
{ id: "source", label: "Source", fixed: true, hide: "sm", width: "12rem", sort: (e) => e.source },
{ id: "matched", label: "Trigger", hide: "sm", width: "9rem", sort: (e) => (e.matched ? 1 : 0) },
{ id: "received", label: "Received", fixed: true, width: "7.5rem", sort: (e) => time(e.received_at) },
{ id: "occurred", label: "Occurred", hidden: true, width: "9rem", sort: (e) => time(e.occurred_at) },
{ id: "linked", label: "Same as", hidden: true, width: "10rem" },
];
</script>
@@ -87,13 +87,13 @@ const columns: DataTableColumn<EventRecord>[] = [
:initial-sort="{ id: 'received', desc: true }"
>
<template #cell-received="{ row }"><Timestamp :at="row.received_at" /></template>
<template #cell-source="{ row }">{{ row.source }}</template>
<template #cell-type="{ row }"><span class="font-mono text-caption">{{ row.type }}</span></template>
<template #cell-source="{ row }"><span class="font-mono">{{ row.source }}</span></template>
<template #cell-type="{ row }"><span class="font-mono">{{ row.type }}</span><span class="block text-caption text-fg-muted sm:hidden">{{ row.source }}</span></template>
<template #cell-matched="{ row }">
<Badge :variant="row.matched ? 'ok' : 'idle'">{{ row.matched ? "Matched" : "Unmatched" }}</Badge>
</template>
<template #cell-occurred="{ row }"><Timestamp :at="row.occurred_at" /></template>
<template #cell-linked="{ row }"><span class="font-mono text-caption">{{ row.linked_to }}</span></template>
<template #cell-linked="{ row }"><span class="font-mono text-caption text-fg-muted">{{ row.linked_to?.slice(0, 8) }}</span></template>
<template #detail="{ row }"><EventDetail :id="row.id" /></template>
<template #empty>
<Empty><EmptyHeader><EmptyTitle>No events</EmptyTitle></EmptyHeader></Empty>
+5 -5
View File
@@ -28,9 +28,9 @@ onMounted(() => {
const columns: DataTableColumn<EventSource_>[] = [
{ id: "name", label: "Source", fixed: true, sort: (s) => s.name },
{ id: "connector", label: "Connector", sort: (s) => s.connector },
{ id: "verification", label: "Verification" },
{ id: "key", label: "Grouped by" },
{ id: "connector", label: "Connector", hide: "sm", width: "12rem", sort: (s) => s.connector },
{ id: "verification", label: "Verification", hide: "sm", width: "14rem" },
{ id: "key", label: "Grouped by", hide: "md", width: "16rem" },
];
// A put creates a source or rotates its token; either way the token is shown
@@ -126,10 +126,10 @@ const connectorNames = computed(() => (connectors.data.value ?? []).map((c) => c
<div v-else-if="!data" role="status" aria-label="Loading sources" class="space-y-2"><Skeleton class="h-8 w-full" /></div>
<template v-else>
<div class="mb-2 flex justify-end">
<Button size="sm" aria-label="Add source" title="Add source" @click="openAdd"><Plus /></Button>
<Button size="icon-sm" variant="ghost" aria-label="Add source" title="Add source" @click="openAdd"><Plus /></Button>
</div>
<DataTable :columns="columns" :rows="data" :row-key="(s) => s.name" storage-key="sources">
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span></template>
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span><span class="block text-caption text-fg-muted sm:hidden">{{ row.connector }}</span></template>
<template #cell-connector="{ row }">{{ row.connector }}</template>
<template #cell-verification="{ row }">{{ row.verification === "hmac" ? `HMAC (${row.hmac_header})` : row.verification === "none" ? "None" : "Bearer token" }}</template>
<template #cell-key="{ row }"><span class="font-mono text-caption">{{ (row.key_fields ?? []).join(", ") || "Connector default" }}</span></template>
+11 -10
View File
@@ -20,6 +20,7 @@ import { errors } from "@/copy/errors";
import { api, describeError, type Trigger, type TriggerInput } from "@/lib/api";
import { fromLines, toLines } from "@/lib/lines";
import { useRead } from "@/lib/use-read";
import { interval } from "@/workflows/use-workflow-list";
import { triggerInput } from "./trigger";
/** With `workflow`, only the triggers that run it, and new ones run it. */
@@ -36,11 +37,11 @@ onMounted(() => {
const rows = computed(() => (data.value ?? []).filter((t) => !props.workflow || t.workflow === props.workflow));
const columns = computed<DataTableColumn<Trigger>[]>(() => [
{ id: "name", label: "Trigger", fixed: true, sort: (t) => t.name },
{ id: "fires", label: "Fires on", fixed: true },
...(props.workflow ? [] : [{ id: "workflow", label: "Workflow", sort: (t: Trigger) => t.workflow }]),
{ id: "filter", label: "Filter", hidden: true },
{ id: "enabled", label: "On", fixed: true, class: "w-0" },
{ id: "name", label: "Trigger", fixed: true, width: "auto", sort: (t) => t.name },
{ id: "fires", label: "Fires on", fixed: true, hide: "sm", width: "18rem" },
...(props.workflow ? [] : [{ id: "workflow", label: "Workflow", hide: "md" as const, width: "14rem", sort: (t: Trigger) => t.workflow }]),
{ id: "filter", label: "Filter", hidden: true, hide: "md", width: "16rem" },
{ id: "enabled", label: "On", fixed: true, width: "5rem" },
]);
const busy = ref(false);
@@ -96,15 +97,15 @@ async function submit(): Promise<void> {
<div v-else-if="!data" role="status" aria-label="Loading triggers" class="space-y-2"><Skeleton class="h-8 w-full" /></div>
<template v-else>
<div class="mb-2 flex justify-end">
<Button size="sm" aria-label="Add trigger" title="Add trigger" @click="open()"><Plus /></Button>
<Button size="icon-sm" variant="ghost" aria-label="Add trigger" title="Add trigger" @click="open()"><Plus /></Button>
</div>
<DataTable :columns="columns" :rows="rows" :row-key="(t) => t.name" :storage-key="workflow ? 'workflow-triggers' : 'triggers'">
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span></template>
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span><span class="block text-caption text-fg-muted sm:hidden">{{ row.every ? `Every ${interval(row.every)}` : `${row.source} ${row.event_type}` }}</span></template>
<template #cell-fires="{ row }">
<template v-if="row.every">Every {{ row.every }}</template>
<template v-else>{{ row.source }} <span class="font-mono text-caption">{{ row.event_type }}</span></template>
<template v-if="row.every">Every {{ interval(row.every) }}</template>
<template v-else>{{ row.source }} <span class="font-mono text-caption text-fg-muted">{{ row.event_type }}</span></template>
</template>
<template #cell-workflow="{ row }"><RouterLink class="underline" :to="`/workflows/${row.workflow}`">{{ row.workflow }}</RouterLink></template>
<template #cell-workflow="{ row }"><RouterLink class="hover:underline" :to="`/workflows/${row.workflow}`">{{ row.workflow }}</RouterLink></template>
<template #cell-filter="{ row }">
<span v-if="!row.every" class="font-mono text-caption">{{ Object.entries(row.filter ?? {}).map(([k, v]) => `${k}=${v}`).join(", ") }}</span>
</template>
+15 -15
View File
@@ -154,31 +154,31 @@ const totalRows = computed<TotalRow[]>(() => {
const dayColumns: DataTableColumn<DayRow>[] = [
{ id: "day", label: "Day", fixed: true, class: "whitespace-nowrap" },
{ id: "calls", label: "Calls", class: "tabular-nums", sort: (row) => row.calls },
{ id: "tokens", label: "Tokens", class: "tabular-nums", sort: tokens },
{ id: "cost", label: "Cost", class: "tabular-nums", sort: (row) => row.cost_usd ?? -1 },
{ id: "calls", label: "Calls", width: "7rem", class: "tabular-nums", sort: (row) => row.calls },
{ id: "tokens", label: "Tokens", width: "7rem", class: "tabular-nums", sort: tokens },
{ id: "cost", label: "Cost", width: "7rem", class: "tabular-nums", sort: (row) => row.cost_usd ?? -1 },
];
const modelColumns: DataTableColumn<ModelRow>[] = [
{ id: "provider", label: "Provider", fixed: true, class: "text-fg-muted whitespace-nowrap" },
{ id: "model", label: "Model", fixed: true, class: "w-full whitespace-normal" },
{ id: "calls", label: "Calls", class: "tabular-nums", sort: (row) => row.calls },
{ id: "tokens", label: "Tokens", class: "tabular-nums", sort: tokens },
{ id: "cost", label: "Cost", class: "tabular-nums", sort: (row) => row.cost_usd ?? -1 },
{ id: "provider", label: "Provider", fixed: true, width: "12rem", class: "text-fg-muted" },
{ id: "model", label: "Model", fixed: true, width: "auto", class: "whitespace-normal" },
{ id: "calls", label: "Calls", width: "7rem", class: "tabular-nums", sort: (row) => row.calls },
{ id: "tokens", label: "Tokens", width: "7rem", class: "tabular-nums", sort: tokens },
{ id: "cost", label: "Cost", width: "7rem", class: "tabular-nums", sort: (row) => row.cost_usd ?? -1 },
];
const sourceColumns: DataTableColumn<SourceRow>[] = [
{ id: "source", label: "Source", fixed: true },
{ id: "calls", label: "Calls", class: "tabular-nums", sort: (row) => row.calls },
{ id: "tokens", label: "Tokens", class: "tabular-nums", sort: tokens },
{ id: "cost", label: "Cost", class: "tabular-nums", sort: (row) => row.cost_usd ?? -1 },
{ id: "calls", label: "Calls", width: "7rem", class: "tabular-nums", sort: (row) => row.calls },
{ id: "tokens", label: "Tokens", width: "7rem", class: "tabular-nums", sort: tokens },
{ id: "cost", label: "Cost", width: "7rem", class: "tabular-nums", sort: (row) => row.cost_usd ?? -1 },
];
const identityColumns: DataTableColumn<IdentityRow>[] = [
{ id: "identity", label: "Identity", fixed: true, class: "w-full whitespace-normal" },
{ id: "calls", label: "Calls", class: "tabular-nums", sort: (row) => row.calls },
{ id: "tokens", label: "Tokens", class: "tabular-nums", sort: tokens },
{ id: "cost", label: "Cost", class: "tabular-nums", sort: (row) => row.cost_usd ?? -1 },
{ id: "identity", label: "Identity", fixed: true, width: "auto", class: "whitespace-normal" },
{ id: "calls", label: "Calls", width: "7rem", class: "tabular-nums", sort: (row) => row.calls },
{ id: "tokens", label: "Tokens", width: "7rem", class: "tabular-nums", sort: tokens },
{ id: "cost", label: "Cost", width: "7rem", class: "tabular-nums", sort: (row) => row.cost_usd ?? -1 },
];
</script>
+4 -11
View File
@@ -30,8 +30,7 @@ const SystemTasksPage = () => import("@/settings/SystemTasksPage.vue");
const SkillsPage = () => import("@/skills/SkillsPage.vue");
const TaskDetailPage = () => import("@/tasks/TaskDetailPage.vue");
const TasksPage = () => import("@/tasks/TasksPage.vue");
const WorkflowsPage = () => import("@/workflows/WorkflowsPage.vue");
const WorkflowPage = () => import("@/workflows/WorkflowPage.vue");
const WorkflowEditorPage = () => import("@/workflows/WorkflowEditorPage.vue");
// internal/gateway/dashboard_tools.go mirrors this table.
//
@@ -92,7 +91,7 @@ export const routes: RouteRecordRaw[] = [
{
path: "/workflows",
name: "workflows",
component: () => import("@/workflows/WorkflowListPage.vue"),
component: () => import("@/workflows/WorkflowsPage.vue"),
// Links written as /workflows?workflow=<id> open that workflow's page.
beforeEnter: (to: RouteLocationGeneric) => {
const { workflow, ...query } = to.query;
@@ -108,21 +107,15 @@ export const routes: RouteRecordRaw[] = [
{
path: "/workflows/:id",
name: "workflow",
component: () => import("@/workflows/WorkflowDocumentPage.vue"),
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",
name: "workflow-editor-list",
component: WorkflowsPage,
meta: { label: "Workflow editor", nav: false, navPath: "/workflows", section: "workflow_editor" },
},
{
path: "/workflow-editor/:id",
name: "workflow-editor",
component: WorkflowPage,
component: WorkflowEditorPage,
meta: { label: "Workflow", nav: false, navPath: "/workflows", section: "workflow_editor" },
},
{
+2 -1
View File
@@ -11,6 +11,7 @@ import { errors } from "@/copy/errors";
import { api, describeError } from "@/lib/api";
import { usePoll, useRead } from "@/lib/use-read";
import { answerApproval } from "@/runs/answer";
import { stateLabel } from "./state";
import { useLiveResource } from "@/stores/session";
/** Waiting approvals are a filter on runs: each asks a person to allow one
@@ -58,7 +59,7 @@ async function answer(id: string, approved: boolean): Promise<void> {
<template v-if="approval.deadline"> · due <Timestamp :at="approval.deadline" /></template>
</p>
</div>
<Badge variant="outline">{{ approval.level }}</Badge>
<Badge variant="outline">{{ stateLabel(approval.level) }}</Badge>
<Button size="sm" variant="outline" :disabled="busy === approval.id" @click="answer(approval.id, false)">Deny</Button>
<Button size="sm" :disabled="busy === approval.id" @click="answer(approval.id, true)">Approve</Button>
</li>
+31 -33
View File
@@ -17,7 +17,7 @@ import { api, describeError, type RunAction } from "@/lib/api";
import { usePoll, useRead } from "@/lib/use-read";
import { useLiveResource } from "@/stores/session";
import ApprovalsSection from "./ApprovalsSection.vue";
import { ended, stateTone } from "./state";
import { ended, stateLabel, stateTone } from "./state";
/** A run's decision trail: where it came from, each action it asked to take
* and how that was judged, and the steps it recorded. */
@@ -32,15 +32,27 @@ usePoll(() => {
if (!finished.value) void reload();
});
const origin = computed(() => {
const o = data.value?.origin;
if (!o) return [];
return [
...(o.source ? [{ label: "Source", value: o.source }] : []),
...(o.type ? [{ label: "Event type", value: o.type }] : []),
...(o.trigger ? [{ label: "Trigger", value: o.trigger }] : []),
...(o.event_id ? [{ label: "Event", value: o.event_id, mono: true }] : []),
];
});
const details = computed(() => {
const run = data.value?.run;
if (!run) return [];
return [
{ label: "Workflow", value: `${run.workflow} v${run.workflow_version}` },
{ label: "Attempts", value: String(run.attempts) },
{ label: "Run", value: run.id, mono: true },
...origin.value,
...(run.attempts > 1 ? [{ label: "Attempts", value: String(run.attempts) }] : []),
...(run.error ? [{ label: "Error", value: run.error }] : []),
...(run.detail ? [{ label: "Detail", value: run.detail }] : []),
{ label: "Run", value: run.id, mono: true },
];
});
const retrying = ref(false);
@@ -71,17 +83,6 @@ async function cancel(): Promise<void> {
cancelling.value = false;
}
}
const origin = computed(() => {
const o = data.value?.origin;
if (!o) return [];
return [
...(o.source ? [{ label: "Source", value: o.source }] : []),
...(o.type ? [{ label: "Event type", value: o.type }] : []),
...(o.trigger ? [{ label: "Trigger", value: o.trigger }] : []),
...(o.event_id ? [{ label: "Event", value: o.event_id, mono: true }] : []),
];
});
function target(action: RunAction): string {
const t = action.decision.action.target;
return t?.ID ? `${t.Kind ? `${t.Kind} ` : ""}${t.ID}` : "";
@@ -94,7 +95,7 @@ const result = computed(() =>
<template>
<div>
<PageHeader :title="data ? data.run.workflow : 'Run'">
<Badge v-if="data" :variant="stateTone(data.run.state)">{{ data.run.state }}</Badge>
<Badge v-if="data" :variant="stateTone(data.run.state)">{{ stateLabel(data.run.state) }}</Badge>
<span v-if="data" class="text-caption text-fg-muted">Started <Timestamp :at="data.run.created_at" /></span>
<Button v-if="data?.run.state === 'parked'" size="sm" :disabled="retrying" @click="retry">Retry</Button>
<Button v-if="cancellable" variant="destructive" size="sm" :disabled="cancelling" @click="cancel">Cancel</Button>
@@ -105,25 +106,23 @@ const result = computed(() =>
<p v-if="retryError" role="alert" class="mb-2 text-caption text-danger">{{ retryError }}</p>
<p v-if="cancelError" role="alert" class="mb-2 text-caption text-danger">{{ cancelError }}</p>
<ApprovalsSection :run="id" @answered="reload" />
<div class="grid gap-x-4 lg:grid-cols-2">
<Section title="Run"><MetadataList :rows="details" /></Section>
<Section v-if="origin.length" title="Started by">
<MetadataList :rows="origin">
<template #value="{ row }">
<RouterLink v-if="row.label === 'Event'" class="underline" :to="{ path: '/events', query: { event: row.value } }">{{ row.value }}</RouterLink>
<template v-else>{{ row.value }}</template>
</template>
</MetadataList>
</Section>
</div>
<Section title="Actions">
<Empty v-if="!data.actions?.length"><EmptyHeader><EmptyTitle>No actions</EmptyTitle></EmptyHeader></Empty>
<ul v-else class="divide-y divide-border">
<Section title="Details">
<MetadataList :rows="details">
<template #value="{ row }">
<RouterLink v-if="row.label === 'Workflow'" class="underline" :to="`/workflows/${data.run.workflow}`">{{ row.value }}</RouterLink>
<RouterLink v-else-if="row.label === 'Event'" class="underline" :to="{ path: '/events', query: { event: row.value } }">{{ row.value }}</RouterLink>
<template v-else>{{ row.value }}</template>
</template>
</MetadataList>
</Section>
<Empty v-if="!data.actions?.length && !data.entries?.length"><EmptyHeader><EmptyTitle>Nothing recorded yet</EmptyTitle></EmptyHeader></Empty>
<Section v-if="data.actions?.length" title="Actions">
<ul class="divide-y divide-border">
<li v-for="action in data.actions" :key="action.decision.id" class="space-y-1 py-3">
<div class="flex flex-wrap items-center gap-2">
<span class="font-mono text-label">{{ action.decision.action.connector }}.{{ action.decision.action.name }}</span>
<span v-if="target(action)" class="text-caption text-fg-muted">{{ target(action) }}</span>
<Badge variant="outline">{{ action.decision.level }}</Badge>
<Badge variant="outline">{{ stateLabel(action.decision.level) }}</Badge>
<Badge v-if="action.decision.dry" variant="secondary">Dry run</Badge>
<Badge v-if="action.decision.refused_by" variant="danger">Refused by {{ action.decision.refused_by }}</Badge>
<Badge v-if="action.approval" :variant="stateTone(action.approval.state)">Approval {{ action.approval.state }}</Badge>
@@ -140,9 +139,8 @@ const result = computed(() =>
</li>
</ul>
</Section>
<Section title="Steps">
<Empty v-if="!data.entries?.length"><EmptyHeader><EmptyTitle>No steps recorded</EmptyTitle></EmptyHeader></Empty>
<ol v-else class="divide-y divide-border">
<Section v-if="data.entries?.length" title="Steps">
<ol class="divide-y divide-border">
<li v-for="entry in data.entries" :key="entry.seq" class="space-y-1 py-2">
<div class="flex flex-wrap items-center gap-2">
<Badge variant="secondary">{{ entry.kind }}</Badge>
+55
View File
@@ -0,0 +1,55 @@
<script setup lang="ts">
import { ExternalLink, Workflow } from "@lucide/vue";
import { useRouter } from "vue-router";
import { Badge } from "@/components/ui/badge";
import { ContextMenuItem } from "@/components/ui/context-menu";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
import { Timestamp } from "@/components/ui/timestamp";
import { duration } from "@/lib/format";
import type { Run } from "@/lib/api";
import { stateLabel, stateTone } from "./state";
/** Workflow runs as a table. A workflow's own page leaves its name column out. */
const props = defineProps<{ rows: Run[]; storageKey: string; withWorkflow?: boolean }>();
const router = useRouter();
const time = (at?: string) => (at ? Date.parse(at) : 0);
const took = (run: Run) => (run.finished_at ? time(run.finished_at) - time(run.created_at) : -1);
const columns: DataTableColumn<Run>[] = [
...(props.withWorkflow ? [{ id: "workflow", label: "Workflow", fixed: true, width: "auto", sort: (r: Run) => r.workflow }] : []),
{ id: "state", label: "State", fixed: true, width: "9.5rem", sort: (r) => r.state },
{ id: "created", label: "Started", hide: "sm", width: "8rem", sort: (r) => time(r.created_at) },
{ id: "duration", label: "Took", hide: "sm", width: "6rem", sort: took },
{ id: "error", label: "Error", width: "24rem", hide: "md" },
{ id: "attempts", label: "Attempts", hidden: true, width: "7rem", sort: (r) => r.attempts },
{ id: "id", label: "Run", hidden: true, width: "14rem" },
];
</script>
<template>
<DataTable
:columns="columns"
:rows="rows"
:row-key="(r) => r.id"
:row-link="(r) => `/runs/${r.id}`"
:row-label="(r) => `${r.workflow} run`"
:storage-key="storageKey"
:initial-sort="{ id: 'created', desc: true }"
>
<template #cell-workflow="{ row }">
<span class="font-medium">{{ row.workflow }}</span> <span class="text-caption text-fg-subtle">v{{ row.workflow_version }}</span>
</template>
<template #cell-state="{ row }"><Badge :variant="stateTone(row.state)" :title="row.error || undefined">{{ stateLabel(row.state) }}</Badge></template>
<template #cell-created="{ row }"><Timestamp :at="row.created_at" /></template>
<template #cell-duration="{ row }"><span class="text-caption text-fg-muted">{{ took(row) >= 0 ? duration(took(row)) : "" }}</span></template>
<template #cell-error="{ row }"><span class="text-caption text-danger" :title="row.error">{{ row.error }}</span></template>
<template #cell-attempts="{ row }">{{ row.attempts }}</template>
<template #cell-id="{ row }"><span class="font-mono text-caption text-fg-muted">{{ row.id.slice(0, 8) }}</span></template>
<template #menu="{ row }">
<ContextMenuItem @select="router.push(`/runs/${row.id}`)"><ExternalLink />Open run</ContextMenuItem>
<ContextMenuItem @select="router.push(`/workflows/${row.workflow}`)"><Workflow />Open workflow</ContextMenuItem>
</template>
<template #empty><slot name="empty" /></template>
</DataTable>
</template>
+27 -50
View File
@@ -1,75 +1,52 @@
<script setup lang="ts">
import { computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { computed, onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { Search } from "@lucide/vue";
import PageHeader from "@/base/PageHeader.vue";
import { X } from "@lucide/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 { ReadError } from "@/components/ui/read-error";
import { Skeleton } from "@/components/ui/skeleton";
import { Timestamp } from "@/components/ui/timestamp";
import type { Run } from "@/lib/api";
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";
import { Spinner } from "@/components/ui/spinner";
import { api } from "@/lib/api";
import { usePoll, useRead } from "@/lib/use-read";
import { useLiveResource } from "@/stores/session";
import ApprovalsSection from "./ApprovalsSection.vue";
import { stateTone } from "./state";
import RunTable from "./RunTable.vue";
const route = useRoute();
const router = useRouter();
const { data, error, reload } = useRead(() => api.runs());
onMounted(reload);
useLiveResource(null, () => void reload());
usePoll(reload);
// ?workflow= narrows the list to one workflow's runs, so a workflow links here.
const workflow = computed(() => String(route.query.workflow ?? ""));
const rows = computed(() => (data.value ?? []).filter((r) => !workflow.value || r.workflow === workflow.value));
const time = (at?: string) => (at ? Date.parse(at) : 0);
const columns: DataTableColumn<Run>[] = [
{ id: "workflow", label: "Workflow", fixed: true, sort: (r) => r.workflow },
{ id: "state", label: "State", fixed: true, sort: (r) => r.state },
{ id: "created", label: "Started", sort: (r) => time(r.created_at) },
{ id: "finished", label: "Finished", sort: (r) => time(r.finished_at) },
{ id: "attempts", label: "Attempts", hidden: true, sort: (r) => r.attempts },
{ id: "id", label: "Run", hidden: true },
];
// A workflow links here with ?workflow=, which starts the filter on its name.
const query = ref(String(route.query.workflow ?? ""));
// A filter earns its place once the list outgrows a glance.
const FILTER_FROM = 8;
const filterable = computed(() => (data.value?.length ?? 0) > FILTER_FROM || !!query.value);
const shown = computed(() => {
const needle = query.value.trim().toLowerCase();
return (data.value ?? []).filter((r) => !needle || r.workflow.toLowerCase().includes(needle) || r.state.includes(needle));
});
</script>
<template>
<div>
<PageHeader title="Runs">
<Button v-if="workflow" variant="outline" size="sm" title="Show every workflow's runs" @click="router.replace({ query: {} })">{{ workflow }}<X data-icon="inline-end" /></Button>
<InputGroup v-if="filterable" class="w-56 max-sm:w-full">
<InputGroupAddon><Search /></InputGroupAddon>
<InputGroupInput v-model="query" type="search" aria-label="Filter runs" placeholder="Filter" />
</InputGroup>
</PageHeader>
<ApprovalsSection @answered="reload" />
<ReadError v-if="error" :message="error" retry-label="Retry" @retry="reload" />
<div v-else-if="!data" role="status" aria-label="Loading runs" class="space-y-2"><Skeleton class="h-8 w-full" /><Skeleton class="h-8 w-full" /></div>
<DataTable
v-else
:columns="columns"
:rows="rows"
:row-key="(r) => r.id"
:row-link="(r) => `/runs/${r.id}`"
:row-label="(r) => `${r.workflow} run`"
storage-key="runs"
:initial-sort="{ id: 'created', desc: true }"
>
<template #cell-workflow="{ row }"><span class="font-medium">{{ row.workflow }}</span> <span class="text-caption text-fg-subtle">v{{ row.workflow_version }}</span></template>
<template #cell-state="{ row }">
<Badge :variant="stateTone(row.state)" :title="row.error || undefined">{{ row.state }}</Badge>
</template>
<template #cell-created="{ row }"><Timestamp :at="row.created_at" /></template>
<template #cell-finished="{ row }"><Timestamp :at="row.finished_at" /></template>
<template #cell-attempts="{ row }">{{ row.attempts }}</template>
<template #cell-id="{ row }"><span class="font-mono text-caption">{{ row.id }}</span></template>
<template #empty>
<Empty><EmptyHeader><EmptyTitle>No runs yet</EmptyTitle></EmptyHeader></Empty>
</template>
</DataTable>
<div v-if="error" class="mb-4 text-label text-danger" role="alert">
<p>{{ error }}</p>
<Button variant="outline" size="sm" @click="reload">Retry</Button>
</div>
<p v-else-if="!data" class="flex items-center gap-2 text-label text-fg-muted"><Spinner />Loading runs…</p>
<Empty v-else-if="!data.length"><EmptyHeader><EmptyTitle>No runs</EmptyTitle></EmptyHeader></Empty>
<p v-else-if="!shown.length" class="text-label text-fg-muted">No run matches.</p>
<RunTable v-else :rows="shown" storage-key="runs" with-workflow />
</div>
</template>
+5
View File
@@ -25,6 +25,11 @@ export function stateTone(state: string): "ok" | "warn" | "danger" | "info" | "i
}
}
/** A run state in words: "waiting_approval" reads "waiting approval". */
export function stateLabel(state: string): string {
return state.replace(/_/g, " ");
}
/** Whether a run state is terminal: the run has ended and cannot be cancelled. */
export function ended(state: string): boolean {
switch (state) {
+100 -135
View File
@@ -1,20 +1,15 @@
<script setup lang="ts">
import { Plus } from "@lucide/vue";
import { computed, onMounted, ref } from "vue";
import { Plus, Trash2 } from "@lucide/vue";
import { computed, onMounted, ref, watch } from "vue";
import PageHeader from "@/base/PageHeader.vue";
import { Button } from "@/components/ui/button";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Input } from "@/components/ui/input";
import { MoreMenu } from "@/components/ui/more-menu";
import { ReadError } from "@/components/ui/read-error";
import { Label } from "@/components/ui/label";
import { Section } from "@/components/ui/section";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { SettingRow } from "@/components/ui/setting-row";
import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
import { errors } from "@/copy/errors";
import { api, describeError, type AgentModel } from "@/lib/api";
import { useRead } from "@/lib/use-read";
@@ -28,145 +23,115 @@ onMounted(() => {
void credentials.reload();
});
interface Row extends AgentModel { alias: string }
const rows = computed<Row[]>(() => Object.entries(data.value ?? {}).map(([alias, m]) => ({ alias, ...m })));
const columns: DataTableColumn<Row>[] = [
{ id: "alias", label: "Alias", fixed: true, sort: (r) => r.alias },
{ id: "model", label: "Model", fixed: true, sort: (r) => r.model },
{ id: "class", label: "Provider", sort: (r) => r.class },
{ id: "base", label: "Base URL", hidden: true },
{ id: "key", label: "API key" },
];
const NONE = "__none__";
const editing = ref(false);
const isNew = ref(true);
const form = ref({ alias: "", class: "", model: "", base_url: "", api_key_credential: NONE });
function open(row?: Row): void {
isNew.value = !row;
actionError.value = "";
tested.value = "";
form.value = {
alias: row?.alias ?? "",
class: row?.class ?? "",
model: row?.model ?? "",
base_url: row?.base_url ?? "",
api_key_credential: row?.api_key_credential || NONE,
};
editing.value = true;
}
const model = (): AgentModel => ({
class: form.value.class.trim(),
model: form.value.model.trim(),
base_url: form.value.base_url.trim() || undefined,
api_key_credential: form.value.api_key_credential === NONE ? undefined : form.value.api_key_credential,
interface Form { class: string; model: string; base_url: string; key: string }
const form = (m?: AgentModel): Form => ({ class: m?.class ?? "", model: m?.model ?? "", base_url: m?.base_url ?? "", key: m?.api_key_credential || NONE });
const body = (f: Form): AgentModel => ({
class: f.class.trim(),
model: f.model.trim(),
base_url: f.base_url.trim() || undefined,
api_key_credential: f.key === NONE ? undefined : f.key,
});
const busy = ref(false);
const actionError = ref("");
const tested = ref("");
async function test(): Promise<void> {
busy.value = true;
actionError.value = "";
tested.value = "";
// Edits are held per alias until that alias is saved.
const edits = ref<Record<string, Form>>({});
const added = ref<string[]>([]);
watch(data, (models) => {
const next: Record<string, Form> = {};
for (const [alias, m] of Object.entries(models ?? {})) next[alias] = edits.value[alias] && dirty(alias) ? edits.value[alias] : form(m);
for (const alias of ["default", ...added.value]) next[alias] ??= edits.value[alias] ?? form();
edits.value = next;
});
const saved = (alias: string) => form(data.value?.[alias]);
function dirty(alias: string): boolean {
const now = edits.value[alias];
const was = saved(alias);
return !!now && (now.class !== was.class || now.model !== was.model || now.base_url !== was.base_url || now.key !== was.key);
}
const aliases = computed(() => [...new Set(["default", ...Object.keys(data.value ?? {}), ...added.value])]);
const bearer = computed(() => (credentials.data.value ?? []).filter((c) => c.kind === "bearer"));
const field = (alias: string): Form => edits.value[alias] ?? form();
const busy = ref("");
const rowError = ref<Record<string, string>>({});
const tested = ref<Record<string, string>>({});
async function run(alias: string, act: () => Promise<void>): Promise<void> {
busy.value = alias;
rowError.value = { ...rowError.value, [alias]: "" };
try {
const answer = await api.testAgentModel(model());
tested.value = `${answer.model} answered “${answer.answer.trim()}”`;
await act();
} catch (cause) {
actionError.value = describeError(cause, errors.common.unknown);
rowError.value = { ...rowError.value, [alias]: describeError(cause, errors.common.unknown) };
} finally {
busy.value = false;
busy.value = "";
}
}
async function save(): Promise<void> {
busy.value = true;
actionError.value = "";
try {
const alias = form.value.alias.trim();
await api.putAgentModel(alias === "default" ? "" : alias, model());
editing.value = false;
const save = (alias: string) =>
run(alias, async () => {
await api.putAgentModel(alias === "default" ? "" : alias, body(field(alias)));
added.value = added.value.filter((a) => a !== alias);
await reload();
} catch (cause) {
actionError.value = describeError(cause, errors.common.unknown);
} finally {
busy.value = false;
}
}
const pending = ref<Row | null>(null);
const removeError = ref("");
async function remove(row: Row): Promise<void> {
busy.value = true;
removeError.value = "";
try {
await api.deleteAgentModel(row.alias === "default" ? "" : row.alias);
});
const test = (alias: string) =>
run(alias, async () => {
const answer = await api.testAgentModel(body(field(alias)));
tested.value = { ...tested.value, [alias]: `${answer.model} answered “${answer.answer.trim()}”` };
});
const remove = (alias: string) =>
run(alias, async () => {
if (data.value?.[alias]) await api.deleteAgentModel(alias === "default" ? "" : alias);
added.value = added.value.filter((a) => a !== alias);
delete edits.value[alias];
await reload();
} catch (cause) {
removeError.value = describeError(cause, errors.common.unknown);
} finally {
busy.value = false;
}
});
const newAlias = ref("");
function addAlias(): void {
const name = newAlias.value.trim();
if (!name || aliases.value.includes(name)) return;
added.value = [...added.value, name];
edits.value = { ...edits.value, [name]: form() };
newAlias.value = "";
}
</script>
<template>
<div>
<PageHeader title="Models">
<Button size="sm" aria-label="Add model" title="Add model" @click="open()"><Plus /></Button>
</PageHeader>
<ReadError v-if="error" :message="error" retry-label="Retry" @retry="reload" />
<div v-else-if="!data" role="status" aria-label="Loading models" class="space-y-2"><Skeleton class="h-8 w-full" /></div>
<DataTable v-else :columns="columns" :rows="rows" :row-key="(r) => r.alias" storage-key="agent-models">
<template #cell-alias="{ row }"><span class="font-medium">{{ row.alias }}</span></template>
<template #cell-model="{ row }"><span class="font-mono text-caption">{{ row.model }}</span></template>
<template #cell-class="{ row }">{{ row.class }}</template>
<template #cell-base="{ row }"><span class="font-mono text-caption">{{ row.base_url }}</span></template>
<template #cell-key="{ row }">{{ row.api_key_credential }}</template>
<template #actions="{ row }">
<MoreMenu :label="`${row.alias} actions`"><DropdownMenuItem @select="open(row)">Edit</DropdownMenuItem><DropdownMenuItem class="text-danger" @select="pending = row">Delete</DropdownMenuItem></MoreMenu>
</template>
<template #empty><Empty><EmptyHeader><EmptyTitle>No models</EmptyTitle></EmptyHeader></Empty></template>
</DataTable>
<p v-if="removeError" role="alert" class="pt-2 text-caption text-danger">{{ removeError }}</p>
<AlertDialog :open="pending !== null" @update:open="(v: boolean) => { if (!v) pending = null; }">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete model?</AlertDialogTitle>
<AlertDialogDescription>Delete the alias "{{ pending?.alias }}"? Workflows that name it will fail.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction @click="if (pending) { const row = pending; pending = null; void remove(row); }">Delete model</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Dialog v-model:open="editing">
<DialogContent class="sm:max-w-2xl">
<DialogHeader><DialogTitle>{{ isNew ? "Add model" : `Edit ${form.alias}` }}</DialogTitle></DialogHeader>
<form id="model-form" @submit.prevent="save">
<SettingRow v-if="isNew" label="Alias" for="model-alias" hint="Workflows name it; default is used when they name none."><Input id="model-alias" v-model="form.alias" required /></SettingRow>
<SettingRow label="Provider" for="model-class"><Input id="model-class" v-model="form.class" placeholder="openai" required /></SettingRow>
<SettingRow label="Model" for="model-name"><Input id="model-name" v-model="form.model" required /></SettingRow>
<SettingRow label="Base URL" for="model-base" hint="Empty uses the provider's own."><Input id="model-base" v-model="form.base_url" type="url" /></SettingRow>
<SettingRow label="API key" for="model-key" hint="A bearer credential.">
<Select v-model="form.api_key_credential">
<SelectTrigger id="model-key" class="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem :value="NONE">None</SelectItem>
<SelectItem v-for="c in (credentials.data.value ?? []).filter((c) => c.kind === 'bearer')" :key="c.name" :value="c.name">{{ c.name }}</SelectItem>
</SelectContent>
</Select>
</SettingRow>
<p v-if="tested" role="status" class="pt-2 text-caption text-ok">{{ tested }}</p>
<p v-if="actionError" role="alert" class="pt-2 text-caption text-danger">{{ actionError }}</p>
</form>
<DialogFooter>
<Button variant="outline" :disabled="busy || !form.class || !form.model" @click="test">Test</Button>
<Button type="submit" form="model-form" :disabled="busy">Save</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<PageHeader title="Models" />
<div v-if="error" class="mb-4 text-label text-danger" role="alert">
<p>{{ error }}</p>
<Button variant="outline" size="sm" @click="reload">Retry</Button>
</div>
<p v-else-if="!data" class="flex items-center gap-2 text-label text-fg-muted"><Spinner />Loading models…</p>
<Section v-else title="Aliases">
<p v-if="!data.default" class="mb-3 text-label text-warn" role="alert">Set the default alias.</p>
<Empty v-if="!aliases.length"><EmptyHeader><EmptyTitle>No models</EmptyTitle></EmptyHeader></Empty>
<div v-for="alias in aliases" :key="alias" class="border-b border-border py-2.5 last-of-type:border-b-0">
<div class="flex flex-wrap items-center gap-3">
<Label :for="`model-${alias}`" class="w-28 text-label font-medium @max-xl:w-full">{{ alias }}</Label>
<Input v-model="field(alias).class" class="w-32 font-mono" placeholder="provider" :aria-label="`${alias} provider`" />
<Input :id="`model-${alias}`" v-model="field(alias).model" class="min-w-40 flex-1 basis-40 font-mono" placeholder="model" />
<Input v-model="field(alias).base_url" type="url" class="min-w-40 flex-1 basis-40 font-mono" placeholder="Base URL" :aria-label="`${alias} base URL`" />
<Select v-model="field(alias).key">
<SelectTrigger class="w-44 @max-xl:w-full" :aria-label="`${alias} API key`"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem :value="NONE">No key</SelectItem>
<SelectItem v-for="c in bearer" :key="c.name" :value="c.name">{{ c.name }}</SelectItem>
</SelectContent>
</Select>
<span class="ml-auto flex items-center gap-1">
<Button variant="outline" size="sm" :disabled="!!busy || !field(alias).class || !field(alias).model" @click="test(alias)">Test</Button>
<Button size="sm" :disabled="!!busy || !dirty(alias) || !field(alias).class || !field(alias).model" @click="save(alias)">Save</Button>
<Button v-if="alias !== 'default' || data.default" variant="ghost" size="icon" :aria-label="`Remove alias ${alias}`" :disabled="!!busy" @click="remove(alias)"><Trash2 /></Button>
</span>
</div>
<p v-if="tested[alias]" role="status" class="pt-1.5 text-caption text-ok">{{ tested[alias] }}</p>
<p v-if="rowError[alias]" role="alert" class="pt-1.5 text-caption text-danger">{{ rowError[alias] }}</p>
</div>
<form class="flex flex-wrap gap-2 border-t border-border pt-3" @submit.prevent="addAlias">
<Input v-model="newAlias" class="max-w-56 font-mono" placeholder="alias" aria-label="New alias" />
<Button type="submit" variant="outline" size="sm" :disabled="!newAlias.trim()"><Plus data-icon="inline-start" />Add alias</Button>
</form>
</Section>
</div>
</template>
+3 -3
View File
@@ -34,8 +34,8 @@ onMounted(() => {
const columns: DataTableColumn<Credential>[] = [
{ id: "name", label: "Credential", fixed: true, sort: (c) => c.name },
{ id: "kind", label: "Kind", sort: (c) => c.kind },
{ id: "fields", label: "Fields" },
{ id: "kind", label: "Kind", hide: "sm", width: "10rem", sort: (c) => c.kind },
{ id: "fields", label: "Fields", hide: "md", width: "24rem" },
];
interface FieldForm { from: "value" | "engine"; value: string; engine: string; key: string }
@@ -94,7 +94,7 @@ async function submit(): Promise<void> {
<template>
<div>
<PageHeader title="Credentials">
<Button size="sm" aria-label="Add credential" title="Add credential" :disabled="!kinds.data.value" @click="open()"><Plus /></Button>
<Button size="icon-sm" variant="ghost" aria-label="Add credential" title="Add credential" :disabled="!kinds.data.value" @click="open()"><Plus /></Button>
</PageHeader>
<p v-if="restarted.length" role="status" class="mb-2 text-caption text-fg-muted">Restarted {{ restarted.join(", ") }}.</p>
<ReadError v-if="error || kinds.error.value" :message="error || kinds.error.value" retry-label="Retry" @retry="reload(); kinds.reload()" />
+6 -6
View File
@@ -31,11 +31,11 @@ onMounted(reload);
const columns = computed<DataTableColumn<Extension>[]>(() => [
{ id: "name", label: "Name", fixed: true, sort: (e) => e.name },
{ id: "state", label: "State", fixed: true, sort: (e) => e.state },
{ id: "version", label: "Version", sort: (e) => e.version ?? "" },
...(props.kind === "connectors" ? [{ id: "capabilities", label: "Declares" }] : []),
{ id: "path", label: "Path", hidden: true },
{ id: "egress", label: "Egress", hidden: true },
{ id: "state", label: "State", fixed: true, width: "9rem", sort: (e) => e.state },
{ id: "version", label: "Version", hide: "sm", width: "8rem", sort: (e) => e.version ?? "" },
...(props.kind === "connectors" ? [{ id: "capabilities", label: "Declares", hide: "md" as const, width: "14rem" }] : []),
{ id: "path", label: "Path", hidden: true, hide: "md", width: "18rem" },
{ id: "egress", label: "Egress", hidden: true, hide: "md", width: "14rem" },
]);
const CAPABILITY_GROUPS = [
@@ -151,7 +151,7 @@ async function remove(): Promise<void> {
<div v-else-if="!data" role="status" :aria-label="`Loading ${noun}s`" class="space-y-2"><Skeleton class="h-8 w-full" /></div>
<template v-else>
<div class="mb-2 flex justify-end">
<Button size="sm" :aria-label="`Add ${noun}`" :title="`Add ${noun}`" @click="open()"><Plus /></Button>
<Button size="icon-sm" variant="ghost" :aria-label="`Add ${noun}`" :title="`Add ${noun}`" @click="open()"><Plus /></Button>
</div>
<DataTable :columns="columns" :rows="data" :row-key="(e) => e.name" :storage-key="`extensions-${kind}`">
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span></template>
+3 -3
View File
@@ -23,10 +23,10 @@ const title = (task: Task) => task.title || "untitled task";
// so the width they would repeat goes to the title.
const columns = computed<DataTableColumn<Task>[]>(() => [
...(props.showRepo
? [{ id: "repo", label: "Repo", class: "whitespace-nowrap text-fg-muted", sort: (t: Task) => `${t.owner ?? ""}/${t.repo ?? ""}` }]
? [{ id: "repo", label: "Repo", width: "12rem", class: "text-fg-muted", sort: (t: Task) => `${t.owner ?? ""}/${t.repo ?? ""}` }]
: []),
...(props.showIssue ? [{ id: "issue", label: "Issue", class: "text-fg-muted", sort: (t: Task) => t.issue_number ?? 0 }] : []),
{ id: "title", label: "Title", fixed: true, class: "w-full whitespace-normal", sort: title },
...(props.showIssue ? [{ id: "issue", label: "Issue", width: "6rem", class: "text-fg-muted", sort: (t: Task) => t.issue_number ?? 0 }] : []),
{ id: "title", label: "Title", fixed: true, width: "auto", class: "whitespace-normal", sort: title },
{ id: "status", label: "Status", sort: (t) => t.status ?? "" },
{ id: "workflow", label: "Workflow", class: "text-fg-muted", sort: (t) => t.workflow ?? "" },
{ id: "activity", label: "Last activity", class: "text-fg-muted", sort: (t) => Date.parse(t.updated_at ?? "") || 0 },
-129
View File
@@ -1,129 +0,0 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { RouterLink, useRoute, useRouter } from "vue-router";
import PageHeader from "@/base/PageHeader.vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ReadError } from "@/components/ui/read-error";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { errors } from "@/copy/errors";
import { api, describeError } from "@/lib/api";
import { useRead } from "@/lib/use-read";
import TriggerList from "@/events/TriggerList.vue";
import WorkflowCanvas from "./WorkflowCanvas.vue";
import WorkflowYaml from "./WorkflowYaml.vue";
/** One workflow: its graph, its document, the versions it has been published
* as, and the triggers that start it. */
const route = useRoute();
const router = useRouter();
const name = String(route.params.id);
const latest = useRead(() => api.workflow(name));
onMounted(latest.reload);
// ?version= shows a published version read-only, marked against the latest.
const versionParam = computed(() => Number(route.query.version) || 0);
const shown = useRead(() => api.workflow(name, versionParam.value));
watch(versionParam, (v) => v && void shown.reload(), { immediate: true });
const viewingOld = computed(() => !!versionParam.value && versionParam.value !== latest.data.value?.version);
const versions = computed(() => Array.from({ length: latest.data.value?.version ?? 0 }, (_, i) => String((latest.data.value?.version ?? 0) - i)));
function pickVersion(v: unknown): void {
const n = Number(v);
void router.replace({ query: { ...route.query, version: n === latest.data.value?.version ? undefined : String(n) } });
}
// The document being edited: unpublished until Publish, and lost on leaving.
const yaml = ref("");
const base = ref(0);
watch(
() => latest.data.value,
(w) => {
if (w && (!base.value || yaml.value === "")) {
yaml.value = w.body;
base.value = w.version;
}
},
);
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);
if (current.version !== base.value) {
publishError.value = `Version ${current.version} was published after you opened version ${base.value}. Copy your changes, then discard them to load it.`;
return;
}
const saved = await api.putWorkflow(name, yaml.value);
base.value = saved.version;
yaml.value = saved.body;
await latest.reload();
} catch (cause) {
publishError.value = describeError(cause, errors.common.unknown);
} finally {
busy.value = false;
}
}
function discard(): void {
base.value = 0;
yaml.value = "";
publishError.value = "";
void latest.reload();
}
const view = computed(() => (["yaml", "triggers"].includes(String(route.query.view)) ? String(route.query.view) : "canvas"));
function showView(v: unknown): void {
void router.replace({ query: { ...route.query, view: v === "canvas" ? undefined : String(v) } });
}
const open = ref<string | null>(null);
const displayed = computed(() => (viewingOld.value ? (shown.data.value?.body ?? "") : yaml.value));
</script>
<template>
<div>
<PageHeader :title="name">
<Badge v-if="edited" variant="outline">Unpublished changes</Badge>
<Select v-if="versions.length > 1" :model-value="String(versionParam || latest.data.value?.version)" @update:model-value="pickVersion">
<SelectTrigger size="sm" aria-label="Version"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem v-for="v in versions" :key="v" :value="v">Version {{ v }}</SelectItem>
</SelectContent>
</Select>
<Badge v-else-if="latest.data.value" variant="outline">Version {{ latest.data.value.version }}</Badge>
<Button size="sm" variant="outline" as-child><RouterLink :to="{ path: '/runs', query: { workflow: name } }">Runs</RouterLink></Button>
</PageHeader>
<ReadError v-if="latest.error.value" :message="latest.error.value" retry-label="Retry" @retry="latest.reload" />
<div v-else-if="!latest.data.value" role="status" aria-label="Loading workflow"><Skeleton class="h-96 w-full" /></div>
<template v-else>
<Tabs :model-value="view" class="mb-3" @update:model-value="showView">
<TabsList variant="line" class="w-full justify-start">
<TabsTrigger value="canvas" class="flex-none px-3">Canvas</TabsTrigger>
<TabsTrigger value="yaml" class="flex-none px-3">YAML</TabsTrigger>
<TabsTrigger value="triggers" class="flex-none px-3">Triggers</TabsTrigger>
</TabsList>
</Tabs>
<ReadError v-if="viewingOld && shown.error.value" :message="shown.error.value" retry-label="Retry" @retry="shown.reload" />
<div v-if="view === 'canvas'" class="h-[70dvh] min-h-96">
<WorkflowCanvas :yaml="displayed" readonly :open="open" @toggle="open = open === $event ? null : $event" />
</div>
<div v-else-if="view === 'yaml'" class="flex flex-col gap-2">
<div v-if="!viewingOld" class="flex flex-wrap items-center justify-end gap-2">
<p v-if="publishError" role="alert" class="mr-auto text-caption text-danger">{{ publishError }}</p>
<Button size="sm" variant="outline" :disabled="!edited || busy" @click="discard">Discard</Button>
<Button size="sm" :disabled="!edited || busy" @click="publish">Publish</Button>
</div>
<WorkflowYaml v-if="viewingOld" :model-value="displayed" readonly />
<WorkflowYaml v-else v-model="yaml" />
</div>
<TriggerList v-else :workflow="name" />
</template>
</div>
</template>
+113
View File
@@ -0,0 +1,113 @@
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
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 WorkflowEditor from "./WorkflowEditor.vue";
import { useWorkflowStats } from "./use-workflow-stats";
import { triggerSummary, useWorkflowTriggers } from "./workflow-triggers";
const route = useRoute();
const router = useRouter();
const { store, data, error, loading, statsKnown, load, enabledOf, setEnabled, duplicate } = useWorkflowStats();
// The path names the workflow; the editor renames or clears it by publishing
// under another id or deleting, and the URL follows.
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" })),
});
// ?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 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));
async function copy(id: string) {
const next = await duplicate(id);
if (next) selected.value = next;
}
</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>
<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">
<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">
<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)" />
<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>
</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 ?? ''"
@duplicate="copy"
@reload-triggers="reloadTriggers"
>
<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>
</WorkflowEditor>
</div>
</div>
</template>
+1 -1
View File
@@ -54,7 +54,7 @@ const CHANGE_VARIANTS = { added: "default", edited: "secondary", removed: "destr
<span class="font-mono text-caption text-fg-subtle">v{{ item.version }}</span>
<Badge :variant="CHANGE_VARIANTS[item.change]">{{ item.change }}</Badge>
</span>
<span class="mt-0.5 block truncate text-caption text-fg-muted" :title="item.at">{{ item.actor || "unknown" }} · {{ item.source || "unknown" }} · <Timestamp :at="item.at" /></span>
<span class="mt-0.5 block truncate text-caption text-fg-muted" :title="item.at">{{ item.actor || "unknown" }} · <template v-if="item.source">{{ item.source }} · </template><Timestamp :at="item.at" /></span>
</button>
</li>
<!-- A failed reload says so even over an older list, which may be stale. -->
+4 -4
View File
@@ -1,16 +1,16 @@
<script setup lang="ts">
import { StatusDot } from "@/components/ui/status-dot";
import { Timestamp } from "@/components/ui/timestamp";
import { statusKind, statusLabel } from "@/lib/task-meta";
import { stateLabel } from "@/runs/state";
/** A workflow's newest run: how it stands, when it started, and a link to it. */
defineProps<{ runId?: number; status?: string; at?: string; running?: number; known: boolean }>();
defineProps<{ to?: string; state?: string; tone?: "ok" | "warn" | "danger" | "info" | "idle"; at?: string; running?: number; known: boolean }>();
</script>
<template>
<RouterLink v-if="runId" :to="{ name: 'task-detail', params: { id: runId } }" class="inline-flex min-w-0 flex-col gap-0.5 rounded-sm hover:underline focus-visible:outline-2 focus-visible:outline-ring" :aria-label="`Run #${runId}, ${statusLabel(status ?? '')}`" @click.stop>
<RouterLink v-if="to" :to="to" class="inline-flex min-w-0 flex-col gap-0.5 rounded-sm hover:underline focus-visible:outline-2 focus-visible:outline-ring" :aria-label="`Latest run, ${stateLabel(state ?? '')}`" @click.stop>
<span class="flex items-center gap-1.5 text-label">
<StatusDot :tone="running ? 'info' : statusKind(status ?? '')" :live="!!running" />{{ running ? `${running} running` : statusLabel(status ?? "") }}
<StatusDot :tone="running ? 'info' : tone" :live="!!running" />{{ running ? `${running} running` : stateLabel(state ?? "") }}
</span>
<Timestamp :at="at" class="text-caption text-fg-subtle" />
</RouterLink>
-126
View File
@@ -1,126 +0,0 @@
<script setup lang="ts">
import { Plus } from "@lucide/vue";
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import PageHeader from "@/base/PageHeader.vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Input } from "@/components/ui/input";
import { ReadError } from "@/components/ui/read-error";
import { Skeleton } from "@/components/ui/skeleton";
import { Timestamp } from "@/components/ui/timestamp";
import { errors } from "@/copy/errors";
import { api, describeError, type Run, type Trigger } from "@/lib/api";
import { useRead } from "@/lib/use-read";
import { stateTone } from "@/runs/state";
import WorkflowYaml from "./WorkflowYaml.vue";
const router = useRouter();
const workflows = useRead(() => api.workflowList());
const triggers = useRead(() => api.triggers());
const runs = useRead(() => api.runs());
onMounted(() => {
void workflows.reload();
void triggers.reload();
void runs.reload();
});
interface Row {
name: string;
version: number;
steps: number;
updated: string;
by?: string;
triggers: Trigger[];
last?: Run;
}
const rows = computed<Row[]>(() =>
(workflows.data.value ?? []).map((w) => ({
name: w.name,
version: w.version,
steps: w.steps?.length ?? 0,
updated: w.created_at,
by: w.created_by,
triggers: (triggers.data.value ?? []).filter((t) => t.workflow === w.name),
last: (runs.data.value ?? []).filter((r) => r.workflow === w.name).sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at))[0],
})),
);
const time = (at?: string) => (at ? Date.parse(at) : 0);
const columns: DataTableColumn<Row>[] = [
{ id: "name", label: "Workflow", fixed: true, sort: (r) => r.name },
{ id: "triggers", label: "Started by" },
{ id: "last", label: "Last run", sort: (r) => time(r.last?.created_at) },
{ id: "steps", label: "Steps", hidden: true, sort: (r) => r.steps },
{ id: "updated", label: "Published", sort: (r) => time(r.updated) },
];
function startedBy(row: Row): string {
if (!row.triggers.length) return triggers.error.value ? "" : "Manual";
return row.triggers.map((t) => (t.every ? `Every ${t.every}` : `${t.source} ${t.event_type}`)).join(", ");
}
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();
try {
await api.putWorkflow(name, draft.value.body);
creating.value = false;
void router.push(`/workflows/${name}`);
} catch (cause) {
createError.value = describeError(cause, errors.common.unknown);
} finally {
busy.value = false;
}
}
</script>
<template>
<div>
<PageHeader title="Workflows">
<Button size="sm" aria-label="New workflow" title="New workflow" @click="creating = true"><Plus /></Button>
</PageHeader>
<ReadError v-if="workflows.error.value" :message="workflows.error.value" retry-label="Retry" @retry="workflows.reload" />
<div v-else-if="!workflows.data.value" role="status" aria-label="Loading workflows" class="space-y-2"><Skeleton class="h-8 w-full" /><Skeleton class="h-8 w-full" /></div>
<template v-else>
<p v-if="triggers.error.value || runs.error.value" role="alert" class="mb-2 text-caption text-danger">{{ triggers.error.value || runs.error.value }}</p>
<DataTable
:columns="columns"
:rows="rows"
:row-key="(r) => r.name"
:row-link="(r) => `/workflows/${r.name}`"
:row-label="(r) => r.name"
storage-key="workflows"
:initial-sort="{ id: 'name', desc: false }"
>
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span> <span class="text-caption text-fg-subtle">v{{ row.version }}</span></template>
<template #cell-triggers="{ row }"><span class="text-caption text-fg-muted">{{ startedBy(row) }}</span></template>
<template #cell-last="{ row }">
<span v-if="row.last" class="flex items-center gap-2"><Badge :variant="stateTone(row.last.state)">{{ row.last.state }}</Badge><Timestamp class="text-caption text-fg-muted" :at="row.last.created_at" /></span>
</template>
<template #cell-steps="{ row }">{{ row.steps }}</template>
<template #cell-updated="{ row }"><Timestamp :at="row.updated" /><span v-if="row.by" class="text-caption text-fg-muted"> by {{ row.by }}</span></template>
<template #empty><Empty><EmptyHeader><EmptyTitle>No workflows</EmptyTitle></EmptyHeader></Empty></template>
</DataTable>
</template>
<Dialog v-model:open="creating">
<DialogContent class="sm:max-w-2xl">
<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]" />
<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>
</DialogContent>
</Dialog>
</div>
</template>
+204 -87
View File
@@ -1,113 +1,230 @@
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
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 { Switch } from "@/components/ui/switch";
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 WorkflowEditor from "./WorkflowEditor.vue";
import { useWorkflowStats } from "./use-workflow-stats";
import { triggerSummary, useWorkflowTriggers } from "./workflow-triggers";
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 { store, data, error, loading, statsKnown, load, enabledOf, setEnabled, duplicate } = useWorkflowStats();
const name = computed(() => String(route.params.id));
// The path names the workflow; the editor renames or clears it by publishing
// under another id or deleting, and the URL follows.
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: "workflow-editor-list" })),
});
// ?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 runOpen = ref(route.query.run !== undefined);
const latest = useRead(() => api.workflow(name.value));
const triggers = useRead(() => api.triggers());
const runs = useRead(() => api.runs());
onMounted(() => {
if (route.query.run !== undefined) void router.replace({ query: { ...route.query, run: undefined } });
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();
});
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";
// 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 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 edited = computed(() => !!latest.data.value && yaml.value !== latest.data.value.body);
async function copy(id: string) {
const next = await duplicate(id);
if (next) selected.value = next;
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="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="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-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">
<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">
<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">{{ 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 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>
<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>
<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 ?? ''"
@duplicate="copy"
@reload-triggers="reloadTriggers"
>
<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>
</WorkflowEditor>
<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>
+7 -12
View File
@@ -1,24 +1,19 @@
<script setup lang="ts">
import { Copy, ListChecks, Play, Trash2 } from "@lucide/vue";
import { Copy, ListChecks } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { MoreMenu } from "@/components/ui/more-menu";
/** Run, and the overflow menu, for one workflow row. */
defineProps<{ id: string; canRun: boolean; stored: boolean }>();
const emit = defineEmits<{ run: []; runs: []; duplicate: []; remove: [] }>();
/** The overflow menu for one workflow row. */
defineProps<{ id: string }>();
const emit = defineEmits<{ runs: []; duplicate: [] }>();
</script>
<template>
<div class="flex items-center gap-1" @click.stop @keydown.stop>
<Button v-if="stored" type="button" size="sm" variant="outline" :disabled="!canRun" :aria-label="`Run ${id}`" :title="canRun ? undefined : 'Disabled'" @click="emit('run')">
<Play data-icon="inline-start" />Run
</Button>
<div class="flex items-center justify-end gap-1" @click.stop @keydown.stop>
<MoreMenu :label="`${id} actions`">
<DropdownMenuItem v-if="stored" @select="emit('runs')"><ListChecks />Open runs</DropdownMenuItem>
<DropdownMenuItem v-if="stored" @select="emit('duplicate')"><Copy />Duplicate</DropdownMenuItem>
<DropdownMenuItem variant="destructive" @select="emit('remove')"><Trash2 />Delete</DropdownMenuItem>
<DropdownMenuItem @select="emit('runs')"><ListChecks />Open runs</DropdownMenuItem>
<DropdownMenuItem @select="emit('duplicate')"><Copy />Duplicate</DropdownMenuItem>
</MoreMenu>
</div>
</template>
+3 -3
View File
@@ -39,8 +39,8 @@ const props = defineProps<{
const emit = defineEmits<{ retry: [] }>();
const runColumns: DataTableColumn<WorkflowRun>[] = [
{ id: "title", label: "Run", fixed: true, class: "w-full max-w-0" },
{ id: "source", label: "Source", class: "max-sm:hidden" },
{ 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 ?? "" },
];
@@ -52,7 +52,7 @@ 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, class: "sm:w-48" },
{ id: "avg", label: "Average", sort: (s) => s.avg_ms || 0, width: "12rem" },
];
function source(run: WorkflowRun): string {
+97 -128
View File
@@ -2,104 +2,80 @@
import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { useMediaQuery } from "@vueuse/core";
import { Copy, ListChecks, Play, Plus, Search, Trash2 } from "@lucide/vue";
import { Copy, ListChecks, Plus, Search } from "@lucide/vue";
import { toast } from "vue-sonner";
import PageHeader from "@/base/PageHeader.vue";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
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 { 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";
import { compact } from "@/lib/format";
import { SEEDED_AGENT_ID } from "./workflow-edit";
import { workflowRows, type WorkflowRow } from "./workflow-rows";
import { byActivity, stepCount } from "./workflow-summary";
import { triggerSummary, useTriggerSources } from "./workflow-triggers";
import { useWorkflowStats } from "./use-workflow-stats";
import { api, describeError } from "@/lib/api";
import { stateTone } from "@/runs/state";
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 { store, data, error, loading, statsKnown, load, enabledOf, setEnabled, duplicate, remove } = useWorkflowStats();
const { rows, error, partial, loading, reload, triggersKnown, runsKnown } = useWorkflowList();
const wide = useMediaQuery("(min-width: 1024px)");
const startedByOf = (id: string) => data.value.definitions?.find((d) => d.id === id)?.started_by ?? [];
const { triggersOf, error: triggersError, known: triggersKnown, reload: reloadTriggers } = useTriggerSources(startedByOf);
interface ListRow extends WorkflowRow {
draft: boolean;
stored: boolean;
steps?: number;
trigger: { text: string; more: string[] };
}
// Stored definitions are the source of truth for the list; statistics join
// them by id, and a workflow seen only in statistics still gets a row.
const stored = computed(() => store.collection.definitions);
const rows = computed<ListRow[]>(() => {
const drafts = store.drafts.filter((draft) => !stored.value.some((d) => d.id === draft.id));
const sources = [...stored.value, ...drafts];
return workflowRows(
data.value.workflows,
sources.map((d) => ({ id: d.id, name: d.id, origin: data.value.definitions?.find((x) => x.id === d.id)?.origin })),
)
.sort(byActivity)
.map((row) => ({
...row,
draft: store.drafts.some((draft) => draft.id === row.id),
stored: stored.value.some((d) => d.id === row.id),
steps: stepCount((stored.value.find((d) => d.id === row.id) ?? store.drafts.find((d) => d.id === row.id))?.yaml ?? ""),
trigger: triggerSummary(triggersOf(row.id)),
}));
});
// A filter earns its place once the list outgrows a glance.
const FILTER_FROM = 8;
const query = ref("");
const shown = computed(() => {
const needle = query.value.trim().toLowerCase();
return needle ? rows.value.filter((row) => row.id.toLowerCase().includes(needle) || row.trigger.text.toLowerCase().includes(needle)) : rows.value;
return needle ? rows.value.filter((row) => row.name.toLowerCase().includes(needle) || row.starts.some((s) => s.toLowerCase().includes(needle))) : rows.value;
});
const open = (id: string, query?: Record<string, string>) => void router.push({ name: "workflow-editor", params: { id }, query });
const run = (id: string) => open(id, { run: "1" });
const openRuns = (id: string) => open(id, { view: "runs" });
const copy = (id: string) => void duplicate(id).then((next) => next && open(next));
const canRun = (row: ListRow) => row.stored && enabledOf(row.id) !== false;
const open = (name: string, query?: Record<string, string>) => void router.push({ path: `/workflows/${name}`, query });
const openRuns = (name: string) => void router.push({ path: "/runs", query: { workflow: name } });
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 stepsLabel = (row: WorkflowRow) => `${row.steps} ${row.steps === 1 ? "step" : "steps"}`;
const deleting = ref("");
async function confirmRemove() {
const id = deleting.value;
deleting.value = "";
await remove(id);
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);
open(next);
} catch (cause) {
toast.error(describeError(cause, errors.common.unknown));
}
}
// A new workflow starts as a draft, so it is in the list straight away and
// nothing runs it until Publish.
async function create() {
let n = 1;
while (rows.value.some((row) => row.id === `workflow-${n}`)) n++;
const id = `workflow-${n}`;
if (await store.putDraft(id, `id: ${id}\nidentity: ${SEEDED_AGENT_ID}\nsteps: []\n`)) open(id);
else toast.error(store.draftState.error || errors.workflows.editor.draftNotSaved);
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();
try {
await api.putWorkflow(name, draft.value.body);
creating.value = false;
open(name);
} catch (cause) {
createError.value = describeError(cause, errors.common.unknown);
} finally {
busy.value = false;
}
}
const reload = () => {
void load();
void store.load();
void reloadTriggers();
};
const anyTokens = computed(() => shown.value.some((row) => row.avg_tokens));
const tokens = (row: ListRow) => (row.avg_tokens ? compact(row.avg_tokens) : "–");
const stepsLabel = (row: ListRow) => (row.steps === undefined ? "" : `${row.steps} ${row.steps === 1 ? "step" : "steps"}`);
</script>
<template>
@@ -109,119 +85,112 @@ const stepsLabel = (row: ListRow) => (row.steps === undefined ? "" : `${row.step
<InputGroupAddon><Search /></InputGroupAddon>
<InputGroupInput v-model="query" type="search" aria-label="Filter workflows" placeholder="Filter" />
</InputGroup>
<Button size="icon-sm" variant="ghost" aria-label="New workflow" title="New workflow" @click="create"><Plus /></Button>
<Button size="icon-sm" variant="ghost" aria-label="New workflow" title="New workflow" @click="creating = true"><Plus /></Button>
</PageHeader>
<div v-if="error || store.error" class="mb-4 text-label text-danger" role="alert">
<p>{{ error || store.error }}</p>
<div v-if="error" class="mb-4 text-label text-danger" role="alert">
<p>{{ error }}</p>
<Button variant="outline" size="sm" @click="reload">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 workflows…</p>
<p v-if="partial" class="mb-2 text-caption text-danger" role="alert">{{ partial }}</p>
<p v-if="loading" class="flex items-center gap-2 text-label text-fg-muted"><Spinner />Loading workflows…</p>
<Empty v-else-if="!rows.length && !error">
<EmptyHeader>
<EmptyTitle>No workflows</EmptyTitle>
</EmptyHeader>
</Empty>
<p v-else-if="!shown.length" class="text-label text-fg-muted">No workflow matches.</p>
<p v-else-if="rows.length && !shown.length" class="text-label text-fg-muted">No workflow matches.</p>
<Table v-else-if="wide" class="table-fixed" aria-label="Workflows">
<Table v-else-if="wide && shown.length" class="table-fixed" aria-label="Workflows">
<TableHeader>
<TableRow>
<TableHead class="w-[22%]">Workflow</TableHead>
<TableHead class="w-[22%]">Starts from</TableHead>
<TableHead class="w-[24%]">Workflow</TableHead>
<TableHead class="w-[24%]">Starts from</TableHead>
<TableHead class="w-16">Steps</TableHead>
<TableHead class="w-20">Enabled</TableHead>
<TableHead class="w-[13%]">Last run</TableHead>
<TableHead class="w-[13%]">Runs</TableHead>
<TableHead v-if="anyTokens" class="w-24 text-right">Tokens</TableHead>
<TableHead class="w-40"><span class="sr-only">Actions</span></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>
</TableRow>
</TableHeader>
<TableBody>
<ContextMenu v-for="row in shown" :key="row.id">
<ContextMenu v-for="row in shown" :key="row.name">
<ContextMenuTrigger as-child>
<TableRow class="cursor-pointer align-middle" @click="open(row.id)">
<TableRow class="cursor-pointer align-middle" @click="open(row.name)">
<TableCell class="whitespace-normal">
<span class="flex min-w-0 items-center gap-2">
<RouterLink :to="{ name: 'workflow', params: { id: row.id } }" class="min-w-0 truncate font-medium hover:underline focus-visible:outline-2 focus-visible:outline-ring" @click.stop>{{ row.id }}</RouterLink>
<Badge v-if="row.draft" variant="outline">Draft</Badge>
<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>
</TableCell>
<TableCell class="whitespace-normal">
<span v-if="row.trigger.text" class="flex min-w-0 items-center gap-1.5">
<span class="truncate">{{ row.trigger.text }}</span>
<Badge v-if="row.trigger.more.length" variant="secondary" :title="row.trigger.more.join('\n')">+{{ row.trigger.more.length }}</Badge>
<span v-if="startsText(row)" class="flex min-w-0 items-center gap-1.5">
<span class="truncate">{{ startsText(row) }}</span>
<Badge v-if="startsMore(row).length" variant="secondary" :title="startsMore(row).join('\n')">+{{ startsMore(row).length }}</Badge>
</span>
<span v-else-if="triggersKnown && !triggersError" class="text-fg-subtle">Manual</span>
<span v-else-if="triggersKnown" class="text-fg-subtle">Manual</span>
</TableCell>
<TableCell class="tabular-nums">{{ row.steps ?? "–" }}</TableCell>
<TableCell>
<Switch v-if="enabledOf(row.id) !== undefined" size="sm" :model-value="enabledOf(row.id)" :aria-label="`${row.id} enabled`" @click.stop @update:model-value="setEnabled(row.id, $event)" />
<TableCell class="tabular-nums">{{ row.steps }}</TableCell>
<TableCell><WorkflowLastRun :to="lastTo(row)" :state="row.last?.state" :tone="row.last && stateTone(row.last.state)" :at="row.last?.created_at" :running="row.running" :known="runsKnown" /></TableCell>
<TableCell><WorkflowDelivery :counts="{ completed: row.succeeded }" :runs="row.runs" /><span v-if="!row.runs && runsKnown" class="text-caption text-fg-subtle">No runs</span></TableCell>
<TableCell class="whitespace-normal">
<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><WorkflowLastRun :run-id="row.last_run_id" :status="row.last_status" :at="row.last_run_at" :running="row.running" :known="statsKnown" /></TableCell>
<TableCell><WorkflowDelivery :counts="row" :runs="row.runs" /><span v-if="!row.runs && statsKnown" class="text-caption text-fg-subtle">No runs</span></TableCell>
<TableCell v-if="anyTokens" class="text-right font-mono tabular-nums" :title="row.avg_tokens ? `${row.avg_tokens.toLocaleString()} tokens per run on average` : undefined">{{ tokens(row) }}</TableCell>
<TableCell class="text-right">
<WorkflowRowActions :id="row.id" :can-run="canRun(row)" :stored="row.stored" @run="run(row.id)" @runs="openRuns(row.id)" @duplicate="copy(row.id)" @remove="deleting = row.id" />
<WorkflowRowActions :id="row.name" @runs="openRuns(row.name)" @duplicate="copy(row)" />
</TableCell>
</TableRow>
</ContextMenuTrigger>
<ContextMenuContent class="min-w-40">
<ContextMenuItem v-if="canRun(row)" @select="run(row.id)"><Play />Run</ContextMenuItem>
<ContextMenuItem v-if="row.stored" @select="openRuns(row.id)"><ListChecks />Open runs</ContextMenuItem>
<ContextMenuItem v-if="row.stored" @select="copy(row.id)"><Copy />Duplicate</ContextMenuItem>
<ContextMenuItem variant="destructive" @select="deleting = row.id"><Trash2 />Delete</ContextMenuItem>
<ContextMenuItem @select="openRuns(row.name)"><ListChecks />Open runs</ContextMenuItem>
<ContextMenuItem @select="copy(row)"><Copy />Duplicate</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>
</TableBody>
</Table>
<ul v-else class="flex flex-col gap-2" aria-label="Workflows">
<li v-for="row in shown" :key="row.id">
<ul v-else-if="shown.length" class="flex flex-col gap-2" aria-label="Workflows">
<li v-for="row in shown" :key="row.name">
<ContextMenu>
<ContextMenuTrigger as-child>
<Card class="cursor-pointer gap-2.5 px-4 py-3 transition-colors hover:bg-secondary/60" @click="open(row.id)">
<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="{ name: 'workflow', params: { id: row.id } }" class="min-w-0 truncate text-label font-medium focus-visible:outline-2 focus-visible:outline-ring" @click.stop>{{ row.id }}</RouterLink>
<Badge v-if="row.draft" variant="outline">Draft</Badge>
<Switch v-if="enabledOf(row.id) !== undefined" size="sm" class="ml-auto" :model-value="enabledOf(row.id)" :aria-label="`${row.id} enabled`" @click.stop @update:model-value="setEnabled(row.id, $event)" />
<WorkflowRowActions :id="row.id" :can-run="canRun(row)" :stored="row.stored" @click.stop @run="run(row.id)" @runs="openRuns(row.id)" @duplicate="copy(row.id)" @remove="deleting = row.id" />
<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)" />
</div>
<p class="flex min-w-0 items-center gap-1.5 text-caption text-fg-muted">
<span class="truncate">{{ row.trigger.text || (triggersKnown && !triggersError ? "Manual" : "") }}</span>
<Badge v-if="row.trigger.more.length" variant="secondary" :title="row.trigger.more.join('\n')">+{{ row.trigger.more.length }}</Badge>
<span v-if="stepsLabel(row)" class="ml-auto shrink-0">{{ stepsLabel(row) }}</span>
<span class="truncate">{{ startsText(row) || (triggersKnown ? "Manual" : "") }}</span>
<Badge v-if="startsMore(row).length" variant="secondary" :title="startsMore(row).join('\n')">+{{ startsMore(row).length }}</Badge>
<span class="ml-auto shrink-0">{{ stepsLabel(row) }}</span>
</p>
<div class="flex items-start justify-between gap-3">
<WorkflowLastRun :run-id="row.last_run_id" :status="row.last_status" :at="row.last_run_at" :running="row.running" :known="statsKnown" />
<WorkflowLastRun :to="lastTo(row)" :state="row.last?.state" :tone="row.last && stateTone(row.last.state)" :at="row.last?.created_at" :running="row.running" :known="runsKnown" />
<div class="flex flex-col items-end gap-1 text-caption text-fg-muted">
<WorkflowDelivery :counts="row" :runs="row.runs" />
<span v-if="row.avg_tokens" class="font-mono">{{ tokens(row) }} tok</span>
<WorkflowDelivery :counts="{ completed: row.succeeded }" :runs="row.runs" />
</div>
</div>
</Card>
</ContextMenuTrigger>
<ContextMenuContent class="min-w-40">
<ContextMenuItem v-if="canRun(row)" @select="run(row.id)"><Play />Run</ContextMenuItem>
<ContextMenuItem v-if="row.stored" @select="openRuns(row.id)"><ListChecks />Open runs</ContextMenuItem>
<ContextMenuItem v-if="row.stored" @select="copy(row.id)"><Copy />Duplicate</ContextMenuItem>
<ContextMenuItem variant="destructive" @select="deleting = row.id"><Trash2 />Delete</ContextMenuItem>
<ContextMenuItem @select="openRuns(row.name)"><ListChecks />Open runs</ContextMenuItem>
<ContextMenuItem @select="copy(row)"><Copy />Duplicate</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>
</li>
</ul>
<AlertDialog :open="!!deleting" @update:open="(value: boolean) => !value && (deleting = '')">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete the {{ deleting }} workflow?</AlertDialogTitle>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" @click="confirmRemove">Delete</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Dialog v-model:open="creating">
<DialogContent class="sm:max-w-2xl">
<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]" />
<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>
</DialogContent>
</Dialog>
</div>
</template>
+80
View File
@@ -0,0 +1,80 @@
import { computed, onMounted } from "vue";
import { api, type Run, type Trigger } from "@/lib/api";
import { usePoll, useRead } from "@/lib/use-read";
import { useLiveResource } from "@/stores/session";
export interface WorkflowRow {
name: string;
version: number;
steps: number;
published: string;
by?: string;
/** What starts it, one entry per distinct way. */
starts: string[];
runs: number;
succeeded: number;
running: number;
last?: Run;
}
const time = (at?: string) => (at ? Date.parse(at) : 0);
/** "24h0m0s" as the server prints a Go duration, "24h" as a person reads it. */
export function interval(duration: string): string {
return duration.replace(/(?<=\D)0s$/, "").replace(/(?<=\D)0m$/, "");
}
/** How a trigger starts its workflow, in words. */
export function startedBy(trigger: Trigger): string {
return trigger.every ? `Every ${interval(trigger.every)}` : `${trigger.source} ${trigger.event_type}`;
}
/** Running workflows first, then by how recently they ran, then by name. */
export function byActivity(a: WorkflowRow, b: WorkflowRow): number {
const live = (b.running ? 1 : 0) - (a.running ? 1 : 0);
if (live) return live;
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. */
export function useWorkflowList() {
const workflows = useRead(() => api.workflowList());
const triggers = useRead(() => api.triggers());
const runs = useRead(() => api.runs());
const reload = () => Promise.all([workflows.reload(), triggers.reload(), runs.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);
return {
rows,
error: workflows.error,
partial,
loading: computed(() => !workflows.data.value && !workflows.error.value),
reload,
triggersKnown: computed(() => !!triggers.data.value),
runsKnown: computed(() => !!runs.data.value),
};
}