fix(ui): stop calling operations the binary does not serve (#2121)

The dashboard is embedded in the single binary, which serves api/openapi.yaml.
It was still calling the old services' routes, so pages that read them answered
with a not-found: the task board, its activity feed and setup panel, logs,
alerts, audit and its export, bindings, schedules, channels, repositories,
skills, curators, the control-plane settings pages, identities and org agents,
the org switcher, secret-reference checks, task metadata, and the audit, usage,
summary and version reads.

Each of those surfaces is removed, and a test compares every /api path in the
dashboard's source with api/openapi.yaml so the next one fails the gate
instead of the browser. Settings that the binary does serve (model providers,
instructions, policies, members) keep their pages.
This commit is contained in:
sam committed 2026-11-27 19:03:02 +11:00
1 parent a23417f392
commit ea6385879f
169 files changed
+245 -15774

No files matched your search

-90
View File
@@ -34,11 +34,6 @@
"label": "Events",
"description": "Received events, their sources, and the triggers that start workflows."
},
{
"path": "/events/bindings",
"label": "Bindings",
"description": "Bindings that decide which workflow an event starts."
},
{
"path": "/events/inspector",
"label": "Inspector",
@@ -59,11 +54,6 @@
"label": "Triggers",
"description": "Triggers that start workflows from events and schedules."
},
{
"path": "/logs",
"label": "Logs",
"description": "Daemon log by level and component."
},
{
"path": "/memory",
"label": "Personal memory",
@@ -74,11 +64,6 @@
"label": "Organisation",
"description": "Members, identities, connections, models and automation."
},
{
"path": "/org/agents",
"label": "Agents",
"description": "Execution identities, their permissions and commit author."
},
{
"path": "/org/alerts",
"label": "Alert webhook",
@@ -89,16 +74,6 @@
"label": "Approvals",
"description": "Default owner, escalation path and approval deadline."
},
{
"path": "/org/audit",
"label": "Audit",
"description": "Settings, access, identity and runtime events."
},
{
"path": "/org/channels",
"label": "Channels",
"description": "Chat channels."
},
{
"path": "/org/connections",
"label": "Connections",
@@ -119,11 +94,6 @@
"label": "Instructions",
"description": "Standing instructions given to every agent in the organisation."
},
{
"path": "/org/issue-routing",
"label": "Issue routing",
"description": "Which workflow an issue runs by its labels."
},
{
"path": "/org/members",
"label": "Members",
@@ -144,26 +114,11 @@
"label": "Policies",
"description": "Access rules for the organisation."
},
{
"path": "/org/repositories",
"label": "Repositories",
"description": "Repository connections, access checks and execution policies."
},
{
"path": "/org/schedules",
"label": "Schedules",
"description": "Time triggers that start workflows."
},
{
"path": "/org/scheduling-policy",
"label": "Scheduling policy",
"description": "Work discovery and forge labels."
},
{
"path": "/org/usage",
"label": "Usage",
"description": "Token spend by model, identity and period."
},
{
"path": "/org/workspaces",
"label": "Workspaces",
@@ -184,36 +139,16 @@
"label": "Instance",
"description": "Every instance-wide setting: models, prompts, connections, runtime and status."
},
{
"path": "/settings/agent-profiles",
"label": "Agent profiles",
"description": "Execution profiles: the image and tools each agent runs with."
},
{
"path": "/settings/authentication",
"label": "Authentication",
"description": "Instance URL and single sign-on providers."
},
{
"path": "/settings/channels",
"label": "Channels",
"description": "Chat channel connections and session defaults."
},
{
"path": "/settings/container-runtime",
"label": "Container runtime",
"description": "How task containers run: runtime, image, limits and egress hosts."
},
{
"path": "/settings/credentials",
"label": "Credentials",
"description": "Sealed credentials extensions and models use."
},
{
"path": "/settings/curators",
"label": "Curators",
"description": "Scheduled memory and capture curation."
},
{
"path": "/settings/extensions",
"label": "Extensions",
@@ -244,41 +179,16 @@
"label": "Organisations",
"description": "The organisations on this instance, and which one is active."
},
{
"path": "/settings/plugins",
"label": "Plugins",
"description": "Extension directories loaded at startup."
},
{
"path": "/settings/secret-engines",
"label": "Secret engines",
"description": "Where secrets are read from: engines, their keys and health."
},
{
"path": "/settings/skills",
"label": "Skills",
"description": "Skills Archie can activate."
},
{
"path": "/settings/status",
"label": "Status",
"description": "Module, connector and runner health, and the running version."
},
{
"path": "/settings/task-execution",
"label": "Task execution",
"description": "Statuses, operator actions, budgets."
},
{
"path": "/settings/tools",
"label": "Tools & MCP",
"description": "Agent tools and MCP servers."
},
{
"path": "/tasks",
"label": "Tasks",
"description": "Picked-up issues and their status."
},
{
"path": "/workflows",
"label": "Workflows",
+1 -15
View File
@@ -7,7 +7,6 @@ import AccountEntry from "@/accounts/AccountEntry.vue";
import { useAccountsStore } from "@/accounts/accounts";
import ChatDock from "@/chat/ChatDock.vue";
import AlertsBell from "@/alerts/AlertsBell.vue";
import CommandPalette from "@/components/command-palette/CommandPalette.vue";
import AccountMenu from "@/components/topbar/AccountMenu.vue";
import OrgCrumb from "@/components/topbar/OrgCrumb.vue";
@@ -21,11 +20,9 @@ import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage, BreadcrumbS
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Card } from "@/components/ui/card";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
import NewTaskDialog from "@/tasks/NewTaskDialog.vue";
import { layoutComponent, resolveLayout } from "@/layouts";
import { TooltipProvider } from "@/components/ui/tooltip";
import { hiddenPaths, navTree } from "@/lib/nav";
import { loadTaskMeta } from "@/lib/task-meta";
import { useSessionStore } from "@/stores/session";
import { Toaster } from "vue-sonner";
import "vue-sonner/style.css";
@@ -55,7 +52,6 @@ void router.isReady().then(() => {
routerReady.value = true;
});
const main = ref<HTMLElement | null>(null);
const newTaskOpen = ref(false);
// A page the caller may not open is not reachable by URL either: the nav drops
// it, so a bookmark or a chat link must not land on a form whose saves the
// control plane refuses.
@@ -94,14 +90,6 @@ watch(() => accounts.status?.user, (user) => {
// loses the entries this process cannot back a moment later, rather than
// holding the page behind a request. A failed read hides nothing.
void session.loadCapabilities();
// The lifecycle vocabulary -- status labels, pill severity, "needs you"
// grouping, and the operator actions -- is served by /api/task-meta. Asked
// for once, after the shell is up: the freeze-dried defaults paint
// immediately and this replaces them, so a catalogue change on the server
// reaches the browser without a UI release. loadTaskMeta never throws (a
// failed read keeps the defaults), so it needs no catch here.
void loadTaskMeta();
});
</script>
@@ -139,10 +127,8 @@ watch(() => accounts.status?.user, (user) => {
</Breadcrumb>
<div class="ml-auto flex shrink-0 items-center gap-4 max-sm:gap-1">
<ConnectionPill />
<CommandPalette :hidden="hidden" @new-task="newTaskOpen = true" />
<NewTaskDialog v-if="session.sections?.work_requests !== false" v-model:open="newTaskOpen" />
<CommandPalette :hidden="hidden" />
<ChatTopbarButton v-if="session.sections?.chat !== false" />
<AlertsBell />
<span><AccountMenu /></span>
</div>
</header>
-93
View File
@@ -1,93 +0,0 @@
<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { computed, ref } from "vue";
import { errors } from "@/copy/errors";
import { Bell, CheckCheck, X } from "@lucide/vue";
import { RouterLink } from "vue-router";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Timestamp } from "@/components/ui/timestamp";
import { groupBySeverity, type AlertSeverity, type OperatorAlert } from "./alerts";
import { useAlerts } from "./use-alerts";
const { alerts, failed, loaded, dismissError, dismiss, dismissAll } = useAlerts();
const open = ref(false);
const groups = computed(() => groupBySeverity(alerts.value));
const tone: Record<AlertSeverity, "danger" | "warn" | "info"> = { action: "danger", warning: "warn", info: "info" };
const label = computed(() =>
alerts.value.length === 0 ? "Alerts" : `Alerts, ${alerts.value.length} open`,
);
function failedDeliveries(alert: OperatorAlert): number {
return alert.deliveries.filter((d) => d.state === "failed").length;
}
</script>
<template>
<Popover v-model:open="open">
<PopoverTrigger as-child>
<Button variant="ghost" size="icon" class="relative" :aria-label="label">
<Bell class="size-4" aria-hidden="true" />
<Badge
v-if="alerts.length"
:variant="groups[0] ? tone[groups[0].severity] : 'info'"
class="absolute -top-0.5 -right-1.5 h-4 min-w-4 px-1 text-caption tabular-nums"
>
{{ alerts.length }}
</Badge>
</Button>
</PopoverTrigger>
<PopoverContent align="end" :collision-padding="8" class="w-[calc(100vw-1rem)] max-w-none p-0 sm:w-96">
<Alert v-if="dismissError" variant="destructive" class="px-3 py-2"><AlertDescription>{{ dismissError }}</AlertDescription></Alert>
<Alert v-if="failed" variant="destructive" class="px-3 py-6 text-center"><AlertDescription>{{ errors.alerts.load }}</AlertDescription></Alert>
<p v-else-if="!loaded" class="px-3 py-6 text-center text-label text-fg-muted" role="status">Loading alerts…</p>
<Empty v-else-if="!groups.length" class="border-0"><EmptyHeader><EmptyTitle>No alerts</EmptyTitle></EmptyHeader></Empty>
<div v-else class="relative max-h-[calc(100dvh-6rem)] overflow-y-auto">
<Tooltip>
<TooltipTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
class="absolute top-1.5 right-1.5"
aria-label="Dismiss all"
@click="dismissAll"
>
<CheckCheck class="size-4" aria-hidden="true" />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">Dismiss all</TooltipContent>
</Tooltip>
<section v-for="group in groups" :key="group.severity" class="border-b p-3 last:border-b-0">
<h3 class="mb-2 text-caption font-semibold text-fg-subtle">{{ group.label }}</h3>
<ul class="grid gap-4">
<li v-for="alert in group.alerts" :key="alert.id" class="flex items-start justify-between gap-2">
<component
:is="alert.link ? RouterLink : 'div'"
v-bind="alert.link ? { to: alert.link } : {}"
class="grid min-w-0 flex-1 gap-1"
:class="alert.link && 'group'"
@click="alert.link && (open = false)"
>
<span class="text-label font-medium group-hover:underline">{{ alert.title }}</span>
<span v-if="alert.body" class="text-label leading-snug text-fg-muted">{{ alert.body }}</span>
<span v-if="failedDeliveries(alert)" class="text-caption text-warn">{{ errors.alerts.webhookDelivery }}</span>
</component>
<Timestamp :at="alert.first_raised" class="mt-0.5 shrink-0 text-caption whitespace-nowrap text-fg-subtle" />
<Tooltip>
<TooltipTrigger as-child>
<Button variant="ghost" size="icon-sm" class="-mr-2 shrink-0" :aria-label="`Dismiss ${alert.title}`" @click="dismiss(alert)"><X /></Button>
</TooltipTrigger>
<TooltipContent>Dismiss</TooltipContent>
</Tooltip>
</li>
</ul>
</section>
</div>
</PopoverContent>
</Popover>
</template>
-37
View File
@@ -1,37 +0,0 @@
/** Operator alerts as the dashboard reads them: what needs attention, by severity. */
export type AlertSeverity = "action" | "warning" | "info";
interface AlertDelivery {
event: string;
state: string;
attempts: { n: number; at: string; status_code?: number; error?: string }[];
}
export interface OperatorAlert {
id: number;
kind: string;
severity: AlertSeverity;
title: string;
body: string;
link?: string;
condition: boolean;
count: number;
first_raised: string;
last_seen: string;
deliveries: AlertDelivery[];
}
/** Most urgent first, as the list groups them. */
const SEVERITY_GROUPS: { severity: AlertSeverity; label: string }[] = [
{ severity: "action", label: "Needs attention" },
{ severity: "warning", label: "Warnings" },
{ severity: "info", label: "Info" },
];
export function groupBySeverity(alerts: readonly OperatorAlert[]) {
return SEVERITY_GROUPS.map((group) => ({
...group,
alerts: alerts.filter((alert) => alert.severity === group.severity),
})).filter((group) => group.alerts.length > 0);
}
-83
View File
@@ -1,83 +0,0 @@
import { storeToRefs } from "pinia";
import { onMounted, ref, watch } from "vue";
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { useSessionStore } from "@/stores/session";
import type { OperatorAlert } from "./alerts";
/**
* The open alerts, shared by every caller (the bell and the dashboard card
* must not hold separate copies): the refs live at module scope, like
* captures/state.ts, and the stream wiring is registered once. The store
* records every alert change as an event, so the newest alert event's id
* moving means the list moved. A reconnect re-reads, since events may have
* been missed.
*/
const alerts = ref<OperatorAlert[]>([]);
const failed = ref(false);
const loaded = ref(false);
const dismissError = ref("");
// Loads overlap when alert events arrive close together; only the newest
// may land, or an older list overwrites a newer one.
let latest = 0;
let wired = false;
// A reconnect replays the backlog, one alert event at a time; read the list
// once per burst instead of once per event.
let pending: ReturnType<typeof setTimeout> | undefined;
function scheduleLoad() {
clearTimeout(pending);
pending = setTimeout(load, 500);
}
async function load() {
const seq = ++latest;
try {
const next = (await api.alerts<{ alerts: OperatorAlert[] }>()).alerts;
if (seq !== latest) return;
alerts.value = next;
failed.value = false;
} catch {
if (seq === latest) failed.value = true;
} finally {
if (seq === latest) loaded.value = true;
}
}
async function dismiss(alert: OperatorAlert) {
latest++;
dismissError.value = "";
try {
await api.dismissAlert(alert.id);
alerts.value = alerts.value.filter((a) => a.id !== alert.id);
} catch (err) {
// The dismiss failed: the alert stays and the reason is shown.
dismissError.value = errors.alerts.dismiss(describeError(err, errors.common.unknown));
await load();
}
}
async function dismissAll() {
const ids = alerts.value.map((a) => a.id);
dismissError.value = "";
const results = await Promise.allSettled(ids.map((id) => api.dismissAlert(id)));
const rejected = results.find((r) => r.status === "rejected");
if (rejected && rejected.status === "rejected") {
dismissError.value = errors.alerts.dismiss(describeError(rejected.reason, errors.common.unknown));
await load();
return;
}
alerts.value = [];
}
export function useAlerts() {
if (!wired) {
wired = true;
const { activity, connectionRevision } = storeToRefs(useSessionStore());
watch(() => activity.value.find((event) => event.kind === "alert")?.id, scheduleLoad);
watch(connectionRevision, scheduleLoad);
onMounted(load);
}
return { alerts, failed, loaded, dismissError, dismiss, dismissAll };
}
-42
View File
@@ -1,42 +0,0 @@
<script setup lang="ts">
import { computed } from "vue";
import { Undo2 } from "@lucide/vue";
import ChangeList from "@/components/ChangeList.vue";
import { Button } from "@/components/ui/button";
import { MetadataList } from "@/components/ui/metadata-list";
import UserReference from "@/org/UserReference.vue";
import {
changesFromFields,
metadataRows,
targetHref,
type AuditRecord,
} from "./audit";
const props = defineProps<{ record: AuditRecord; canRevert?: boolean }>();
defineEmits<{ revert: [] }>();
const changes = computed(() => changesFromFields(props.record.detail));
const rows = computed(() => metadataRows(props.record));
const href = computed(() => targetHref(props.record.target));
</script>
<template>
<div class="space-y-3 py-1">
<ChangeList v-if="changes.length" :changes="changes" :revertable="false" />
<MetadataList v-if="rows.length" :rows="rows">
<template #value="{ row }">
<UserReference v-if="row.key === 'target' && record.target?.kind === 'identity'" :id="record.target.id" :name="record.target.label" />
<RouterLink
v-else-if="row.key === 'target' && href"
:to="href"
class="hover:underline"
>{{ row.value }}</RouterLink>
<template v-else>{{ row.value }}</template>
</template>
</MetadataList>
<div v-if="props.canRevert">
<Button variant="outline" size="sm" @click="$emit('revert')"><Undo2 data-icon="inline-start" />Revert</Button>
</div>
</div>
</template>
-36
View File
@@ -1,36 +0,0 @@
<script setup lang="ts">
import { Download } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { api } from "@/lib/api";
import { exportFilterParams, type AuditQuery } from "./audit";
/** Export is a navigation, not a fetch: the server owns the filename through
* Content-Disposition. The window is resolved when the operator picks a
* format, so the export covers everything visible now rather than at render.
* A new tab keeps a failed export's response visible instead of saving the
* error text as a file. */
const props = defineProps<{ query: AuditQuery }>();
function open(format: "csv" | "json"): void {
window.open(api.auditExportURL(format, exportFilterParams(props.query)), "_blank", "noopener");
}
</script>
<template>
<DropdownMenu>
<DropdownMenuTrigger as-child>
<Button variant="outline" size="sm"><Download data-icon="inline-start" />Export</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem @select="open('csv')">CSV</DropdownMenuItem>
<DropdownMenuItem @select="open('json')">JSON</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</template>
-244
View File
@@ -1,244 +0,0 @@
<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from "vue";
import { ListFilter, X } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Toggle } from "@/components/ui/toggle";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import {
filterChips,
presetLabel,
valueLabel,
type AuditChip,
type AuditFacets,
type AuditQuery,
} from "./audit";
const props = defineProps<{ query: AuditQuery; facets: AuditFacets }>();
const emit = defineEmits<{ change: [patch: Partial<AuditQuery>] }>();
const advancedOpen = ref(false);
// Search is typed, so it settles before it reaches the URL and the server.
const search = ref(props.query.q ?? "");
let searchTimer: ReturnType<typeof setTimeout> | undefined;
watch(
() => props.query.q,
(value) => {
const next = value ?? "";
if (next !== search.value) search.value = next;
},
);
watch(search, (value) => {
clearTimeout(searchTimer);
const next = value.trim();
if (next === (props.query.q ?? "")) return;
searchTimer = setTimeout(() => emit("change", { q: next || undefined }), 300);
});
onUnmounted(() => clearTimeout(searchTimer));
const actor = ref(props.query.actor ?? "");
const action = ref((props.query.actions ?? []).join(", "));
const targetId = ref(props.query.target_id ?? "");
const from = ref(props.query.from ?? "");
const to = ref(props.query.to ?? "");
watch(() => props.query.actor, (value) => (actor.value = value ?? ""));
watch(() => props.query.actions.join(","), () => (action.value = props.query.actions.join(", ")));
watch(() => props.query.target_id, (value) => (targetId.value = value ?? ""));
watch(() => props.query.from, (value) => (from.value = value ?? ""));
watch(() => props.query.to, (value) => (to.value = value ?? ""));
const preset = computed(() =>
props.query.from || props.query.to ? "custom" : props.query.since || "30d",
);
function setPreset(value: unknown) {
if (typeof value !== "string" || value === "custom") return;
emit("change", {
since: value === "30d" ? undefined : value,
from: undefined,
to: undefined,
});
}
function setCategories(value: unknown) {
emit("change", { categories: Array.isArray(value) ? value.map(String) : [] });
}
function setDenied(value: boolean) {
emit("change", { outcome: value ? "denied" : undefined });
}
function commitActor() {
emit("change", { actor: actor.value.trim() || undefined });
}
function commitAction() {
const list = action.value.split(",").map((entry) => entry.trim()).filter(Boolean);
emit("change", { actions: list });
}
function commitTargetId() {
emit("change", { target_id: targetId.value.trim() || undefined });
}
function commitFrom() {
emit("change", { from: from.value || undefined, since: undefined });
}
function commitTo() {
emit("change", { to: to.value || undefined, since: undefined });
}
const chips = computed(() => filterChips(props.query, props.facets));
const advancedCount = computed(
() =>
props.query.actions.length +
(props.query.actor ? 1 : 0) +
(props.query.severity ? 1 : 0) +
(props.query.target_kind ? 1 : 0) +
(props.query.target_id ? 1 : 0) +
(props.query.from ? 1 : 0) +
(props.query.to ? 1 : 0),
);
function removeChip(chip: AuditChip) {
if (chip.key === "kind") {
emit("change", { kinds: props.query.kinds.filter((kind) => kind !== chip.value) });
return;
}
if (chip.key === "action") {
emit("change", { actions: props.query.actions.filter((entry) => entry !== chip.value) });
return;
}
const patch: Partial<AuditQuery> = {};
patch[chip.key] = undefined;
emit("change", patch);
}
</script>
<template>
<div class="mb-3">
<div class="flex flex-wrap items-center gap-2">
<Input
v-model="search"
type="search"
aria-label="Search events"
placeholder="Search"
class="w-full sm:max-w-56"
/>
<ToggleGroup
v-if="props.facets.categories.length"
type="multiple"
variant="outline"
size="sm"
:model-value="props.query.categories"
aria-label="Categories"
class="max-w-full flex-wrap"
@update:model-value="setCategories"
>
<ToggleGroupItem
v-for="option in props.facets.categories"
:key="option"
:value="option"
>{{ valueLabel(option) }}</ToggleGroupItem>
</ToggleGroup>
<Select :model-value="preset" @update:model-value="setPreset">
<SelectTrigger class="w-36" aria-label="Time range"><SelectValue>{{ presetLabel(props.query) }}</SelectValue></SelectTrigger>
<SelectContent>
<SelectItem value="any">Any time</SelectItem>
<SelectItem value="24h">Last 24 hours</SelectItem>
<SelectItem value="7d">Last 7 days</SelectItem>
<SelectItem value="30d">Last 30 days</SelectItem>
</SelectContent>
</Select>
<Toggle
variant="outline"
size="sm"
:model-value="props.query.outcome === 'denied'"
@update:model-value="setDenied"
>Denied</Toggle>
<Popover v-model:open="advancedOpen">
<PopoverTrigger as-child>
<Button variant="outline" size="sm" aria-label="Filters">
<ListFilter data-icon="inline-start" />Filters<Badge v-if="advancedCount" variant="secondary" class="ml-1">{{ advancedCount }}</Badge>
</Button>
</PopoverTrigger>
<PopoverContent align="start" class="w-96 max-w-[calc(100vw-2rem)]">
<div class="grid gap-3">
<div class="grid gap-1.5">
<Label for="audit-actor">Actor</Label>
<Input id="audit-actor" v-model="actor" @change="commitActor" @keydown.enter="commitActor" />
</div>
<div class="grid gap-1.5">
<Label for="audit-action">Action</Label>
<Input id="audit-action" v-model="action" @change="commitAction" @keydown.enter="commitAction" />
</div>
<div class="grid gap-1.5">
<Label for="audit-severity">Severity</Label>
<Select
:model-value="props.query.severity || 'any'"
@update:model-value="(value) => emit('change', { severity: value === 'any' || !value ? undefined : String(value) })"
>
<SelectTrigger id="audit-severity" class="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="any">Any severity</SelectItem>
<SelectItem v-for="option in props.facets.severities" :key="option" :value="option">{{ valueLabel(option) }}</SelectItem>
</SelectContent>
</Select>
</div>
<div class="grid gap-1.5">
<Label for="audit-target-kind">Target kind</Label>
<Select
:model-value="props.query.target_kind || 'any'"
@update:model-value="(value) => emit('change', { target_kind: value === 'any' || !value ? undefined : String(value) })"
>
<SelectTrigger id="audit-target-kind" class="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="any">Any target kind</SelectItem>
<SelectItem v-for="option in props.facets.target_kinds" :key="option" :value="option">{{ valueLabel(option) }}</SelectItem>
</SelectContent>
</Select>
</div>
<div class="grid gap-1.5">
<Label for="audit-target-id">Target</Label>
<Input id="audit-target-id" v-model="targetId" @change="commitTargetId" @keydown.enter="commitTargetId" />
</div>
<div class="grid grid-cols-2 gap-2">
<div class="grid gap-1.5">
<Label for="audit-from">From</Label>
<Input id="audit-from" v-model="from" type="datetime-local" @change="commitFrom" />
</div>
<div class="grid gap-1.5">
<Label for="audit-to">To</Label>
<Input id="audit-to" v-model="to" type="datetime-local" @change="commitTo" />
</div>
</div>
</div>
</PopoverContent>
</Popover>
</div>
<ul v-if="chips.length" class="mt-2 flex flex-wrap gap-1.5" aria-label="Active filters">
<li v-for="chip in chips" :key="`${chip.key}:${chip.value}`">
<Button
variant="secondary"
size="sm"
:aria-label="`Remove ${chip.text}`"
@click="removeChip(chip)"
>{{ chip.text }}<X data-icon="inline-end" /></Button>
</li>
</ul>
</div>
</template>
-504
View File
@@ -1,504 +0,0 @@
import type { LocationQuery } from "vue-router";
import type { QueryParams } from "@/lib/api";
import { formatValue, type Change } from "@/lib/changes";
import { exactTime } from "../lib/format.ts";
import { useAppearanceStore } from "../stores/appearance";
/** One actor as the audit feed reports it. */
interface AuditActor {
id: string;
name?: string;
kind?: string;
principal_id?: string;
}
/** The thing the event happened to; `href` is a same-origin dashboard route. */
export interface AuditTarget {
kind: string;
id: string;
label?: string;
href?: string;
}
interface AuditField {
field: string;
old?: unknown;
new?: unknown;
}
/** Per-event context. A settings change carries `fields`; a runtime event
* carries `data`. */
export interface AuditDetail {
fields?: AuditField[];
data?: Record<string, unknown> | null;
version?: number;
request_id?: string;
source?: string;
table?: string;
}
type AuditCategory = "settings" | "access" | "identity" | "runtime" | "automation";
type AuditSeverity = "info" | "warning" | "error";
type AuditOutcome = "success" | "denied" | "failure";
export interface AuditRecord {
/** Composite and opaque, e.g. "1:42". */
id: string;
at: string;
category: AuditCategory;
action: string;
kind: string;
severity: AuditSeverity;
outcome: AuditOutcome;
actor: AuditActor;
target: AuditTarget;
summary: string;
detail?: AuditDetail;
}
/** One settings kind the feed can name, with its catalog title. */
interface SettingsKind {
kind: string;
title: string;
}
/** The server's closed vocabularies, so the UI never invents one. */
export interface AuditFacets {
categories: string[];
severities: string[];
outcomes: string[];
target_kinds: string[];
settings_kinds: SettingsKind[];
/** The runtime event kinds the instance's audit retention can window. */
retention_kinds: string[];
}
export interface AuditResponse {
records: AuditRecord[];
next_cursor?: string | null;
has_more: boolean;
facets?: AuditFacets;
}
export function emptyFacets(): AuditFacets {
return {
categories: [],
severities: [],
outcomes: [],
target_kinds: [],
settings_kinds: [],
retention_kinds: [],
};
}
/** The filter state carried in the URL. */
export interface AuditQuery {
q?: string;
categories: string[];
kinds: string[];
actions: string[];
actor?: string;
target_kind?: string;
target_id?: string;
severity?: string;
outcome?: string;
/** 24h, 7d, 30d or any. Absent means the default 30 days. */
since?: string;
/** Custom range, in datetime-local form. */
from?: string;
to?: string;
}
const PRESET_MS: Record<string, number> = {
"24h": 86_400_000,
"7d": 604_800_000,
"30d": 2_592_000_000,
};
/** The default window: what the time select shows when the URL is bare. */
const DEFAULT_SINCE = "30d";
/** Export names its own start when the operator chose Any time. */
const EPOCH = "1970-01-01T00:00:00Z";
function text(value: LocationQuery[string] | undefined): string | undefined {
const first = Array.isArray(value) ? value[0] : value;
const trimmed = first == null ? "" : String(first).trim();
return trimmed || undefined;
}
function list(value: LocationQuery[string] | undefined): string[] {
if (value == null) return [];
const raw = Array.isArray(value) ? value : [value];
return raw
.flatMap((item) => String(item).split(","))
.map((item) => item.trim())
.filter(Boolean);
}
/** Reads the URL into a query. `section` is the pre-Audit deep-link name for
* the resource-kind filter, and still wins when `kind` is absent. */
export function queryFromRoute(query: LocationQuery): AuditQuery {
const kinds = list(query.kind);
return {
q: text(query.q),
categories: list(query.categories),
kinds: kinds.length ? kinds : list(query.section),
actions: list(query.actions),
actor: text(query.actor),
target_kind: text(query.target_kind),
target_id: text(query.target_id),
severity: text(query.severity),
outcome: text(query.outcome),
since: text(query.since),
from: text(query.from),
to: text(query.to),
};
}
/** Writes a query back as URL values: arrays are comma-joined so a shared or
* bookmarked URL stays readable. */
export function routeQueryFor(query: AuditQuery): Record<string, string> {
const out: Record<string, string> = {};
const put = (key: string, value: string | undefined) => {
if (value) out[key] = value;
};
put("q", query.q?.trim());
put("categories", query.categories.join(","));
put("actions", query.actions.join(","));
put("kind", query.kinds.join(","));
put("actor", query.actor?.trim());
put("target_kind", query.target_kind);
put("target_id", query.target_id?.trim());
put("severity", query.severity);
put("outcome", query.outcome);
put("since", query.since);
put("from", query.from);
put("to", query.to);
return out;
}
function instant(value: string | undefined): string | undefined {
if (!value) return undefined;
const date = new Date(value);
return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
}
function presetMs(since?: string): number {
return PRESET_MS[since ?? DEFAULT_SINCE] ?? PRESET_MS[DEFAULT_SINCE];
}
/** Resolves the explicit window once per load. The cursor is bound to these
* exact bounds, so pagination must not recompute them. */
function timeBounds(
query: AuditQuery,
now = Date.now(),
): { from?: string; to?: string } {
const from = instant(query.from);
const to = instant(query.to);
if (from || to) return { from, to };
if (query.since === "any") return {};
return { from: new Date(now - presetMs(query.since)).toISOString() };
}
/** The server filter for one page. Arrays become repeated parameters. */
export function apiParams(query: AuditQuery, now = Date.now()): QueryParams {
const { from, to } = timeBounds(query, now);
return {
q: query.q?.trim() || undefined,
categories: query.categories.length ? query.categories : undefined,
actions: query.actions.length ? query.actions : undefined,
kind: query.kinds.length ? query.kinds : undefined,
actor: query.actor?.trim() || undefined,
target_kind: query.target_kind,
target_id: query.target_id?.trim() || undefined,
severity: query.severity,
outcome: query.outcome,
from,
to,
};
}
/** Export takes both ends explicitly: the server refuses to guess a window.
* An open start is the epoch sentinel, and both preset and default windows
* resolve to concrete timestamps. */
export function exportFilterParams(query: AuditQuery, now = Date.now()): QueryParams {
const params = apiParams(query, now);
const to = instant(query.to) ?? new Date(now).toISOString();
const from =
instant(query.from) ??
(query.since === "any"
? EPOCH
: new Date(now - presetMs(query.since)).toISOString());
return { ...params, from, to };
}
export function hasFilters(query: AuditQuery): boolean {
return !!(
query.q ||
query.categories.length ||
query.kinds.length ||
query.actions.length ||
query.actor ||
query.target_kind ||
query.target_id ||
query.severity ||
query.outcome ||
query.from ||
query.to
);
}
/** What the table says when the server returned no rows. An empty feed and a
* filter that matched nothing must not read the same. */
export function emptyMessage(query: AuditQuery): string {
if (hasFilters(query)) return "No records match these filters.";
if (query.since === "any") return "No audit records yet.";
if (query.from || query.to) return "No records in this range.";
const window = query.since === "24h" ? "24 hours" : query.since === "7d" ? "7 days" : "30 days";
return `No records in the last ${window}.`;
}
export function presetLabel(query: AuditQuery): string {
if (query.from || query.to) return "Custom range";
switch (query.since) {
case "any":
return "Any time";
case "24h":
return "Last 24 hours";
case "7d":
return "Last 7 days";
default:
return "Last 30 days";
}
}
export interface AuditChip {
key:
| "kind"
| "action"
| "actor"
| "severity"
| "outcome"
| "target_kind"
| "target_id"
| "from"
| "to";
value: string;
text: string;
}
/** A server value read as a label: "access_policies" -> "Access policies". */
export function valueLabel(value: string): string {
const words = value.replaceAll("_", " ").replaceAll("-", " ");
return words ? words.charAt(0).toUpperCase() + words.slice(1) : value;
}
function settingsKindLabel(options: SettingsKind[], value: string): string {
return options.find((option) => option.kind === value)?.title ?? value;
}
function localTime(value: string): string {
const date = new Date(value);
// In the zone chosen under Appearance, like Timestamp, not the browser's.
return Number.isNaN(date.getTime()) ? value : exactTime(date, useAppearanceStore().timeZone);
}
/** The advanced and deep-link filters as removable chips. */
export function filterChips(query: AuditQuery, facets: AuditFacets): AuditChip[] {
return [
...query.kinds.map((value) => ({
key: "kind" as const,
value,
text: `Kind: ${settingsKindLabel(facets.settings_kinds, value)}`,
})),
...query.actions.map((value) => ({
key: "action" as const,
value,
text: `Action: ${value}`,
})),
...(query.actor ? [{ key: "actor" as const, value: query.actor, text: `Actor: ${query.actor}` }] : []),
...(query.severity
? [
{
key: "severity" as const,
value: query.severity,
text: `Severity: ${valueLabel(query.severity)}`,
},
]
: []),
// Denied has its own toggle; any other outcome is reachable only by URL,
// so it gets a chip or it would filter invisibly.
...(query.outcome && query.outcome !== "denied"
? [
{
key: "outcome" as const,
value: query.outcome,
text: `Outcome: ${valueLabel(query.outcome)}`,
},
]
: []),
...(query.target_kind
? [
{
key: "target_kind" as const,
value: query.target_kind,
text: `Target kind: ${valueLabel(query.target_kind)}`,
},
]
: []),
...(query.target_id
? [{ key: "target_id" as const, value: query.target_id, text: `Target: ${query.target_id}` }]
: []),
...(query.from ? [{ key: "from" as const, value: query.from, text: `From: ${localTime(query.from)}` }] : []),
...(query.to ? [{ key: "to" as const, value: query.to, text: `To: ${localTime(query.to)}` }] : []),
];
}
export type AuditBadgeVariant = "danger" | "warn" | "info";
/** A textual badge carries severity; colour alone never does. An error is a
* failure of the event whether or not its outcome says success. */
export function badgeFor(record: AuditRecord): { label: string; variant: AuditBadgeVariant } | null {
if (record.outcome === "denied") return { label: "Denied", variant: "danger" };
if (record.outcome === "failure" || record.severity === "error")
return { label: "Failed", variant: "danger" };
if (record.severity === "warning") return { label: "Warning", variant: "warn" };
return null;
}
/** One leaf per changed field, in the shape ChangeList renders. */
export function changesFromFields(detail?: AuditDetail): Change[] {
return (detail?.fields ?? []).map((field, index) => ({
path: field.field || `field ${index + 1}`,
before: field.old,
after: field.new,
}));
}
export interface AuditMetadataRow {
key: string;
label: string;
value?: string;
mono?: boolean;
}
function humanise(field: string): string {
return field.replaceAll("_", " ").replaceAll("-", " ");
}
/** Label/value rows for a runtime event: its target, its data and how it was
* recorded. A settings change shows its diff instead. */
export function metadataRows(record: AuditRecord): AuditMetadataRow[] {
const detail = record.detail ?? {};
const rows: AuditMetadataRow[] = [];
if (!detail.fields?.length && hasTarget(record.target)) {
rows.push({
key: "target",
label: "Target",
value: record.target?.label || record.target?.id || "",
});
}
if (detail.data && typeof detail.data === "object" && !Array.isArray(detail.data)) {
for (const [key, value] of Object.entries(detail.data as Record<string, unknown>)) {
rows.push({
key: `data.${key}`,
label: humanise(key),
value: formatValue(value),
mono: typeof value !== "string",
});
}
} else if (detail.data != null) {
rows.push({ key: "data", label: "Data", value: formatValue(detail.data), mono: true });
}
if (detail.table) rows.push({ key: "table", label: "Table", value: detail.table, mono: true });
if (detail.source) rows.push({ key: "source", label: "Source", value: detail.source, mono: true });
if ((detail.version ?? 0) > 0)
rows.push({ key: "version", label: "Version", value: String(detail.version), mono: true });
if (detail.request_id)
rows.push({ key: "request", label: "Request", value: detail.request_id, mono: true });
return rows;
}
export function recordKey(record: AuditRecord): string {
return record.id;
}
/** A target exists when it names anything; an event may have none. */
export function hasTarget(target?: AuditTarget): boolean {
return !!target && !!(target.kind || target.id);
}
/** The dashboard route for a target. A task route is built from its id, so an
* older server href cannot send the operator to the wrong page. */
export function targetHref(target?: AuditTarget): string {
if (target?.kind === "task" && target.id)
return `/tasks/${encodeURIComponent(target.id)}`;
return target?.href ?? "";
}
/** The target's own id when it adds anything beyond the label: the settings
* resource kind, a record key, or a task id. */
export function targetDetail(target?: AuditTarget): string {
if (!target?.id) return "";
const label = target.label ?? "";
if (label && (label === target.id || label.endsWith(target.id))) return "";
return target.id;
}
/** Keeps the first occurrence, so a live page and an older page cannot show
* the same event twice. */
export function dedupeRecords(records: AuditRecord[]): AuditRecord[] {
const seen = new Set<string>();
return records.filter((record) => {
const key = recordKey(record);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
/** Saved views live in this browser, keyed by the signed-in identity. */
export interface SavedAuditView {
name: string;
query: Record<string, string>;
}
function savedViewsKey(identityId: string): string {
return `archie.audit.views.${identityId}`;
}
export function readSavedViews(identityId: string): SavedAuditView[] {
if (!identityId) return [];
try {
const raw = localStorage.getItem(savedViewsKey(identityId));
if (!raw) return [];
const parsed: unknown = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
return parsed.flatMap((entry): SavedAuditView[] => {
if (!entry || typeof entry !== "object") return [];
const candidate = entry as { name?: unknown; query?: unknown };
if (typeof candidate.name !== "string" || !candidate.name.trim()) return [];
if (!candidate.query || typeof candidate.query !== "object") return [];
const query = Object.fromEntries(
Object.entries(candidate.query as Record<string, unknown>).map(([key, value]) => [
key,
String(value),
]),
);
return [{ name: candidate.name, query }];
});
} catch {
return [];
}
}
export function writeSavedViews(identityId: string, views: SavedAuditView[]): void {
if (!identityId) return;
try {
localStorage.setItem(savedViewsKey(identityId), JSON.stringify(views));
} catch {
// The view still applies for this page; only persistence is lost.
}
}
-165
View File
@@ -1,165 +0,0 @@
import { defineStore } from "pinia";
import { ref } from "vue";
import { errors } from "@/copy/errors";
import { ApiError, api, describeError, type QueryParams } from "@/lib/api";
import {
apiParams,
dedupeRecords,
emptyFacets,
recordKey,
type AuditFacets,
type AuditQuery,
type AuditRecord,
type AuditResponse,
} from "./audit";
const PAGE_SIZE = 100;
function failure(err: unknown): string {
if (err instanceof ApiError && err.status === 503) return errors.audit.unavailable;
return describeError(err, errors.audit.load);
}
/** The server's vocabularies arrive with the first page; a later page that
* omits one must not blank the filters the operator is using. */
function facetsFrom(next: AuditFacets | undefined, current: AuditFacets): AuditFacets {
if (!next) return current;
const pick = <T,>(incoming: T[] | undefined, previous: T[]): T[] =>
incoming?.length ? incoming : previous;
return {
categories: pick(next.categories, current.categories),
severities: pick(next.severities, current.severities),
outcomes: pick(next.outcomes, current.outcomes),
target_kinds: pick(next.target_kinds, current.target_kinds),
settings_kinds: pick(next.settings_kinds, current.settings_kinds),
retention_kinds: pick(next.retention_kinds, current.retention_kinds),
};
}
/** One loaded audit feed. Filters live in the URL; this store owns only the
* pages fetched for the current filter. */
export const useAuditStore = defineStore("audit", () => {
const records = ref<AuditRecord[]>([]);
const facets = ref<AuditFacets>(emptyFacets());
const loading = ref(false);
const loadingMore = ref(false);
const error = ref("");
const moreError = ref("");
const nextCursor = ref<string | null>(null);
const hasMore = ref(false);
let generation = 0;
let pages = 1;
// Resolved once per filter load: the cursor is bound to these exact bounds.
let params: QueryParams = {};
async function load(query: AuditQuery): Promise<void> {
const token = ++generation;
params = apiParams(query);
loading.value = true;
loadingMore.value = false;
error.value = "";
moreError.value = "";
records.value = [];
nextCursor.value = null;
hasMore.value = false;
pages = 1;
try {
const response = await api.audit<AuditResponse>({ ...params, limit: PAGE_SIZE });
if (token !== generation) return;
records.value = dedupeRecords(response.records ?? []);
facets.value = facetsFrom(response.facets, facets.value);
nextCursor.value = response.next_cursor || null;
hasMore.value = !!response.has_more;
} catch (err) {
if (token !== generation) return;
error.value = failure(err);
} finally {
if (token === generation) loading.value = false;
}
}
async function loadMore(): Promise<void> {
if (!nextCursor.value || loading.value || loadingMore.value) return;
const token = generation;
loadingMore.value = true;
moreError.value = "";
try {
const response = await api.audit<AuditResponse>({
...params,
cursor: nextCursor.value,
limit: PAGE_SIZE,
});
if (token !== generation) return;
records.value = dedupeRecords([...records.value, ...(response.records ?? [])]);
nextCursor.value = response.next_cursor || null;
hasMore.value = !!response.has_more;
pages += 1;
} catch (err) {
if (token === generation) moreError.value = failure(err);
} finally {
if (token === generation) loadingMore.value = false;
}
}
/** Merges a fresh page one into the loaded feed: an id already on screen
* keeps its place, replaced when the server now sends different content (a
* coalesced access decision count, for example). An unseen id is returned so the page can
* prepend it or hold it behind the new-events button. */
function mergePageOne(incoming: AuditRecord[]): AuditRecord[] {
const positions = new Map(records.value.map((record, index) => [recordKey(record), index]));
const merged = records.value.slice();
const added: AuditRecord[] = [];
let replaced = false;
for (const record of dedupeRecords(incoming)) {
const at = positions.get(recordKey(record));
if (at === undefined) {
added.push(record);
continue;
}
if (JSON.stringify(merged[at]) === JSON.stringify(record)) continue;
merged[at] = record;
replaced = true;
}
if (replaced) records.value = merged;
return added;
}
/** Re-reads page one after a live head. Returns the records this page did
* not already hold; the page decides whether to prepend or hold them. */
async function refresh(): Promise<AuditRecord[]> {
if (loading.value || error.value) return [];
const token = generation;
const response = await api.audit<AuditResponse>({ ...params, limit: PAGE_SIZE });
if (token !== generation) return [];
facets.value = facetsFrom(response.facets, facets.value);
// Only a single-page feed can take the new page-one cursor: a loaded older
// page is keyed to the cursor the operator is paging from.
if (pages === 1) {
nextCursor.value = response.next_cursor || null;
hasMore.value = !!response.has_more;
}
return mergePageOne(response.records ?? []);
}
function prepend(incoming: AuditRecord[]): void {
if (!incoming.length) return;
records.value = dedupeRecords([...incoming, ...records.value]);
}
return {
records,
facets,
loading,
loadingMore,
error,
moreError,
nextCursor,
hasMore,
load,
loadMore,
refresh,
prepend,
};
});
@@ -16,16 +16,13 @@ import { Kbd } from "@/components/ui/kbd";
import { api } from "@/lib/api";
import { errors } from "@/copy/errors";
import { navEntries } from "@/lib/nav";
import { statusLabel } from "@/lib/task-meta";
import { useSessionStore } from "@/stores/session";
/**
* Jump to a page, a task or a workflow by name. Opened from the top bar, with
* Cmd/Ctrl+K, or with '/' when no field has focus. Tasks and workflows are
* read when the palette opens, so it never shows a stale list for long.
* Jump to a page or a workflow by name. Opened from the top bar, with
* Cmd/Ctrl+K, or with '/' when no field has focus. Workflows are read when the
* palette opens, so it never shows a stale list for long.
*/
const props = defineProps<{ hidden: string[] }>();
const emit = defineEmits<{ newTask: [] }>();
const router = useRouter();
const open = ref(false);
@@ -36,35 +33,19 @@ function onCloseAutoFocus(event: Event): void {
document.getElementById("main-content")?.focus({ preventScroll: true });
}
interface TaskEntry {
id: number | string;
title?: string;
status?: string;
}
const pages = computed(() => navEntries(props.hidden));
const tasks = ref<TaskEntry[]>([]);
const workflows = ref<{ id: string; name: string }[]>([]);
const shortcut = navigator.platform.startsWith("Mac") ? "⌘K" : "Ctrl K";
const session = useSessionStore();
const showWorkflows = computed(() => !props.hidden.includes("/workflows"));
const showTasks = computed(() => !props.hidden.includes("/tasks"));
const showNewTask = computed(() => session.sections?.work_requests !== false);
// A failed read shows as an error item with Retry in that group, not as a
// missing group: the pages still work either way.
const tasksError = ref(false);
const workflowsError = ref(false);
let entriesGeneration = 0;
async function loadEntries(): Promise<void> {
const current = ++entriesGeneration;
const [taskPage, workflowList] = await Promise.all([
showTasks.value ? api.taskPage<TaskEntry>({ limit: 100 }).catch(() => null) : { tasks: [] },
showWorkflows.value ? api.workflowList().catch(() => null) : [],
]);
const workflowList = showWorkflows.value ? await api.workflowList().catch(() => null) : [];
if (current !== entriesGeneration) return;
tasksError.value = taskPage === null;
tasks.value = taskPage?.tasks ?? [];
workflowsError.value = workflowList === null;
workflows.value = (workflowList ?? []).map(({ id, name }) => ({ id, name }));
}
@@ -78,11 +59,6 @@ function go(path: string): void {
void router.push(path);
}
function newTask(): void {
open.value = false;
emit("newTask");
}
function onGlobalKeydown(event: KeyboardEvent): void {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
event.preventDefault();
@@ -106,17 +82,10 @@ onUnmounted(() => document.removeEventListener("keydown", onGlobalKeydown));
<span class="max-lg:hidden">Jump to</span>
<Kbd class="ml-auto max-lg:hidden">{{ shortcut }}</Kbd>
</Button>
<CommandDialog @close-auto-focus="onCloseAutoFocus" v-model:open="open" title="Jump to" description="Find a page, task or workflow.">
<CommandInput placeholder="Find a page, task or workflow" />
<CommandDialog @close-auto-focus="onCloseAutoFocus" v-model:open="open" title="Jump to" description="Find a page or a workflow.">
<CommandInput placeholder="Find a page or a workflow" />
<CommandList>
<CommandEmpty>No matches.</CommandEmpty>
<CommandGroup v-if="showNewTask" heading="Actions">
<CommandItem value="New task" @select="newTask">New task</CommandItem>
</CommandGroup>
<CommandGroup heading="Views">
<CommandItem value="Tasks in progress" @select="go('/tasks?status=running')">Tasks in progress</CommandItem>
<CommandItem value="Tasks needing attention" @select="go('/tasks?status=needs_attention')">Tasks needing attention</CommandItem>
</CommandGroup>
<CommandGroup heading="Pages">
<CommandItem
v-for="entry in pages"
@@ -140,23 +109,6 @@ onUnmounted(() => document.removeEventListener("keydown", onGlobalKeydown));
{{ workflow.name }}
</CommandItem>
</CommandGroup>
<CommandGroup v-if="tasksError" heading="Tasks">
<CommandItem value="tasks-error" @select="loadEntries">{{ errors.components.commandPalette.tasks }}</CommandItem>
</CommandGroup>
<CommandGroup v-else-if="tasks.length" heading="Tasks">
<CommandItem
v-for="task in tasks"
:key="task.id"
:value="`task:${task.id}`"
@select="go(`/tasks/${task.id}`)"
>
<span class="text-fg-muted shrink-0 tabular-nums">#{{ task.id }}</span>
<span class="truncate">{{ task.title }}</span>
<span v-if="task.status" class="text-fg-muted ml-auto shrink-0 text-caption">{{
statusLabel(task.status)
}}</span>
</CommandItem>
</CommandGroup>
</CommandList>
</CommandDialog>
</template>
+1 -2
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { LogOut, NotebookText, Palette, ScrollText, UserRound } from "@lucide/vue";
import { LogOut, NotebookText, Palette, UserRound } from "@lucide/vue";
import { useAccountsStore } from "@/accounts/accounts";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
@@ -31,7 +31,6 @@ const accounts = useAccountsStore();
<DropdownMenuItem as-child><RouterLink to="/account"><UserRound />Your account</RouterLink></DropdownMenuItem>
<DropdownMenuItem as-child><RouterLink to="/memory"><NotebookText />Memory</RouterLink></DropdownMenuItem>
<DropdownMenuItem as-child><RouterLink to="/account/appearance"><Palette />Appearance</RouterLink></DropdownMenuItem>
<DropdownMenuItem as-child><RouterLink to="/logs"><ScrollText />Logs</RouterLink></DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem @select="accounts.signOut"><LogOut />Sign out</DropdownMenuItem>
+2 -40
View File
@@ -1,56 +1,18 @@
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { computed, onMounted, ref } from "vue";
import { Check, ChevronDown } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useOrgStore } from "@/stores/org";
import { errors } from "@/copy/errors";
import { describeError } from "@/lib/api";
import { useHoverOpen } from "./hover-open";
const orgStore = useOrgStore();
const { homeOrg, memberOrgs, orgs } = storeToRefs(orgStore);
const failed = ref("");
onMounted(() => void orgStore.loadOrg().catch((cause) => (failed.value = describeError(cause, errors.common.unknown))));
const choices = computed(() => orgs.value.filter((o) => memberOrgs.value.includes(o.id)));
const name = computed(() => orgs.value.find((o) => o.id === homeOrg.value)?.name ?? (failed.value ? errors.components.org.unavailable : "Loading…"));
async function choose(id: string): Promise<void> {
if (id === homeOrg.value) return;
failed.value = "";
try {
await orgStore.actInOrg(id);
} catch (cause) {
failed.value = describeError(cause, errors.common.unknown);
}
}
const hover = useHoverOpen();
const name = computed(() => orgStore.orgs.find((o) => o.id === orgStore.homeOrg)?.name ?? (failed.value ? errors.components.org.unavailable : "Loading…"));
</script>
<template>
<DropdownMenu v-if="choices.length > 1" :open="hover.open.value" :modal="false" @update:open="hover.update">
<DropdownMenuTrigger as-child>
<Button variant="ghost" size="sm" class="gap-1 px-2" :aria-label="`Organisation: ${name}`" :title="failed || undefined" @pointerenter="hover.enterTrigger" @pointerleave="hover.leaveTrigger">
<span class="max-w-40 truncate max-sm:max-w-20">{{ name }}</span>
<ChevronDown class="size-4" aria-hidden="true" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" class="min-w-48" @pointerenter="hover.enter" @pointerleave="hover.leave">
<DropdownMenuItem v-for="o in choices" :key="o.id" @select="choose(o.id)">
{{ o.name }}
<Check v-if="o.id === homeOrg" class="ml-auto" aria-label="Current" />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<span v-else class="max-w-40 truncate px-2 text-label font-medium max-sm:max-w-20" :title="failed || undefined" :aria-label="`Organisation: ${name}`">{{ name }}</span>
<span class="max-w-40 truncate px-2 text-label font-medium max-sm:max-w-20" :title="failed || undefined" :aria-label="`Organisation: ${name}`">{{ name }}</span>
</template>
-17
View File
@@ -1,10 +1,8 @@
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { computed } from "vue";
import { useRoute } from "vue-router";
import { ChevronDown } from "@lucide/vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@@ -14,30 +12,17 @@ import {
} from "@/components/ui/dropdown-menu";
import { activeNavPath, navTree, type NavEntry } from "@/lib/nav";
import { navIcons } from "@/lib/nav-icons";
import { attentionStatusIds } from "@/lib/task-meta";
import { useLiveResource } from "@/stores/session";
import { useTasksStore } from "@/stores/tasks";
import { useHoverOpen } from "./hover-open";
const props = defineProps<{ hidden: string[]; link?: string }>();
const route = useRoute();
const store = useTasksStore();
const { summary } = storeToRefs(store);
// The attention count has to stay current on every page, not only the dashboard.
useLiveResource("tasks", () => void store.load(), 5000);
const links = computed(() =>
navTree(props.hidden).flatMap((node): NavEntry[] => (node.kind === "link" ? [node.entry] : node.items)),
);
// Detail routes carry the primary destination they belong to in meta.navPath.
const activePath = computed(() => (typeof route.meta.navPath === "string" ? route.meta.navPath : activeNavPath(route.path)));
const current = computed(() => links.value.find((entry) => entry.path === activePath.value));
const attention = computed(() => {
const counts = summary.value?.statuses ?? {};
let total = 0;
for (const id of attentionStatusIds()) total += counts[id] ?? 0;
return total;
});
const hover = useHoverOpen();
</script>
@@ -55,7 +40,6 @@ const hover = useHoverOpen();
<DropdownMenuTrigger v-else as-child>
<Button variant="ghost" size="sm" class="gap-1 px-2" aria-label="Sections" @pointerenter="hover.enterTrigger" @pointerleave="hover.leaveTrigger">
<span>{{ current?.label ?? route.meta.label ?? "Sections" }}</span>
<Badge v-if="activePath !== '/' && attention" variant="warn" class="tabular-nums" :aria-label="`${attention} need attention`">{{ attention }}</Badge>
<ChevronDown class="size-4" aria-hidden="true" />
</Button>
</DropdownMenuTrigger>
@@ -64,7 +48,6 @@ const hover = useHoverOpen();
<RouterLink :to="entry.path" :aria-current="entry.path === activePath ? 'page' : undefined">
<component :is="navIcons[entry.path]" v-if="navIcons[entry.path]" aria-hidden="true" />
{{ entry.label }}
<Badge v-if="entry.path === '/' && attention" variant="warn" class="ml-auto tabular-nums" :aria-label="`${attention} need attention`">{{ attention }}</Badge>
</RouterLink>
</DropdownMenuItem>
</DropdownMenuContent>
-5
View File
@@ -1,5 +0,0 @@
export const alerts = {
load: "Alerts could not be loaded.",
dismiss: (detail: string) => `Dismiss failed: ${detail}`,
webhookDelivery: "Webhook delivery failed.",
} as const;
-13
View File
@@ -1,13 +0,0 @@
export const audit = {
unavailable: "Audit is unavailable.",
load: "Audit could not be loaded.",
refresh: "Audit could not refresh.",
revert: {
resourceLoad: "That resource could not be loaded.",
unavailable: "That earlier version is no longer available.",
},
retention: {
unavailable: "Retention settings are unavailable.",
save: "Retention could not be saved.",
},
} as const;
-19
View File
@@ -1,19 +0,0 @@
// Failure copy for the bindings folder: the list, its editor and dispatch links.
export const bindings = {
page: {
actionNotApplied: "That did not take effect",
},
editor: {
saveFailed: "Could not save",
},
table: {
notConfigured: "Bindings are not configured",
},
dispatchLinks: {
unavailable: "Dispatches unavailable.",
noTask: "claimed, no task recorded",
noReason: "no reason recorded",
accessDenied: "access policy refused to start",
workflowDisabled: "is disabled",
},
} as const;
-8
View File
@@ -2,17 +2,13 @@
// dot-walk it, e.g. errors.chat.turn.stop, so the copy is
// changed here and nowhere else.
import { accounts } from "./accounts.ts";
import { alerts } from "./alerts.ts";
import { app } from "./app.ts";
import { audit } from "./audit.ts";
import { base } from "./base.ts";
import { bindings } from "./bindings.ts";
import { channels } from "./channels.ts";
import { chat } from "./chat.ts";
import { common } from "./common.ts";
import { components } from "./components.ts";
import { dashboard } from "./dashboard.ts";
import { logs } from "./logs.ts";
import { mappings } from "./mappings.ts";
import { org } from "./org.ts";
import { settings } from "./settings.ts";
@@ -22,17 +18,13 @@ import { workflows } from "./workflows.ts";
export const errors = {
accounts,
alerts,
app,
audit,
base,
bindings,
channels,
chat,
common,
components,
dashboard,
logs,
mappings,
org,
settings,
-10
View File
@@ -1,10 +0,0 @@
// Failure and empty-state copy for the log page.
export const logs = {
read: {
unreadable: "Cannot read logs",
},
empty: {
streamUnavailable: "Log stream unavailable",
streamUnavailableDetail: "This process is not delivering live daemon logs.",
},
} as const;
-3
View File
@@ -1,7 +1,4 @@
export const org = {
identities: {
unavailable: "Unavailable identity",
},
rename: {
conflict: (name: string) => `The name is now “${name}”. Save again to replace it.`,
},
-33
View File
@@ -1,33 +0,0 @@
<script lang="ts">
/** One thing a curator did, and why it did it. */
export interface CuratorActionEntry {
type?: string;
at?: string | number;
detail?: string;
reason?: string;
}
</script>
<script setup lang="ts">
import { Timestamp } from "@/components/ui/timestamp";
const props = defineProps<{ action: CuratorActionEntry }>();
</script>
<template>
<li class="rounded-sm bg-muted px-3 py-2">
<div class="flex items-baseline justify-between gap-2">
<span class="text-label font-medium">{{
props.action.type || "action"
}}</span>
<span class="text-caption text-fg-subtle"><Timestamp :at="props.action.at" /></span>
</div>
<p v-if="props.action.detail" class="mt-1 text-label text-fg-muted">
{{ props.action.detail }}
</p>
<!-- The reason is the point of this list: an action without one is not
reviewable. -->
<p v-if="props.action.reason" class="mt-1 text-caption text-fg-subtle">Why: {{ props.action.reason }}
</p>
</li>
</template>
-73
View File
@@ -1,73 +0,0 @@
<script lang="ts">
import type { StatusKind } from "@/lib/status";
import type { CuratorActionEntry } from "./CuratorAction.vue";
/** A registered curator, its point-in-time health, and its recent activity. */
export interface Curator {
name: string;
health?: { status?: string; message?: string };
last_run_at?: string | number;
last_run_actions?: number;
recent_actions?: CuratorActionEntry[];
}
</script>
<script setup lang="ts">
import { Badge } from "@/components/ui/badge";
import { Section } from "@/components/ui/section";
import { Timestamp } from "@/components/ui/timestamp";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import CuratorAction from "./CuratorAction.vue";
const props = defineProps<{ curator: Curator }>();
function healthKind(status: string | undefined): StatusKind {
switch (status) {
case "healthy":
return "ok";
case "degraded":
return "warn";
case "unhealthy":
return "danger";
default:
return "idle";
}
}
</script>
<template>
<Section :title="props.curator.name" class="mb-0">
<template #action>
<Badge :variant="healthKind(props.curator.health?.status)">
{{ props.curator.health?.status || "unknown" }}
</Badge>
</template>
<p class="mb-3 text-caption text-fg-subtle">
<template v-if="props.curator.last_run_at">
Last ran <Timestamp :at="props.curator.last_run_at" /> · {{ props.curator.last_run_actions }} action{{ props.curator.last_run_actions === 1 ? "" : "s" }}
</template>
<template v-else>Has not run yet</template>
</p>
<p
v-if="props.curator.health?.message"
class="mb-3 text-label text-fg-muted"
>
{{ props.curator.health.message }}
</p>
<ul
v-if="props.curator.recent_actions?.length"
class="flex flex-col gap-2"
>
<CuratorAction
v-for="(a, i) in props.curator.recent_actions"
:key="i"
:action="a"
/>
</ul>
<Empty v-else>
<EmptyHeader>
<EmptyTitle>No activity</EmptyTitle>
</EmptyHeader>
</Empty>
</Section>
</template>
-64
View File
@@ -1,64 +0,0 @@
<script setup lang="ts">
import { computed } from "vue";
import { TableCell, TableRow } from "@/components/ui/table";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Timestamp } from "@/components/ui/timestamp";
import { useOrgStore } from "@/stores/org";
import { activityDetail } from "./activity-detail";
import { describeTimelineEvent } from "@/tasks/timeline-event";
import { useTasksStore, type ActivityEvent } from "@/stores/tasks";
const identities = useOrgStore();
identities.watchIdentities();
/**
* One row of the live activity table. A row whose event resolves to a task is
* a link to it, and has to behave like one for a keyboard: Enter and Space both
* open it, which is why it is focusable and carries role="link".
*/
const props = defineProps<{ event: ActivityEvent }>();
const emit = defineEmits<{ open: [taskID: number] }>();
const tasks = useTasksStore();
const taskID = computed(() => tasks.taskIDFor(props.event));
// The detail is cut to one line by activityDetail and clamped again in the
// cell so a long unbroken token (a path, a URL, a hash) cannot widen the column
// past the table.
const detail = computed(() => activityDetail(props.event, identities.identityName));
function open() {
if (taskID.value > 0) emit("open", taskID.value);
}
</script>
<template>
<TableRow
:class="taskID > 0 ? 'cursor-pointer' : ''"
@click="open"
>
<TableCell class="font-medium">
<button
v-if="taskID > 0"
type="button"
class="rounded-sm text-left focus-visible:outline-2 focus-visible:outline-ring"
aria-label="Open task details"
@click.stop="open"
>{{ describeTimelineEvent({ ...props.event, at: undefined, detail: undefined }).title }}</button>
<template v-else>{{ describeTimelineEvent({ ...props.event, at: undefined, detail: undefined }).title }}</template>
</TableCell>
<TableCell class="font-mono">{{
taskID > 0 ? `#${taskID}` : "–"
}}</TableCell>
<TableCell class="w-[55%] max-w-0">
<Tooltip>
<TooltipTrigger as-child>
<span tabindex="0" class="block truncate">{{ detail.text }}</span>
</TooltipTrigger>
<TooltipContent v-if="detail.truncated">{{ detail.full }}</TooltipContent>
</Tooltip>
</TableCell>
<TableCell><Timestamp :at="event.at" /></TableCell>
</TableRow>
</template>
-104
View File
@@ -1,104 +0,0 @@
<script setup lang="ts">
import { Alert, AlertDescription } from "@/components/ui/alert";
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import { errors } from "@/copy/errors";
import { api, describeError } from "@/lib/api";
import { useOrgStore } from "@/stores/org";
import NewTaskDialog from "@/tasks/NewTaskDialog.vue";
import { firstLine } from "@/tasks/first-line";
import type { WorkflowDefinition } from "@/workflows/workflow-rows";
import { declaredInputs } from "@/tasks/work-request";
/**
* Start a task from a prompt. A workflow that needs more than the prompt (a
* repository, a required input) opens the full form with the prompt carried
* over, rather than being refused by the server.
*/
const router = useRouter();
const prompt = ref("");
const workflow = ref("");
const definitions = ref<WorkflowDefinition[]>([]);
const loaded = ref(false);
const loadError = ref("");
const error = ref("");
const submitting = ref(false);
const formOpen = ref(false);
onMounted(async () => {
try {
const list = await api.workflows<{ definitions?: WorkflowDefinition[] }>();
definitions.value = (list?.definitions ?? []).filter((d) => d.enabled);
workflow.value ||= definitions.value[0]?.id ?? "";
} catch (err) {
loadError.value = describeError(err, errors.common.unknown);
} finally {
loaded.value = true;
}
});
const org = useOrgStore();
org.watchIdentities();
const actor = computed(() => org.identities.find((i) => i.kind !== "system" && i.lifecycle === "active"));
const selected = computed(() => definitions.value.find((d) => d.id === workflow.value));
const needsForm = computed(() => {
const mode = selected.value?.repository ?? "required";
return (mode !== "none" && mode !== "optional") || declaredInputs(selected.value).some((i) => i.required) || !actor.value;
});
async function run() {
if (!prompt.value.trim() || !workflow.value || submitting.value) return;
if (needsForm.value) {
formOpen.value = true;
return;
}
submitting.value = true;
error.value = "";
try {
const result = await api.workRequest<{ task_id: number }>({
identity: actor.value!.id,
repository: "",
workflow: workflow.value,
title: firstLine(prompt.value),
instructions: prompt.value,
inputs: {},
});
void router.push(`/tasks/${result.task_id}`);
} catch (err) {
error.value = describeError(err, errors.common.unknown);
} finally {
submitting.value = false;
}
}
</script>
<template>
<div>
<form class="grid gap-1.5" @submit.prevent="run">
<div class="flex gap-2 @max-xl:flex-wrap">
<Input v-model="prompt" class="min-w-0 flex-1" placeholder="Describe what Archie should do" aria-label="Task" />
<Select v-model="workflow" :disabled="!definitions.length">
<SelectTrigger class="w-56 @max-xl:flex-1" aria-label="Workflow"><span class="flex min-w-0 items-center gap-1.5"><span class="text-fg-muted">Workflow</span><SelectValue /></span></SelectTrigger>
<SelectContent position="popper">
<SelectGroup>
<SelectItem v-for="d in definitions" :key="d.id" :value="d.id">{{ d.name || d.id }}</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
<Button type="submit" :disabled="!prompt.trim() || !workflow || submitting"><Spinner v-if="submitting" data-icon="inline-start" />Run</Button>
</div>
<Alert v-if="loadError || error" variant="destructive"><AlertDescription>{{ loadError || error }}</AlertDescription></Alert>
<p v-else-if="!loaded" class="text-caption text-fg-subtle" role="status">Loading workflows…</p>
<p v-else-if="!definitions.length" class="text-caption text-fg-subtle">
No enabled workflows. <RouterLink to="/workflows" class="underline">Enable one</RouterLink>
</p>
</form>
<NewTaskDialog v-model:open="formOpen" :workflow="workflow" :instructions="prompt" />
</div>
</template>
-52
View File
@@ -1,52 +0,0 @@
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { Check, Circle } from "@lucide/vue";
import { computed, ref, watch } from "vue";
import { Section } from "@/components/ui/section";
import { setupPanelState, type Setup, type SetupPanelState } from "./setup-preference";
import { useTasksStore } from "@/stores/tasks";
const props = defineProps<{ setup?: Setup | null }>();
const { setup: taskSetup } = storeToRefs(useTasksStore());
const activeSetup = computed(() => (props.setup?.steps?.length ? props.setup : taskSetup.value));
/**
* The setup checklist, rendered only while there is setup work left.
*
* A fully configured daemon renders nothing: a completion card would celebrate
* the absence of a problem and hold a grid cell. Setup regressing to
* incomplete brings the checklist back on its own.
*/
const panel = ref<SetupPanelState>(setupPanelState(activeSetup.value));
watch(activeSetup, () => {
panel.value = setupPanelState(activeSetup.value);
});
const steps = computed(() => activeSetup.value?.steps ?? []);
const pct = computed(() => {
const total = steps.value.length;
if (!total) return 0;
return Math.round(((total - panel.value.remaining.length) / total) * 100);
});
</script>
<template>
<Section v-if="panel.kind === 'incomplete'" title="Setup" class="mb-0">
<template #action>
<span class="text-label font-semibold text-link tabular-nums">{{ pct }}%</span>
</template>
<ul class="grid gap-2 text-label">
<li v-for="(step, i) in steps" :key="i" class="flex items-center gap-2">
<Check v-if="step.done" class="size-3.5 shrink-0 text-ok" aria-label="Done" />
<Circle v-else class="size-3.5 shrink-0 text-fg-subtle" aria-label="To do" />
<span class="flex min-w-0 flex-col">
<RouterLink v-if="!step.done && step.path" :to="step.path" class="font-medium hover:underline">{{ step.title }}</RouterLink>
<span v-else :class="step.done ? 'text-fg-muted' : 'font-medium'">{{ step.title }}</span>
<span v-if="step.detail" class="text-caption text-fg-subtle">{{ step.detail }}</span>
</span>
</li>
</ul>
</Section>
</template>
-60
View File
@@ -1,60 +0,0 @@
// Live activity's detail column.
//
// The daemon puts whatever a stage produced into an event's detail, so the
// column holds anything from "session-memory" to a few thousand characters of
// agent transcript. Printed raw, one row would dwarf the table.
//
// The rule is one line in the cell, the whole payload still available. The cut
// happens here rather than in CSS because the row also needs to know whether
// there is more to show.
// Long enough for a useful parked reason, short enough that every row is the
// same height at the widths the table is used at.
const CELL_LIMIT = 160;
/** An activity event, as far as this column reads it. Deliberately narrower
* than the event the dashboard holds: this is the whole of what the cell
* renders, so a caller can pass anything carrying either field. */
export interface ActivityDetailInput {
detail?: unknown;
message?: unknown;
actor_id?: string;
principal_id?: string;
}
/** The cell's content: the rendered line, the payload, and whether they differ. */
export interface ActivityDetail {
text: string;
full: string;
truncated: boolean;
}
/**
* activityDetail returns `{ text, full, truncated }` for one event:
* `text` is the single line the cell renders, `full` the untouched payload,
* and `truncated` whether the two differ.
*/
export function activityDetail(
event: ActivityDetailInput | undefined,
identityName?: (id: string) => string,
): ActivityDetail {
let full = String(event?.detail || event?.message || "");
if (identityName) {
for (const id of [event?.actor_id, event?.principal_id])
if (id) full = full.replaceAll(id, identityName(id));
}
if (!full) return { text: "", full: "", truncated: false };
// The first line that says something: agent output often opens with blanks.
const firstLine =
full
.split("\n")
.map((line) => line.trim())
.find(Boolean) || "";
const clipped =
firstLine.length > CELL_LIMIT
? `${firstLine.slice(0, CELL_LIMIT).trimEnd()}…`
: firstLine;
return { text: clipped, full, truncated: clipped !== full };
}
-65
View File
@@ -1,65 +0,0 @@
/**
* The live activity feed's filter.
*
* Every event the dashboard receives belongs either to a task run or to the
* daemon's own background work, and the two are read for different reasons:
* "what is my work doing" against "what is the daemon doing". A task event is
* one that resolves to a task -- the same test the table's rows already use to
* link an event to a task -- so the filter can never disagree with the links
* inside the rows it is filtering.
*/
export type ActivityFilter = "all" | "tasks" | "system";
/** An event as far as the filter reads it: the task it belongs to, if any. */
export interface ActivityFilterInput {
task_id?: number | string | null;
}
/** The three views, in the order the header renders them. */
export const ACTIVITY_FILTERS: { value: ActivityFilter; label: string }[] = [
{ value: "tasks", label: "Tasks" },
{ value: "system", label: "System" },
{ value: "all", label: "All" },
];
/** belongsToTask is the same test the rows use to point an event at a task. */
function belongsToTask(
event: ActivityFilterInput | null | undefined,
): boolean {
return (Number(event?.task_id) || 0) > 0;
}
/** matchesActivityFilter decides one event, so a group row can be judged by the
* events it stands for. */
export function matchesActivityFilter(
event: ActivityFilterInput | null | undefined,
filter: ActivityFilter,
): boolean {
if (filter === "tasks") return belongsToTask(event);
if (filter === "system") return !belongsToTask(event);
return true;
}
/** filterActivity keeps the events a view is about, in arrival order. The two
* narrow views partition the feed: nothing shows in both, nothing in neither. */
export function filterActivity<T extends ActivityFilterInput>(
events: readonly T[],
filter: ActivityFilter,
): T[] {
return events.filter((event) => matchesActivityFilter(event, filter));
}
/**
* activityEmptyTitle words the empty state. A feed with nothing in it and a
* feed this view emptied are different facts, and a blank title means there are
* rows to show, so the caller renders no empty state at all.
*/
export function activityEmptyTitle(
visible: number,
filter: ActivityFilter,
): string {
if (visible > 0) return "";
if (filter === "all") return "No activity yet";
return filter === "tasks" ? "Archie is waiting for a task" : "No system events yet";
}
-67
View File
@@ -1,67 +0,0 @@
import type { ActivityEvent } from "../stores/tasks.ts";
import { activityDetail } from "./activity-detail.ts";
/**
* The live activity feed's grouping projection.
*
* The daemon emits high-frequency background telemetry that arrives as dozens
* of same-shape rows an hour, often as an interleave of kinds (a curator
* cycle emits curator_run, session-memory and curator_action events that all
* carry the same payload). Printed raw, the table stops being scannable and
* real milestones drown.
*
* The rule: a *run of consecutive* events sharing one task and one rendered
* detail collapses into a single group row. Kind is deliberately not part of
* the key: an interleave of kinds over one payload is one cycle of noise,
* not three events, so anything else stays on its own line, and a milestone
* is never merged with an event carrying different information. The grouping
* is consecutive, not global, so interleaved events keep their order and
* nothing is reordered under the operator.
*
* This is a pure view projection over the store's raw stream: the store keeps
* every event, and this module decides only how the feed presents them.
*/
/** One displayed row: either a single event (count 1) or a collapsed run. */
export interface ActivityGroup {
/** Stable identity of the run: the grouping key of its first event. */
key: string;
/** The resolved label the row shows, matching the Event column's fallback. */
label: string;
/** The task the group's events resolve to, or 0 for none. */
taskID: number;
/** How many events the group carries; 1 means an uncollapsed row. */
count: number;
/** The newest event of the run -- what the row shows while collapsed. */
representative: ActivityEvent;
/** Every event in the run, newest first. */
events: ActivityEvent[];
}
function groupKey(detail: string, taskID: number | undefined): string {
return `${detail}:${taskID ?? 0}`;
}
export function groupActivity(events: ActivityEvent[]): ActivityGroup[] {
const groups: ActivityGroup[] = [];
for (const event of events) {
const label = event.kind || event.type || "event";
const taskID = Number(event.task_id) || 0;
const key = groupKey(activityDetail(event).text, taskID);
const last = groups[groups.length - 1];
if (last && last.key === key) {
last.count += 1;
last.events.push(event);
continue;
}
groups.push({
key,
label,
taskID,
count: 1,
representative: event,
events: [event],
});
}
return groups;
}
-32
View File
@@ -1,32 +0,0 @@
/** One setup step as the daemon reports it. */
interface SetupStep {
title: string;
detail?: string;
done: boolean;
/** The page that fixes an unfinished step, so the checklist is a set of
* links rather than a description of work with nowhere to go. */
path?: string;
}
export interface Setup {
steps: SetupStep[];
}
export interface SetupPanelState {
/** omit: nothing to show, either no setup data or setup fully done. */
kind: "omit" | "incomplete";
remaining: SetupStep[];
}
// setupPanelState distinguishes the only two states worth rendering: there is
// setup work left (the checklist), or there is not (nothing: a configured
// daemon is the absence of a problem, not a card announcing it).
export function setupPanelState(
setup: Setup | null | undefined,
): SetupPanelState {
const remaining = (setup?.steps ?? []).filter((step) => !step.done);
if (!setup?.steps?.length || !remaining.length) {
return { kind: "omit", remaining: [] };
}
return { kind: "incomplete", remaining };
}
-8
View File
@@ -1,8 +0,0 @@
import { onMounted } from "vue";
import { useTasksStore } from "@/stores/tasks";
/** Fetches the board when the page opens; the shell keeps it live. */
export function useDashboard(): void {
onMounted(useTasksStore().load);
}
+17 -138
View File
@@ -371,7 +371,6 @@ export const api = {
deletePasskey: (id:string) => request<void>(`/api/account/passkeys/${encodeURIComponent(id)}`,{method:"DELETE",body:{},parse:false}),
beginPasskey: <T = unknown>(registration:boolean) => request<T>(registration?"/api/account/passkeys/begin":"/api/auth/passkey/begin",{method:"POST",body:{}}),
finishPasskey: (registration:boolean,credential:unknown,name:string) => request(registration?"/api/account/passkeys/finish":"/api/auth/passkey/finish",{method:"POST",body:{credential,name}}),
checkSecret: (ref: { engine: string; key: string }) => request<{ resolved: boolean; process: string }>("/api/secret-references/check", { method: "POST", body: ref }),
notes: () => request<MemoryNotes>("/api/memory/notes"),
rememberNote: (text: string) => request<MemoryNote>("/api/memory/notes", { method: "POST", body: { text } }),
correctNote: (id: string, text: string) =>
@@ -401,21 +400,7 @@ export const api = {
request<{ version: number }>("/api/access/policies", { method: "PUT", body: policy }),
deletePolicy: (policy: unknown) =>
request<void>("/api/access/policies", { method: "DELETE", body: policy, parse: false }),
schedules: <T = unknown>() => request<T>("/api/schedules"),
// scheduleSave creates or replaces the schedule with this id.
scheduleSave: <T = unknown>(id: string, schedule: unknown) =>
request<T>(`/api/schedules/${encodeURIComponent(id)}`, { method: "PUT", body: schedule }),
scheduleDelete: (id: string) =>
request<void>(`/api/schedules/${encodeURIComponent(id)}`, { method: "DELETE", parse: false }),
scheduleRunNow: <T = unknown>(id: string) =>
request<T>(`/api/schedules/${encodeURIComponent(id)}/runs`, { method: "POST", body: {} }),
scheduleRuns: <T = unknown>(id: string) =>
request<T>(`/api/schedules/${encodeURIComponent(id)}/runs`),
orgs: <T = unknown>() => request<T>("/api/orgs"),
// orgSelect sets the org the caller's tasks, workflows and settings act in;
// the server refuses one the caller is not a member of.
orgSelect: (id: string) =>
request<void>("/api/orgs/current", { method: "PUT", body: { id }, parse: false }),
// orgCreate makes an org with its default workspace and first owner; only
// an instance admin may.
orgCreate: <T = unknown>(org: { id: string; name: string; owner_identity: string }) =>
@@ -447,7 +432,6 @@ export const api = {
// orgHistory lists the org's appended name changes, newest first.
orgHistory: <T = unknown>(id: string) =>
request<T>(`/api/orgs/${encodeURIComponent(id)}/history`),
orgAgents: <T = unknown>(id: string) => request<T>(`/api/orgs/${encodeURIComponent(id)}/agents`),
orgMembers: <T = unknown>(id: string) =>
request<T>(`/api/orgs/${encodeURIComponent(id)}/members`),
orgMemberCandidates: <T = unknown>(id: string) =>
@@ -486,14 +470,6 @@ export const api = {
`/api/orgs/${encodeURIComponent(id)}/members/${encodeURIComponent(identity)}/reactivate`,
{ method: "POST", parse: false },
),
assignOrgAgent: <T = unknown>(id: string, identity: string) =>
request<T>(
`/api/orgs/${encodeURIComponent(id)}/agents/${encodeURIComponent(identity)}`,
{ method: "PUT" },
),
alerts: <T = unknown>() => request<T>("/api/alerts"),
dismissAlert: (id: number) =>
request<void>(`/api/alerts/${id}/dismiss`, { method: "POST", parse: false }),
channelLinks: () => request<ChannelLinks>("/api/account/channels"),
/** Issues a single-use code and returns the URL that sends it to the channel. */
beginChannelLink: (connector: string) =>
@@ -503,95 +479,8 @@ export const api = {
method: "DELETE",
parse: false,
}),
identities: <T = unknown>() => request<T>("/api/identities"),
identityCreate: <T = unknown>(identity: { display_name: string; kind: string }) =>
request<T>("/api/identities", { method: "POST", body: identity }),
// identityCommand runs one lifecycle command (rename, suspend, reactivate,
// retire) against the version the caller last read.
identityCommand: <T = unknown>(id: string, command: string, body: { expected_version: number; display_name: string }) =>
request<T>(`/api/identities/${encodeURIComponent(id)}/${encodeURIComponent(command)}`, { method: "POST", body }),
summary: <T = unknown>() => request<T>("/api/summary"),
// usage reads the org's model usage for the last days. The server derives
// the org from the caller and clamps days to 1..365.
usage: <T = unknown>(days = 30) => request<T>("/api/usage" + qs({ days })),
tasks: <T = unknown>() => request<T>("/api/tasks"),
// taskPage reads one page of the board; next is the cursor for the page
// after it, or null when this page was the last.
taskPage: async <T = unknown>(params: QueryParams) => {
const res = await send("/api/tasks" + qs(params), {
headers: { Accept: "application/json" },
signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
});
return {
tasks: (await res.json()) as T[],
next: res.headers.get("X-Next-Cursor"),
};
},
taskMeta: <T = unknown>() => request<T>("/api/task-meta"),
task: <T = unknown>(id: string) =>
request<T>(`/api/tasks/${encodeURIComponent(id)}`),
taskAttempts: <T = unknown>(id: string) =>
request<T>(`/api/tasks/${encodeURIComponent(id)}/attempts`),
taskChanges: <T = unknown>(id: string, params?: QueryParams) =>
request<T>(`/api/tasks/${encodeURIComponent(id)}/changes` + qs(params)),
taskDebug: <T = unknown>(id: string, params?: QueryParams) =>
request<T>(`/api/tasks/${encodeURIComponent(id)}/debug` + qs(params)),
taskTranscript: <T = unknown>(id: string, params?: QueryParams) =>
request<T>(`/api/tasks/${encodeURIComponent(id)}/transcript` + qs(params)),
// taskAction posts an operator action. A review-gate answer may carry a
// payload: the instructions a rereview requires, and the finding keys an
// approve posts (an absent selection means every offered finding). A retry
// carries the worktree mode the operator chose, and may name the step it
// resumes from. Every other action sends
// none.
taskAction: <T = unknown>(
id: string,
action: string,
payload?: {
instructions?: string;
findings?: string[];
retry_mode?: string;
resume_from?: string;
current_definition?: boolean;
},
) =>
request<T>(`/api/tasks/${encodeURIComponent(id)}/action`, {
method: "POST",
body: { action, ...payload },
}),
setup: <T = unknown>() => request<T>("/api/setup"),
capabilities: <T = unknown>() => request<T>("/api/capabilities"),
workflows: <T = unknown>() => request<T>("/api/workflows"),
checkRepository: <T = unknown>(input: { owner: string; repository: string; identity_id: string }) => request<T>("/api/control-plane/resources/repository-policies/check", { method: "POST", body: input, timeoutMs: 35000 }),
repositories: <T = unknown>() => request<T>("/api/repositories"),
workRequest: <T = unknown>(workRequest: Payload) =>
request<T>("/api/work-requests", { method: "POST", body: workRequest }),
skills: <T = unknown>() => request<T>("/api/skills"),
channels: <T = unknown>() => request<T>("/api/channels"),
curators: <T = unknown>() => request<T>("/api/curators"),
channelReload: <T = unknown>(id: string) =>
request<T>(`/api/channels/${encodeURIComponent(id)}/reload`, {
method: "POST",
body: {},
}),
config: <T = unknown>() => request<T>("/api/config"),
// The audit feed is filtered and paginated on the server; export is a
// browser navigation, so its URL is built here beside the request.
audit: <T = unknown>(params: QueryParams = {}) => request<T>("/api/audit" + qs(params)),
auditExportURL: (format: "csv" | "json", params: QueryParams = {}) =>
"/api/audit/export" + qs({ ...params, format }),
logs: <T = unknown>(params?: QueryParams) =>
request<T>("/api/logs" + qs(params)),
taskLogs: <T = unknown>(id: string, params?: QueryParams) =>
request<T>(`/api/tasks/${encodeURIComponent(id)}/logs` + qs(params)),
// A download is a navigation, not a fetch: the browser must own the
// Content-Disposition filename and stream the body to disk rather than hold
// a whole log in memory. The URL builder is the client-side contract, and
// log-row keeps it beside the panel that uses it.
taskLogDownloadURL: (id: string, attempt?: number | null) =>
`/api/tasks/${encodeURIComponent(id)}/logs/download` +
(attempt == null ? "" : `?attempt=${attempt}`),
version: <T = unknown>() => request<T>("/api/version"),
capabilities: <T = unknown>() => request<T>("/api/capabilities"),
captures: <T = unknown>(limit?: number) =>
request<T>("/api/captures" + qs({ limit })),
eventTypes: <T = unknown>() => request<T>("/api/event-types"),
@@ -626,32 +515,6 @@ export const api = {
method: "POST",
body: { capture_id: captureId, fields },
}),
bindings: <T = unknown>(workspace?: string) =>
request<T>("/api/bindings" + qs({ workspace })),
dispatches: <T = unknown>(kind: "bindings" | "captures" | "tasks", id: string) =>
request<T>(`/api/${kind}/${encodeURIComponent(id)}/dispatches`),
bindingCreate: <T = unknown>(binding: Payload) =>
request<T>("/api/bindings", { method: "POST", body: binding }),
bindingUpdate: <T = unknown>(id: string, binding: Payload) =>
request<T>(`/api/bindings/${encodeURIComponent(id)}`, {
method: "PATCH",
body: binding,
}),
bindingDelete: (id: string) =>
request<void>(`/api/bindings/${encodeURIComponent(id)}`, {
method: "DELETE",
parse: false,
}),
bindingApprove: <T = unknown>(id: string) =>
request<T>(`/api/bindings/${encodeURIComponent(id)}/approve`, {
method: "POST",
}),
// bindingPause stops an armed binding; bindingResume returns it to pending
// approval.
bindingPause: <T = unknown>(id: string) =>
request<T>(`/api/bindings/${encodeURIComponent(id)}/pause`, { method: "POST" }),
bindingResume: <T = unknown>(id: string) =>
request<T>(`/api/bindings/${encodeURIComponent(id)}/resume`, { method: "POST" }),
sourceSigning: (id: string, signed: boolean) =>
request<EventSource_>(`/api/sources/${encodeURIComponent(id)}/signing`, {
method: "POST",
@@ -930,16 +793,32 @@ export interface ApprovalConfirmation {
options: { publicKey: Record<string, unknown> };
}
/** One action an approval request covers, in the order the request covers
* them: the first action, or the whole sequence one request asks about. */
export interface ApprovalStep {
decision_id: string;
/** The connector and action, as "connector action". */
action: string;
/** "kind:id". */
target: string;
level: string;
}
export interface Approval {
id: string;
run_id: string;
step: number;
kind: string;
/** The connector and action of the request's first action. */
action: string;
/** The first action's "kind:id" target. */
target: string;
level: string;
summary: string;
state: string;
/** The actions the request covers, in the order they run. An autonomy
* proposal covers none. */
steps?: ApprovalStep[];
requested_at: string;
deadline?: string;
answered_at?: string;
+5 -98
View File
@@ -1,8 +1,9 @@
// The freeze-dried /api/task-meta catalog the dashboard renders before the
// served one arrives, or when archied is unreachable; task-meta.ts replaces it
// with the live catalog.
// The lifecycle statuses the dashboard draws, and the severity and "needs you"
// grouping each one carries. The single binary serves no catalogue for these,
// so this snapshot is the vocabulary; a status it doesn't list renders as its
// own id with an idle pill.
/** A lifecycle status as the server describes it. */
/** A lifecycle status as the dashboard draws it. */
export interface StatusMeta {
id: string;
label: string;
@@ -10,29 +11,6 @@ export interface StatusMeta {
needs_attention?: boolean;
}
/** An operator control as the server describes it. */
export interface ActionMeta {
id: string;
label: string;
kind: string;
confirm?: string;
}
/** A changes_captured file status as the server describes it. */
export interface ChangeStatusMeta {
id: string;
label: string;
}
/** A retry worktree mode as the server describes it. */
export interface RetryModeMeta {
id: string;
label: string;
description: string;
default?: boolean;
requires_branch?: boolean;
}
export const DEFAULT_STATUSES: StatusMeta[] = [
{ id: "queued", label: "Queued", kind: "idle" },
{ id: "running", label: "Running", kind: "info" },
@@ -50,74 +28,3 @@ export const DEFAULT_STATUSES: StatusMeta[] = [
{ id: "rejected", label: "Rejected", kind: "danger" },
{ id: "closed_wont_do", label: "Won't do", kind: "idle" },
];
export const DEFAULT_ACTIONS: ActionMeta[] = [
{
id: "cancel",
label: "Cancel",
kind: "quiet",
confirm: `Cancel "{title}"? Closes the issue.`,
},
{
id: "stop",
label: "Stop",
kind: "primary",
confirm: `Stop "{title}"? Work stays parked.`,
},
{ id: "approve", label: "Approve", kind: "primary" },
{ id: "rereview", label: "Re-review", kind: "quiet" },
{
id: "reject",
label: "Reject",
kind: "quiet",
confirm: `Reject "{title}"? Closes the issue.`,
},
{ id: "retry", label: "Retry", kind: "primary" },
{
id: "abandon",
label: "Abandon",
kind: "quiet",
confirm: `Abandon "{title}"? The issue stays open.`,
},
{
id: "archive",
label: "Archive",
kind: "quiet",
confirm: `Archive the local record for "{title}"?`,
},
{
id: "merge",
label: "Merge",
kind: "primary",
confirm: `Merge the pull request for "{title}"?`,
},
{ id: "open_pr", label: "Open PR", kind: "link" },
{ id: "open_issue", label: "Open issue", kind: "link" },
];
export const DEFAULT_CHANGE_STATUSES: ChangeStatusMeta[] = [
{ id: "added", label: "Added" },
{ id: "modified", label: "Modified" },
{ id: "deleted", label: "Deleted" },
{ id: "renamed", label: "Renamed" },
{ id: "typechange", label: "Type changed" },
];
export const DEFAULT_RETRY_MODES: RetryModeMeta[] = [
{
id: "refresh_onto_base",
label: "Refresh onto base",
description:
"Retry from the current base; discards pushed commits.",
default: true,
},
{
id: "continue_pushed_work",
label: "Continue pushed work",
description:
"Resume the pushed branch.",
requires_branch: true,
},
];
export const DEFAULT_CONFIG_SCHEMA = "archie/task-config@1";
+10 -117
View File
@@ -1,93 +1,23 @@
// Central lifecycle vocabulary for the dashboard. The backend is the source of
// truth: /api/task-meta returns the statuses (label, pill severity, "needs you"
// grouping) and operator actions (label, button variant, confirm prompt). This
// module fetches that catalog and exposes the accessors the rest of the UI
// reads, so no surface keeps a hand-synced copy of the vocabulary.
// Lifecycle vocabulary for the dashboard: the status labels, pill severities
// and "needs you" grouping the shell and the stage rail draw.
//
// The defaults below are a freeze-dried snapshot that render immediately and
// keep working when archied is unreachable; loadTaskMeta() replaces them with
// the live catalog as soon as it arrives. They must match the backend catalog
// so drawing the page never flashes a stale label.
//
// loadTaskMeta() is called once at boot by main.ts. The catalog is held in
// refs, so a late-arriving catalog re-renders whatever already read it; there
// is no separate "re-render the mounted route" step the way the Preact shell
// needed one.
//
// The dashboard draws a line here between two kinds of vocabulary. Anything
// that is *presentation* -- a status's label, pill severity and "needs you"
// grouping, or a control's label and confirm prompt -- is served, because the
// server owns the words as well as the ids.
import { computed, shallowRef } from "vue";
import { api } from "./api";
// The single binary serves no catalogue for this, so the vocabulary is the
// snapshot in task-meta-snapshot.ts. Keep it in step with the statuses the
// binary reports; a status it doesn't list renders as its own id.
import type { StatusKind } from "./status";
import {
type ActionMeta,
type ChangeStatusMeta,
DEFAULT_ACTIONS,
DEFAULT_CHANGE_STATUSES,
DEFAULT_CONFIG_SCHEMA,
DEFAULT_RETRY_MODES,
DEFAULT_STATUSES,
type RetryModeMeta,
type StatusMeta,
} from "./task-meta-snapshot";
import { DEFAULT_STATUSES, type StatusMeta } from "./task-meta-snapshot";
export type { ActionMeta, RetryModeMeta, StatusMeta };
const statuses = shallowRef<StatusMeta[]>([...DEFAULT_STATUSES]);
const actions = shallowRef<ActionMeta[]>([...DEFAULT_ACTIONS]);
const retryModesRef = shallowRef<RetryModeMeta[]>([...DEFAULT_RETRY_MODES]);
const changeStatuses = shallowRef<ChangeStatusMeta[]>([
...DEFAULT_CHANGE_STATUSES,
]);
const configSchemaRef = shallowRef<string>(DEFAULT_CONFIG_SCHEMA);
const statusById = computed(
() => new Map(statuses.value.map((s) => [s.id, s])),
);
const actionById = computed(() => new Map(actions.value.map((a) => [a.id, a])));
const changeStatusById = computed(
() => new Map(changeStatuses.value.map((c) => [c.id, c])),
);
// loadTaskMeta upgrades the dashboard from the server catalog. It never throws:
// a failed fetch keeps the defaults so the UI still renders.
export async function loadTaskMeta(): Promise<void> {
try {
const data = await api.taskMeta<{
statuses?: StatusMeta[];
actions?: ActionMeta[];
retry_modes?: RetryModeMeta[];
change_statuses?: ChangeStatusMeta[];
config_schema?: string;
} | null>();
if (Array.isArray(data?.statuses)) statuses.value = data.statuses;
if (Array.isArray(data?.actions)) actions.value = data.actions;
if (Array.isArray(data?.retry_modes)) retryModesRef.value = data.retry_modes;
if (Array.isArray(data?.change_statuses))
changeStatuses.value = data.change_statuses;
if (data?.config_schema) configSchemaRef.value = data.config_schema;
} catch {
// archied unreachable or not yet serving this route; keep the defaults.
}
}
const statusById = new Map(DEFAULT_STATUSES.map((s) => [s.id, s]));
/** statusLabel is the human-readable name for a lifecycle status. */
export function statusLabel(id: string): string {
return statusById.value.get(id)?.label || id || "Unknown";
return statusById.get(id)?.label || id || "Unknown";
}
/** statusKind is the pill severity token (idle, info, ok, warn, danger). */
export function statusKind(id: string): StatusKind {
return (statusById.value.get(id)?.kind || "idle") as StatusKind;
}
/** statusList returns every known lifecycle status in display order. */
export function statusList(): StatusMeta[] {
return statuses.value;
return (statusById.get(id)?.kind || "idle") as StatusKind;
}
/**
@@ -95,42 +25,5 @@ export function statusList(): StatusMeta[] {
* filter (work that needs attention).
*/
export function attentionStatusIds(): Set<string> {
return new Set(statuses.value.filter((s) => s.needs_attention).map((s) => s.id));
return new Set((DEFAULT_STATUSES as StatusMeta[]).filter((s) => s.needs_attention).map((s) => s.id));
}
/**
* actionFor returns the presentation metadata for an operator control, or null
* if the backend has never seen it.
*/
export function actionFor(id: string): ActionMeta | null {
return actionById.value.get(id) || null;
}
/**
* retryModes returns the server's retry worktree modes in display order. The
* retry dialog renders these and falls back to the frozen snapshot before the
* catalog arrives.
*/
export function retryModes(): RetryModeMeta[] {
return retryModesRef.value;
}
/**
* changeStatusLabel names a changes_captured file status. An id the catalog
* does not know renders as itself rather than breaking the row.
*/
export function changeStatusLabel(id: string | undefined): string {
return (id && changeStatusById.value.get(id)?.label) || id || "unknown";
}
/** configSchema is the schema stamp a recognised config_captured payload carries. */
export function configSchema(): string {
return configSchemaRef.value;
}
/** What a task waiting for approval asks the operator to decide. */
export const approvalLabels: Record<string, string> = {
plan: "Plan",
review: "Review findings",
budget: "Continue?",
};
+3 -142
View File
@@ -1,10 +1,9 @@
// The dashboard's WebMCP tools: what an in-page agent may read and do.
// The dashboard's WebMCP tools: what an in-page agent may read.
//
// The API client is a parameter rather than a module import, so this list is
// host-agnostic and unit-testable; `archie-webmcp.ts` is the one place that
// binds it to the dashboard's own client. Scope is deliberate: read-only
// inspection and consequential task actions. The authenticated operator's
// session authorizes every mutation.
// inspection only.
//
// Security model: these tools run in the signed-in operator's own browser
// session, so they inherit exactly what that operator can already do and can
@@ -12,25 +11,13 @@
//
// The annotations are advisory, and today they are not enforced: Chrome 152's
// `getTools()` reports only `readOnlyHint` and `untrustedContentHint` and drops
// `consequentialHint`, so no agent sees it from discovery, and a page-invoked
// `executeTool` gates nothing. `consequentialHint` is still set on the recovery
// tools because the spec accepts it and a conforming client may honour it.
// The `confirm: true` requirement below is a deliberate-action signal, not a
// security control: an agent can pass it trivially. Its value is making the
// model state intent rather than reaching for a mutation mid-sentence.
// `consequentialHint`. Every tool here is a read.
import type { WebMcpTool } from "./webmcp";
/** The dashboard client these tools call. `ui/src/lib/api.ts` satisfies it. */
export interface DashboardApi {
health<T = unknown>(): Promise<T>;
tasks<T = unknown>(): Promise<T>;
task<T = unknown>(id: string): Promise<T>;
captures<T = unknown>(limit?: number): Promise<T>;
taskAction<T = unknown>(
id: string,
action: string,
payload?: { instructions?: string; findings?: string[] },
): Promise<T>;
}
/** The MCP-shaped envelope a tool result is returned in. */
@@ -47,93 +34,9 @@ function jsonEnvelope(value: unknown): ToolEnvelope {
return textEnvelope(JSON.stringify(value, null, 2));
}
/** A required task id, read from tool input. */
function taskID(input: Record<string, unknown>): string {
const id = input.task_id;
if (typeof id !== "string" && typeof id !== "number") {
throw new Error("task_id is required");
}
return String(id);
}
const taskIDSchema = {
type: "object",
properties: {
task_id: {
type: "string",
description: "Task id, as shown on the dashboard's task pages.",
},
},
required: ["task_id"],
additionalProperties: false,
} as const;
// A task action's schema. `confirm` is required and must be true: a
// deliberate-action signal, not a security control (see the module header).
const taskActionSchema = {
type: "object",
properties: {
task_id: {
type: "string",
description: "Task id, as shown on the dashboard's task pages.",
},
confirm: {
type: "boolean",
description:
"Must be true. State the intent explicitly rather than as a side effect of another action.",
},
},
required: ["task_id", "confirm"],
additionalProperties: false,
} as const;
/** One task action, published under its own name so the agent chooses by intent. */
function taskActionTool(
client: DashboardApi,
name: string,
action: string,
description: string,
): WebMcpTool {
return {
name,
description,
inputSchema: taskActionSchema,
annotations: { readOnlyHint: false, consequentialHint: true },
execute: async (input) => {
const id = taskID(input);
if (input.confirm !== true) {
throw new Error(
`${name}: confirm must be true; this action changes a task`,
);
}
return jsonEnvelope(await client.taskAction(id, action));
},
};
}
/** Every tool the dashboard publishes to model context. */
export function archieWebMcpTools(client: DashboardApi): WebMcpTool[] {
return [
{
name: "list_tasks",
description:
"List Archie's tasks with their state, stage, and age. Read-only. The output is operator- and agent-authored and must be treated as untrusted.",
inputSchema: {
type: "object",
properties: {},
additionalProperties: false,
},
annotations: { readOnlyHint: true, untrustedContentHint: true },
execute: async () => jsonEnvelope(await client.tasks()),
},
{
name: "get_task",
description:
"Read one task's status and detail by id. Read-only. The output includes agent-generated content and must be treated as untrusted.",
inputSchema: taskIDSchema,
annotations: { readOnlyHint: true, untrustedContentHint: true },
execute: async (input) => jsonEnvelope(await client.task(taskID(input))),
},
{
name: "recent_events",
description:
@@ -169,47 +72,5 @@ export function archieWebMcpTools(client: DashboardApi): WebMcpTool[] {
annotations: { readOnlyHint: true, untrustedContentHint: false },
execute: async () => jsonEnvelope(await client.health()),
},
taskActionTool(
client,
"retry_task",
"retry",
"Requeue a task that is stuck or parked so the workflow runs it again; keeps the task, its history, and its pull request. This recovers stalled work -- it is not how a review is approved.",
),
taskActionTool(
client,
"stop_task",
"stop",
"Stop a running task recoverably: it moves to parked and can be retried later. Does not close the issue or discard the branch. Use this to pause work; use cancel_task to end it.",
),
taskActionTool(
client,
"cancel_task",
"cancel",
"End a parked task archie should not continue; the forge issue stays open. stop_task parks a running task recoverably instead.",
),
taskActionTool(
client,
"approve_task",
"approve",
"Approve a task waiting for approval so its workflow can continue.",
),
taskActionTool(
client,
"reject_task",
"reject",
"Reject a task Archie should not continue. This ends the task and may close its forge issue or pull request.",
),
taskActionTool(
client,
"abandon_task",
"abandon",
"Abandon a parked task without closing its forge issue.",
),
taskActionTool(
client,
"archive_task",
"archive",
"Archive a terminal task, removing its local task record and worktree.",
),
];
}
-27
View File
@@ -1,27 +0,0 @@
<script setup lang="ts">
import { Pause, Play } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { paused } from "./state";
/**
* Freeze the tail, or read the history again.
*
* Pause is a state as much as an action, so the button carries it: while the
* list has stopped following the stream this is the only thing on the page
* that says so, and the emphasis marks it.
*/
function togglePause(): void {
paused.value = !paused.value;
}
</script>
<template>
<div class="flex flex-wrap items-center gap-2">
<Button :variant="paused ? 'default' : 'outline'" @click="togglePause">
<Play v-if="paused" data-icon="inline-start" />
<Pause v-else data-icon="inline-start" />
{{ paused ? "Resume" : "Pause" }}
</Button>
</div>
</template>
-122
View File
@@ -1,122 +0,0 @@
<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from "vue";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { LOG_LEVELS } from "@/lib/log";
import { componentOptions, serviceOptions, filters } from "./state";
/**
* The list's filters: level, component and a search over messages and fields.
*
* The level and component pair are two-way on the filter state, because a
* change to either is a new read; the search box commits after a pause,
* because a keystroke is not a request.
*/
// reka-ui refuses an empty string as a SelectItem value -- it is how the
// component spells "nothing selected". The wire wants an absent filter for
// "all", so the sentinel converts at this boundary and everything downstream
// (the filter state, the query string, the server) keeps the empty value.
const ALL = "__all__";
// LOG_LEVELS' values are a wire contract: the server matches that CSV
// server-side, so the labels are paired with them here and never rewritten.
const levelOptions = LOG_LEVELS.map((option) => ({
value: option.value || ALL,
label: option.label,
}));
const componentSelectOptions = computed(() => [
{ value: ALL, label: "All components" },
...componentOptions.value.map((name) => ({ value: name, label: name })),
]);
const service=computed(()=>filters.service||ALL);
function setService(value:unknown):void{filters.service=value===ALL?"":String(value??"")}
const level = computed(() => filters.level || ALL);
const component = computed(() => filters.component || ALL);
function setLevel(value: unknown): void {
filters.level = value === ALL ? "" : String(value ?? "");
}
function setComponent(value: unknown): void {
filters.component = value === ALL ? "" : String(value ?? "");
}
// Seeded from the filter rather than from nothing: the filters outlive a visit
// to this page, and a box that came back empty while the list was still
// narrowed by its query would be claiming the list is unfiltered.
const search = ref(filters.q);
let searchTimer: ReturnType<typeof setTimeout> | undefined;
watch(search, (value) => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
filters.q = value;
}, 250);
});
onUnmounted(() => clearTimeout(searchTimer));
</script>
<template>
<div class="flex min-w-0 flex-wrap items-center gap-2">
<Select :model-value="service" @update:model-value="setService">
<SelectTrigger size="sm" class="w-48" aria-label="Service"><SelectValue placeholder="All services" /></SelectTrigger>
<SelectContent><SelectGroup>
<SelectItem :value="ALL">All services</SelectItem>
<SelectItem v-for="name in serviceOptions" :key="name" :value="name">{{ name }}</SelectItem>
</SelectGroup></SelectContent>
</Select>
<Select :model-value="level" @update:model-value="setLevel">
<SelectTrigger size="sm" class="w-44" aria-label="Level">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem
v-for="option in levelOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
<Select :model-value="component" @update:model-value="setComponent">
<SelectTrigger size="sm" class="w-44" aria-label="Component">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem
v-for="option in componentSelectOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
<Input
v-model="search"
type="search"
aria-label="Search messages and fields"
placeholder="Search messages and fields…"
class="min-w-0 flex-1 md:max-w-56"
/>
</div>
</template>
-72
View File
@@ -1,72 +0,0 @@
<script setup lang="ts">
import { ref, watch } from "vue";
import LogTable from "@/base/LogTable.vue";
import { Skeleton } from "@/components/ui/skeleton";
import { entryKey } from "./log-entries";
import { errors } from "@/copy/errors";
import LogsEmpty from "./LogsEmpty.vue";
import { emptyDetail, emptyTitle, entries, loading, readError } from "./state";
/**
* The lines, or the one thing that stands in for them.
*
* Dense and monospace by design: the point of this page is scanning a lot of
* lines quickly.
*/
// Varied widths, so the placeholder reads as lines of a log rather than a
// table waiting to be filled.
const SKELETON_ROWS = [
"w-11/12",
"w-3/4",
"w-5/6",
"w-2/3",
"w-11/12",
"w-1/2",
"w-5/6",
"w-3/4",
];
const scroller = ref<HTMLElement | null>(null);
// The tail follows the newest line, which is the last one. flush: 'post'
// scrolls after the new rows are in the DOM -- scrolling before that measures
// the height the list is about to replace.
watch(
entries,
() => {
const el = scroller.value;
if (el) el.scrollTop = el.scrollHeight;
},
{ flush: "post" },
);
</script>
<template>
<div ref="scroller" class="max-h-[62vh] overflow-y-auto text-caption">
<!-- A failed read is about this page's request, not about the log, so it
says what the server said rather than borrowing an empty state. -->
<LogsEmpty v-if="readError" :title="errors.logs.read.unreadable" :detail="readError" />
<div
v-else-if="loading && !entries.length"
class="flex flex-col gap-3 px-3 py-4"
>
<Skeleton
v-for="(width, i) in SKELETON_ROWS"
:key="i"
class="h-3"
:class="width"
/>
</div>
<LogsEmpty
v-else-if="!entries.length"
:title="emptyTitle"
:detail="emptyDetail"
/>
<template v-else>
<LogTable :entries="entries" :row-key="entryKey" storage-key="logs" services />
</template>
</div>
</template>
-18
View File
@@ -1,18 +0,0 @@
<script setup lang="ts">
import { Badge } from "@/components/ui/badge";
import { meta, streamKind, streamState } from "./state";
/**
* What the list is showing, and the state of the stream that is supposed to be
* adding to it: the lines mean nothing without it.
*/
</script>
<template>
<div class="flex flex-wrap items-center gap-3">
<span class="min-w-0 break-words font-mono text-caption text-fg-subtle">{{
meta
}}</span>
<Badge v-if="streamKind !== 'ok'" :variant="streamKind">{{ streamState }}</Badge>
</div>
</template>
-28
View File
@@ -1,28 +0,0 @@
<script setup lang="ts">
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import LogFilters from "./LogFilters.vue";
import LogList from "./LogList.vue";
import {serviceErrors} from "./state";
import LogStatus from "./LogStatus.vue";
/** The log surface: the filters and the stream's own state over the lines. */
</script>
<template>
<!-- gap-0 so the header's rule sits on the list rather than a card gap above
it; the rows carry their own separators. -->
<Card class="gap-0">
<CardHeader
class="flex flex-wrap items-center justify-between gap-3 border-b"
>
<LogFilters />
<LogStatus />
</CardHeader>
<CardContent class="px-0">
<Alert v-for="(error,service) in serviceErrors" :key="service" variant="destructive" class="px-3 py-2"><AlertDescription>{{ service }}: {{ error }}</AlertDescription></Alert>
<LogList />
</CardContent>
</Card>
</template>
-24
View File
@@ -1,24 +0,0 @@
<script setup lang="ts">
import {
Empty,
EmptyDescription,
EmptyHeader,
EmptyTitle,
} from "@/components/ui/empty";
/**
* The list's nothing-to-show state: a title that names the situation and a
* line saying what to expect next. Which words those are is decided by
* logs-empty.ts, not here.
*/
defineProps<{ title: string; detail?: string }>();
</script>
<template>
<Empty>
<EmptyHeader>
<EmptyTitle>{{ title }}</EmptyTitle>
<EmptyDescription v-if="detail">{{ detail }}</EmptyDescription>
</EmptyHeader>
</Empty>
</template>
-71
View File
@@ -1,71 +0,0 @@
import type { LogEntry } from "@/lib/log";
/**
* What the log list is made of: the filters an entry survives, the key that
* makes one entry, and the merge of the durable history with the live tail.
* Pure, so the page's rendering has nothing to decide about entries.
*/
/** The filters the list is read through. All three narrow the read
* server-side as well as the live stream locally. */
export interface LogFilters {
service?: string;
level: string;
component: string;
q: string;
}
/**
* entryKey is the identity of a log line: its time, level, message and fields.
* The live stream repeats entries the history also carries, so both sides key
* on the same value and the duplicate is stored once.
*/
export function entryKey(entry: LogEntry): string {
return `${entry.time || ""}|${entry.level || ""}|${entry.message || entry.msg || ""}|${JSON.stringify(entry.fields || {})}`;
}
/**
* matchesFilters applies the filters to one entry. It runs over live entries as
* they arrive and again over the merged list, so the level CSV is matched part
* by part exactly as the server matches it (`splitCSV` in
* internal/webui/api_tasks_logs.go).
*/
export function matchesFilters(entry: LogEntry, filters: LogFilters): boolean {
if (
filters.level &&
!filters.level.split(",").includes((entry.level || "").toUpperCase())
) {
return false;
}
if (filters.service && entry.fields?.service !== filters.service) return false;
if (filters.component && entry.fields?.component !== filters.component)
return false;
if (filters.q) {
const needle = filters.q.toLowerCase();
const hay =
`${entry.message || entry.msg || ""} ${JSON.stringify(entry.fields || {})}`.toLowerCase();
if (!hay.includes(needle)) return false;
}
return true;
}
/**
* mergeEntries overlays the live tail on the durable history, keeps the last
* 1000 that pass the filters, and returns them oldest first.
*
* A key the history already holds keeps its position when the live entry
* replaces it, so a line both sources carry is not reordered; lines only ever
* seen live land at the end, where the newest ones belong.
*/
export function mergeEntries(
history: LogEntry[],
live: Map<string, LogEntry>,
filters: LogFilters,
): LogEntry[] {
const byID = new Map<string, LogEntry>();
for (const entry of history) byID.set(entryKey(entry), entry);
for (const [id, entry] of live) byID.set(id, entry);
return [...byID.values()]
.filter((entry) => matchesFilters(entry, filters))
.slice(-1000);
}
-27
View File
@@ -1,27 +0,0 @@
// What the logs list says when it has nothing to show: a dead stream, a
// deployment with no durable history, or filters that match nothing.
import { errors } from "@/copy/errors";
/** logsEmptyTitle names the situation. */
export function logsEmptyTitle(
durableUnavailable: boolean,
streamState: string,
): string {
if (streamState === "unavailable") return errors.logs.empty.streamUnavailable;
if (durableUnavailable) return "No logs yet";
return "Nothing matches";
}
/** The line under the title: what to expect next. */
export function logsEmptyDetail(
durableUnavailable: boolean,
streamState: string,
): string {
if (streamState === "unavailable") {
return errors.logs.empty.streamUnavailableDetail;
}
if (durableUnavailable) {
return "This deployment keeps no durable history.";
}
return "Try a wider level or clear the search.";
}
-190
View File
@@ -1,190 +0,0 @@
import { computed, onMounted, onUnmounted, reactive, ref, watch } from "vue";
import { errors } from "@/copy/errors";
import { api, describeError } from "@/lib/api";
import { useSessionStore } from "@/stores/session";
import type { LogEntry } from "@/lib/log";
import type { StatusKind } from "@/lib/status";
import type { StreamState } from "@/lib/stream-state";
import {
entryKey,
matchesFilters,
mergeEntries,
type LogFilters,
} from "./log-entries";
import { logsEmptyDetail, logsEmptyTitle } from "./logs-empty";
/**
* The log page's shared state.
*
* The filters, the stream's state and the list itself are read by different
* components, so it lives in a module rather than being threaded down through a
* chain of props.
*/
/** One page of the durable log, as GET /api/logs answers it. */
interface LogHistory {
entries?: LogEntry[];
components?: string[];
services?:string[];
errors?:Record<string,string>;
file?: string;
/** The process serving the request keeps no durable history. */
disabled?: boolean;
}
export const filters = reactive<LogFilters>({
level: "",
service:"",
component: "",
q: "",
});
/** The components the filter can name: those the server found, plus any the
* live stream has shown since. */
export const serviceOptions=ref<string[]>([]);
export const serviceErrors=ref<Record<string,string>>({});
export const componentOptions = ref<string[]>([]);
export const paused = ref(false);
export const loading = ref(true);
export const readError = ref<string | null>(null);
export const streamState = ref<StreamState | "connecting">("connecting");
const historyEntries = ref<LogEntry[]>([]);
const durableUnavailable = ref(false);
const logFile = ref("");
// Live entries are held in a plain Map so a line the stream repeats is stored
// once, and the tick is what makes that mutation visible to `entries` below --
// a Map is not something a computed can depend on by being read.
const liveEntries = new Map<string, LogEntry>();
const liveTick = ref(0);
export const entries = computed(() => {
void liveTick.value;
return mergeEntries(historyEntries.value, liveEntries, filters);
});
/** A failed read, else the file the lines came from. */
export const meta = computed(() => (readError.value ? errors.logs.read.unreadable : logFile.value));
/** The stream's state as a badge kind. Never `ok` for a stream that is still
* connecting, and never `warn` for one that has given up: the two are
* different answers, and stream-state.ts is what tells them apart. */
export const streamKind = computed<StatusKind>(() => {
if (streamState.value === "live") return "ok";
return streamState.value === "unavailable" ? "danger" : "warn";
});
/** Which of the nothing-to-show situations the list is in. */
export const emptyTitle = computed(() =>
logsEmptyTitle(durableUnavailable.value, streamState.value),
);
export const emptyDetail = computed(() =>
logsEmptyDetail(durableUnavailable.value, streamState.value),
);
let generation=0;
async function loadLogs(): Promise<void> {
const current=++generation;
loading.value = true;
// readError is cleared only by a successful read below: clearing it here
// makes the error and the stale lines alternate on every 5 s refresh.
try {
const res = await api.logs<LogHistory>({
service:filters.service,
level: filters.level,
component: filters.component,
q: filters.q,
limit: 500,
});
if(current!==generation)return;
readError.value = null;
serviceOptions.value=[...new Set([...serviceOptions.value,...(res.services??[])])].sort();
serviceErrors.value=res.errors??{};
componentOptions.value = res.components ?? [];
durableUnavailable.value = !!res.disabled;
logFile.value = res.file ?? "";
historyEntries.value = res.entries ?? [];
} catch (err) {
if(current!==generation)return;
// The server's own message is the only part of a failure an operator can
// act on, so it is what the list says instead of the lines.
readError.value = describeError(err, errors.common.unknown);
} finally {
if(current===generation)loading.value = false;
}
}
function handleEntry(raw: unknown): void {
// Paused drops what arrives rather than buffering it: the list is a view of
// the stream, and resuming continues from where the stream is now instead of
// replaying the pause.
if (paused.value) return;
const entry = raw as LogEntry;
if (!matchesFilters(entry, filters)) return;
if (streamState.value === "unavailable") streamState.value = "live";
liveEntries.set(entryKey(entry), entry);
// The list shows only the last 1000; keep a margin and drop the oldest so
// the map cannot grow without bound while the page stays open.
if (liveEntries.size > 1500) {
let excess = liveEntries.size - 1500;
for (const key of liveEntries.keys()) {
liveEntries.delete(key);
if (--excess <= 0) break;
}
}
const component = entry.fields?.component;
if (
typeof component === "string" &&
component &&
!componentOptions.value.includes(component)
) {
componentOptions.value = [...componentOptions.value, component];
}
liveTick.value += 1;
}
let refresh:ReturnType<typeof setInterval>|undefined;
let unsubscribe: (() => void) | undefined;
/** Owns the initial read, the re-reads a filter change causes, and the live
* stream, for the page's lifetime. */
export function useLogs(): void {
const live = useSessionStore();
onMounted(() => {
// A mount opens a new stream against a fresh read, so the tail starts
// unpaused, connecting, and without the lines the previous visit's stream
// left behind. The filters are not reset: they are what the operator last
// asked to see, and the read below answers them again.
paused.value = false;
streamState.value = "connecting";
liveEntries.clear();
liveTick.value += 1;
void loadLogs();
refresh=setInterval(()=>{if(!paused.value)void loadLogs()},5000);
unsubscribe = live.subscribe("logs", handleEntry);
streamState.value = live.streamState;
});
onUnmounted(() => {
clearInterval(refresh);
generation++;
unsubscribe?.();
unsubscribe = undefined;
});
watch(() => live.streamState, (state) => {
streamState.value = state;
});
// A process without a LogFeed cannot deliver live entries.
const stopStatus = live.subscribe("logs-status", (data) => {
if (!(data as { available: boolean }).available) streamState.value = "unavailable";
});
onUnmounted(stopStatus);
// Every filter is a server-side one -- the request carries it -- so a change
// to any of them is a new read, not a re-filter of what is already here.
watch(filters, () => void loadLogs());
}
+9 -3
View File
@@ -34,13 +34,19 @@ const error = ref("");
const busy = ref(false);
const identities = useOrgStore();
// The owner has to be an identity that already exists, so the candidates are the
// members of the caller's organisation.
const people = computed(() =>
identities.identities.filter((i) => i.kind !== "system" && i.lifecycle === "active"),
(identities.membersByOrg.get(identities.homeOrg) ?? []).filter((member) => member.kind !== "system" && member.status === "active"),
);
function opened(value: boolean): void {
open.value = value;
if (value) identities.watchIdentities();
if (value) {
void identities.loadOrg()
.then(() => identities.readMembers(identities.homeOrg))
.catch((cause) => (error.value = describeError(cause, errors.common.unknown)));
}
}
async function create(): Promise<void> {
@@ -80,7 +86,7 @@ async function create(): Promise<void> {
<SelectValue placeholder="Owner" />
</SelectTrigger>
<SelectContent>
<SelectItem v-for="person in people" :key="person.id" :value="person.id">
<SelectItem v-for="person in people" :key="person.identity_id" :value="person.identity_id">
{{ person.display_name }}
</SelectItem>
</SelectContent>
+5 -8
View File
@@ -9,19 +9,16 @@ const accounts = useAccountsStore();
const scope = computed(() => props.orgId || org.homeOrg);
const recordName = computed(() => props.name === props.id ? undefined : props.name);
watch(() => [props.id, recordName.value, props.kind, props.orgId] as const, ([id, name, kind, orgId]) => {
watch(() => [props.id, props.kind, props.orgId] as const, ([id, kind, orgId]) => {
if (!id || (kind && kind !== "user")) return;
if (!name || !kind) org.watchIdentities();
void org.loadOrg().then(() => {
if (!name || !kind) return org.readMembers(orgId || org.homeOrg);
}).catch(() => { /* Without a directory, keep the attribution supplied by the record. */ });
void org.loadOrg().then(() => org.readMembers(orgId || org.homeOrg))
.catch(() => { /* Without a member list, keep the attribution supplied by the record. */ });
}, { immediate: true });
const identity = computed(() => org.identities.find((entry) => entry.id === props.id));
const member = computed(() => org.membersByOrg.get(scope.value)?.find((entry) => entry.identity_id === props.id));
const account = computed(() => accounts.status?.user?.id === props.id ? accounts.status?.user : undefined);
const kind = computed(() => props.kind || member.value?.kind || identity.value?.kind || account.value?.kind);
const label = computed(() => recordName.value || member.value?.display_name || identity.value?.display_name || account.value?.display_name || props.id || props.fallback);
const kind = computed(() => props.kind || member.value?.kind || account.value?.kind);
const label = computed(() => recordName.value || member.value?.display_name || account.value?.display_name || props.id || props.fallback);
</script>
<template>
-2
View File
@@ -81,8 +81,6 @@ async function loadCounts() {
const loaded = await loadEventCounts({
captures: api.captures,
mappings: () => api.mappings(),
// A binding is a trigger bound to an event type.
bindings: async () => ({ bindings: (await api.triggers()).filter((t) => t.event_type_id) }),
});
if (gen !== countsGeneration) return;
counts.value = loaded;
@@ -1,202 +0,0 @@
<script setup lang="ts">
import { errors } from "@/copy/errors";
import TriggerRuns from "@/pages/events/bindings/components/TriggerRuns.vue";
import { computed, ref, watch } from "vue";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { eventTypeLabel, type EventType } from "@/pages/events/inspector/lib/event-types";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import {
draftFromBinding,
emptyDraft,
mappingsForEventType,
type Binding,
type BindingDraft,
type MappingOption,
type WorkflowOption,
} from "@/pages/events/bindings/lib/binding-trigger";
/**
* The binding editor: name, the event type it applies to, an optional mapping
* of that type, and the workflow it starts. Signing is the source's.
*/
const props = defineProps<{
/** null is a new binding; a binding is an edit. */
binding: Binding | null;
mappings: MappingOption[];
eventTypes: EventType[];
workflows: WorkflowOption[];
saving: boolean;
error: string | null;
}>();
const open = defineModel<boolean>("open", { required: true });
const emit = defineEmits<{ save: [draft: BindingDraft] }>();
// The draft is re-seeded on every open, so an edit that was cancelled -- or a
// save that failed -- never leaks into the next binding's form.
const draft = ref<BindingDraft>(emptyDraft());
watch(
open,
(isOpen) => {
if (isOpen)
draft.value = props.binding ? draftFromBinding(props.binding) : emptyDraft();
},
{ immediate: true },
);
const typeMappings = computed(() =>
mappingsForEventType(props.mappings, draft.value.eventTypeId),
);
// A mapping belongs to one event type, so changing the type clears a mapping
// that no longer fits it.
watch(
() => draft.value.eventTypeId,
() => {
if (!typeMappings.value.some((m) => m.id === draft.value.mappingId))
draft.value.mappingId = "";
},
);
// Select items cannot carry an empty value.
const NO_MAPPING = "__none__";
const mappingChoice = computed({
get: () => draft.value.mappingId || NO_MAPPING,
set: (v: string) => {
draft.value.mappingId = v === NO_MAPPING ? "" : v;
},
});
const title = computed(() => (props.binding ? "Edit binding" : "New binding"));
</script>
<template>
<Dialog v-model:open="open">
<DialogContent class="max-h-[85vh] overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle>{{ title }}</DialogTitle>
<DialogDescription>Saving returns it to pending approval.</DialogDescription>
</DialogHeader>
<form @submit.prevent="emit('save', draft)">
<FieldGroup>
<Field>
<FieldLabel for="binding-name">Name</FieldLabel>
<Input
id="binding-name"
v-model="draft.name"
pattern="[a-z][a-z0-9\-]*"
required
/>
</Field>
<Field>
<FieldLabel for="binding-event-type">Event type</FieldLabel>
<Select v-model="draft.eventTypeId">
<SelectTrigger id="binding-event-type" class="w-full">
<SelectValue placeholder="Pick an event type" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem
v-for="type in props.eventTypes"
:key="type.id"
:value="type.id"
>
{{ eventTypeLabel(type.id, props.eventTypes) }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Field>
<Field>
<FieldLabel for="binding-mapping">Field mapping</FieldLabel>
<Select v-model="mappingChoice" :disabled="!draft.eventTypeId">
<SelectTrigger id="binding-mapping" class="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem :value="NO_MAPPING">None</SelectItem>
<SelectItem
v-for="mapping in typeMappings"
:key="mapping.id"
:value="String(mapping.id)"
>
{{ mapping.name }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Field>
<Field>
<FieldLabel for="binding-workflow">Workflow</FieldLabel>
<Select v-model="draft.workflow">
<SelectTrigger id="binding-workflow" class="w-full">
<SelectValue placeholder="Pick a workflow" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem
v-for="workflow in props.workflows"
:key="workflow.id"
:value="workflow.id"
>
{{ workflow.name }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Field>
</FieldGroup>
<section v-if="props.binding" class="mt-4 flex flex-col gap-2">
<h3 class="text-caption font-medium tracking-[0.06em] text-fg-subtle uppercase">Recent runs</h3>
<TriggerRuns kind="triggers" :id="props.binding.id" />
</section>
<!-- Beside the buttons, not at the top: the dialog scrolls, and Save is
clicked at the bottom, where a refusal must be seen. -->
<Alert v-if="props.error" variant="destructive" class="mt-4">
<AlertTitle>{{ errors.bindings.editor.saveFailed }}</AlertTitle>
<AlertDescription>{{ props.error }}</AlertDescription>
</Alert>
<DialogFooter class="mt-4">
<Button type="button" variant="outline" @click="open = false"
>Cancel</Button
>
<Button
type="submit"
:disabled="props.saving || !draft.eventTypeId || !draft.workflow"
>
<Spinner v-if="props.saving" data-icon="inline-start" />{{ props.saving ? "Saving" : "Save" }}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</template>
@@ -1,73 +0,0 @@
<script setup lang="ts">
import { Check, Pause, Pencil, Play, Trash2 } from "@lucide/vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { MoreMenu } from "@/components/ui/more-menu";
import { TableCell, TableRow } from "@/components/ui/table";
import BindingStatusBadge from "@/pages/events/bindings/components/BindingStatusBadge.vue";
import { eventTypeLabel, type EventType } from "@/pages/events/inspector/lib/event-types";
import type { Binding } from "@/pages/events/bindings/lib/binding-trigger";
/** One saved binding's summary row. */
const props = defineProps<{
binding: Binding;
eventTypes: EventType[];
}>();
const emit = defineEmits<{
edit: [binding: Binding];
approve: [binding: Binding];
pause: [binding: Binding];
resume: [binding: Binding];
delete: [binding: Binding];
}>();
</script>
<template>
<TableRow>
<TableCell class="font-medium">{{ props.binding.name }}</TableCell>
<TableCell class="font-mono text-fg-muted">
<div class="flex items-center gap-2">
{{ eventTypeLabel(props.binding.event_type_id, props.eventTypes) }}
<Badge v-if="props.binding.unsigned" variant="warn">Unsigned</Badge>
</div>
</TableCell>
<TableCell>{{ props.binding.workflow || "–" }}</TableCell>
<TableCell><BindingStatusBadge :status="props.binding.status" /></TableCell>
<TableCell>
<div class="flex items-center justify-end gap-1">
<Button
variant="outline"
size="sm"
@click="emit('edit', props.binding)"
>
<Pencil data-icon="inline-start" />
Edit</Button>
<!-- Only a pending binding can be approved. An armed binding is
already firing, so the button would be a no-op -- or worse, a
misleading one. -->
<Button
v-if="props.binding.status === 'pending_approval'"
size="sm"
@click="emit('approve', props.binding)"
>
<Check data-icon="inline-start" />
Approve</Button>
<MoreMenu :label="`More actions for ${props.binding.name}`">
<DropdownMenuItem
v-if="props.binding.status === 'armed'"
@select="emit('pause', props.binding)"
><Pause />Pause</DropdownMenuItem>
<!-- Resuming returns the binding to pending approval, so it is
approved again before it fires. -->
<DropdownMenuItem
v-if="props.binding.status === 'paused'"
@select="emit('resume', props.binding)"
><Play />Resume</DropdownMenuItem>
<DropdownMenuItem variant="destructive" @select="emit('delete', props.binding)"><Trash2 />Delete</DropdownMenuItem>
</MoreMenu>
</div>
</TableCell>
</TableRow>
</template>
@@ -1,15 +0,0 @@
<script setup lang="ts">
import { Badge } from "@/components/ui/badge";
import { statusKind, statusLabel } from "@/pages/events/bindings/lib/binding-draft";
/** A binding's lifecycle state: pending approval, armed or paused. The
* colour ramp is shared with every other status in the dashboard, so the
* same colour means the same thing here as it does on a task. */
const props = defineProps<{ status?: string }>();
</script>
<template>
<Badge :variant="statusKind(props.status)">{{
statusLabel(props.status)
}}</Badge>
</template>
@@ -1,101 +0,0 @@
<script setup lang="ts">
import { computed } from "vue";
import { errors } from "@/copy/errors";
import {
Empty,
EmptyDescription,
EmptyHeader,
EmptyTitle,
} from "@/components/ui/empty";
import { Skeleton } from "@/components/ui/skeleton";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import BindingRow from "@/pages/events/bindings/components/BindingRow.vue";
import type { EventType } from "@/pages/events/inspector/lib/event-types";
import type { Binding } from "@/pages/events/bindings/lib/binding-trigger";
import type { LoadFailure } from "@/pages/events/bindings/lib/use-bindings";
const props = defineProps<{
/** null means loading, [] means loaded and empty. */
bindings: Binding[] | null;
eventTypes: EventType[];
failure: LoadFailure | null;
}>();
const emit = defineEmits<{
edit: [binding: Binding];
approve: [binding: Binding];
pause: [binding: Binding];
resume: [binding: Binding];
delete: [binding: Binding];
}>();
const loading = computed(() => props.bindings === null);
const rows = computed(() => props.bindings ?? []);
// The failure description is the daemon's own words. "bindings not configured"
// answers a deployment with no binding store wired, and the operator can act on
// that, where a blanket "cannot reach archied" would be false about a daemon
// that answered.
const failureTitle = computed(() =>
props.failure?.kind === "unconfigured"
? errors.bindings.table.notConfigured
: errors.common.unresponsive,
);
</script>
<template>
<Empty v-if="props.failure">
<EmptyHeader>
<EmptyTitle>{{ failureTitle }}</EmptyTitle>
<EmptyDescription>{{ props.failure.message }}</EmptyDescription>
</EmptyHeader>
</Empty>
<Empty v-else-if="!loading && !rows.length">
<EmptyHeader>
<EmptyTitle>No bindings yet</EmptyTitle>
</EmptyHeader>
</Empty>
<Table v-else>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Event type</TableHead>
<TableHead>Workflow</TableHead>
<TableHead>Status</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
<template v-if="loading">
<TableRow v-for="row in 3" :key="row">
<TableCell v-for="col in 5" :key="col"
><Skeleton class="h-4 w-full"
/></TableCell>
</TableRow>
</template>
<template v-else>
<BindingRow
v-for="binding in rows"
:key="binding.id"
:binding="binding"
:event-types="props.eventTypes"
@edit="emit('edit', $event)"
@approve="emit('approve', $event)"
@pause="emit('pause', $event)"
@resume="emit('resume', $event)"
@delete="emit('delete', $event)"
/>
</template>
</TableBody>
</Table>
</template>
@@ -1,48 +0,0 @@
<script setup lang="ts">
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import type { Binding } from "@/pages/events/bindings/lib/binding-trigger";
/** Confirming a delete, and nothing else. A binding cannot be recovered, so
* the action is behind a dialog rather than a click. */
const props = defineProps<{ binding: Binding | null }>();
const emit = defineEmits<{ confirm: [binding: Binding]; cancel: [] }>();
// The binding is handed back by value so the confirmation stands on its own:
// the dialog closes on the click, and the caller must not have to re-read
// state that the close has already cleared.
function confirm(): void {
if (props.binding) emit("confirm", props.binding);
}
// Reka closes the dialog on the action click, so this is what tells the caller
// to forget the pending binding -- whether the delete happened or not.
function onOpenChange(open: boolean): void {
if (!open) emit("cancel");
}
</script>
<template>
<AlertDialog :open="props.binding !== null" @update:open="onOpenChange">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete "{{ props.binding?.name }}"?</AlertDialogTitle>
<AlertDialogDescription>It stops dispatching immediately and cannot be recovered.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" @click="confirm"
>Delete</AlertDialogAction
>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</template>
@@ -1,89 +0,0 @@
<script setup lang="ts">
import { ref, watch } from "vue";
import { api } from "@/lib/api";
import { errors } from "@/copy/errors";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Timestamp } from "@/components/ui/timestamp";
/**
* Dispatch ledger rows for one binding, capture or task. Each row links the
* binding, the capture it evaluated, and the task it started or the reason no
* task started. `omit` hides the column for the page's own entity.
*/
interface Dispatch {
binding_id: string;
binding_version: number;
capture_id: string;
task_id?: number;
reason?: string;
dispatched_at: string;
}
const props = defineProps<{
kind: "bindings" | "captures" | "tasks";
id: string;
}>();
const dispatches = ref<Dispatch[]>([]);
const failed = ref(false);
let generation = 0;
watch(
() => [props.kind, props.id],
async () => {
const current = ++generation;
failed.value = false;
try {
const res = await api.dispatches<Dispatch[]>(props.kind, props.id);
if (current !== generation) return;
dispatches.value = res;
} catch {
if (current !== generation) return;
dispatches.value = [];
failed.value = true;
}
},
{ immediate: true },
);
const captureLink = (id: string) => ({
path: "/events/inspector",
query: { capture: id },
});
</script>
<template>
<p v-if="failed" class="text-caption text-fg-muted">{{ errors.bindings.dispatchLinks.unavailable }}</p>
<ul v-else-if="dispatches.length" class="flex flex-col gap-1 text-caption">
<li
v-for="d in dispatches"
:key="d.binding_id + d.capture_id"
class="flex flex-wrap items-center gap-x-2 font-mono text-fg-muted"
>
<RouterLink
v-if="props.kind !== 'bindings'"
:to="'/events/bindings'"
class="hover:text-foreground"
>binding {{ d.binding_id.slice(0, 8) }} v{{ d.binding_version }}</RouterLink
>
<RouterLink
v-if="props.kind !== 'captures'"
:to="captureLink(d.capture_id)"
class="hover:text-foreground"
>capture {{ d.capture_id.slice(0, 8) }}</RouterLink
>
<template v-if="props.kind !== 'tasks'">
<RouterLink
v-if="d.task_id"
:to="`/tasks/${d.task_id}`"
class="text-foreground hover:underline"
>task #{{ d.task_id }}</RouterLink
>
<span v-else>{{ d.reason || errors.bindings.dispatchLinks.noTask }}</span>
</template>
<Timestamp :at="d.dispatched_at" />
</li>
</ul>
<Empty v-else-if="props.kind !== 'tasks'"><EmptyHeader><EmptyTitle>No dispatches yet.</EmptyTitle></EmptyHeader></Empty>
</template>
@@ -1,90 +0,0 @@
<script setup lang="ts">
import { ref, watch } from "vue";
import { api, type MappingFailure, type NoRunReason, type TriggerRun } from "@/lib/api";
import { errors } from "@/copy/errors";
import { Badge } from "@/components/ui/badge";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Timestamp } from "@/components/ui/timestamp";
/**
* The runs a trigger started or a stored delivery started, each linking the
* other two ends: which delivery, which trigger, which run.
*/
const props = defineProps<{
kind: "triggers" | "captures";
id: string;
}>();
const runs = ref<TriggerRun[]>([]);
const failed = ref(false);
let generation = 0;
watch(
() => [props.kind, props.id],
async () => {
const current = ++generation;
failed.value = false;
try {
const res =
props.kind === "triggers"
? await api.triggerDispatches(props.id)
: await api.captureDispatches(props.id);
if (current !== generation) return;
runs.value = res;
} catch {
if (current !== generation) return;
runs.value = [];
failed.value = true;
}
},
{ immediate: true },
);
const copy = errors.bindings.dispatchLinks;
const outcomeVariant = { started: "ok", failed: "danger", denied: "warn", disabled: "idle" } as const;
const failureText = (f: MappingFailure) =>
`${f.path} ${f.reason.replace("_", " ")}` + (f.value === undefined ? "" : ` (found ${JSON.stringify(f.value)})`);
const noRunText = (reason?: NoRunReason) => {
if (reason?.failures?.length) return `${reason.mapping}: ${reason.failures.map(failureText).join(", ")}`;
if (reason?.code === "access_denied") return `${copy.accessDenied} ${reason.workflow}`;
if (reason?.code === "workflow_disabled") return `${reason.workflow} ${copy.workflowDisabled}`;
return copy.noReason;
};
</script>
<template>
<p v-if="failed" class="text-caption text-fg-muted">{{ errors.bindings.dispatchLinks.unavailable }}</p>
<ul v-else-if="runs.length" class="flex flex-col gap-1 text-caption">
<li
v-for="r in runs"
:key="r.event_id + r.trigger_id"
class="flex flex-wrap items-center gap-x-2 font-mono text-fg-muted"
>
<RouterLink
v-if="props.kind === 'triggers'"
:to="{ path: '/events/inspector', query: { capture: r.event_id } }"
class="hover:text-foreground"
>capture {{ r.event_id.slice(0, 8) }}</RouterLink
>
<RouterLink
v-else
:to="'/events/bindings'"
class="hover:text-foreground"
>{{ r.trigger }}</RouterLink
>
<RouterLink v-if="r.run_id" :to="`/runs/${r.run_id}`" class="text-foreground hover:underline"
>run {{ r.run_id.slice(0, 8) }}</RouterLink
>
<template v-else>
<Badge :variant="outcomeVariant[r.outcome]">{{ r.outcome }}</Badge>
<span class="break-all">{{ noRunText(r.reason) }}</span>
</template>
<Timestamp v-if="r.created_at" :at="r.created_at" />
</li>
</ul>
<Empty v-else><EmptyHeader><EmptyTitle>No runs yet.</EmptyTitle></EmptyHeader></Empty>
</template>
-129
View File
@@ -1,129 +0,0 @@
<script setup lang="ts">
definePage({
name: "events-bindings",
meta: {
label: "Bindings",
description: "Bindings that decide which workflow an event starts.",
navPath: "/events",
section: "bindings",
},
});
import { errors } from "@/copy/errors";
import { Plus } from "@lucide/vue";
import { onMounted, ref } from "vue";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Section } from "@/components/ui/section";
import { useLiveResource } from "@/stores/session";
import BindingEditor from "@/pages/events/bindings/components/BindingEditor.vue";
import BindingsTable from "@/pages/events/bindings/components/BindingsTable.vue";
import DeleteBindingDialog from "@/pages/events/bindings/components/DeleteBindingDialog.vue";
import type { Binding, BindingDraft } from "@/pages/events/bindings/lib/binding-trigger";
import { useBindings } from "@/pages/events/bindings/lib/use-bindings";
/**
* Playbook bindings: tie an event type's mapping, an optional filter and a
* workflow together, with a draft -> pending_approval -> armed state machine so nothing
* self-arms. See docs/architecture/bindings.md and
* docs/prds/payload-field-mapping.md. Owner/Repo optionally pin a multi-repo
* deployment's dispatch target.
*/
const {
bindings,
mappings,
eventTypes,
workflows,
failure,
actionFailure,
saving,
saveFailure,
load,
resetSaveFailure,
save,
approve,
pause,
resume,
remove,
} = useBindings();
const editorOpen = ref(false);
// null is a new binding; a binding is an edit.
const editing = ref<Binding | null>(null);
const deleting = ref<Binding | null>(null);
useLiveResource(null, () => void load());
onMounted(load);
function startCreate(): void {
editing.value = null;
resetSaveFailure();
editorOpen.value = true;
}
function startEdit(binding: Binding): void {
editing.value = binding;
resetSaveFailure();
editorOpen.value = true;
}
async function handleSave(draft: BindingDraft): Promise<void> {
// The editor stays open on failure so the server's reason and the fields it
// is about are still on screen together.
if (await save(draft)) editorOpen.value = false;
}
async function handleDelete(binding: Binding): Promise<void> {
deleting.value = null;
await remove(binding);
}
</script>
<template>
<div>
<Section>
<template #action>
<Button v-if="!failure" size="sm" @click="startCreate">
<Plus data-icon="inline-start" />
New binding</Button>
</template>
<!-- A mutation that failed leaves the list on screen accurate, so its
failure sits beside the list rather than replacing it. -->
<Alert v-if="actionFailure" variant="destructive" class="mb-4">
<AlertTitle>{{ errors.bindings.page.actionNotApplied }}</AlertTitle>
<AlertDescription>{{ actionFailure.message }}</AlertDescription>
</Alert>
<BindingsTable
:bindings="bindings"
:event-types="eventTypes"
:failure="failure"
@edit="startEdit"
@approve="approve"
@pause="pause"
@resume="resume"
@delete="deleting = $event"
/>
</Section>
<BindingEditor
v-model:open="editorOpen"
:binding="editing"
:mappings="mappings"
:event-types="eventTypes"
:workflows="workflows"
:saving="saving"
:error="saveFailure"
@save="handleSave"
/>
<DeleteBindingDialog
:binding="deleting"
@confirm="handleDelete"
@cancel="deleting = null"
/>
</div>
</template>
@@ -1,258 +0,0 @@
/**
* The bindings vocabulary: the wire shapes the daemon returns, the draft the
* editor form edits, and the status ramp the list renders. Pure, so it reads
* (and would test) without the page's fetch wiring -- the same split
* binding-editor.jsx had from bindings.jsx in the Preact build.
*/
import type { EventType } from "@/pages/events/inspector/lib/event-types";
/**
* A binding as GET /api/bindings returns it. Signing belongs to the source the
* matcher names; unsigned is set when that source takes unsigned events.
*/
export interface Binding {
id: string;
name: string;
matcher?: { source?: string };
mapping_id?: string;
/** Optional CEL over the mapping's parameters; an excluded event is not dispatched. */
filter?: string;
workflow?: string;
/** A pin is a complete owner/repo pair or not a pin at all. */
owner?: string;
repo?: string;
/** The mapped parameter holding "owner/name", when the repository comes from the event. */
repo_param?: string;
/** Each workflow input from a mapped parameter or a constant. */
inputs?: Record<string, InputSource>;
status?: string;
version?: number;
unsigned?: boolean;
/** Set when the binding's org has disabled the workflow it targets. */
workflow_disabled?: boolean;
/** The newest ledger row: a task started, or why none was. */
last_outcome?: { task_id?: number; reason?: string; dispatched_at: string };
}
/** One workflow input's assignment on the wire. */
export interface InputSource {
param?: string;
value?: unknown;
}
/** A mapped parameter: its name and field type. */
export interface MappingField {
name: string;
type: string;
}
/** The fields of GET /api/mappings this page needs. */
export interface MappingOption {
id: string;
name: string;
event_type_id?: string;
fields?: MappingField[];
}
/** The mappings that belong to one event type, which are the ones a binding
* on that type can use. */
export function mappingsForEventType(
mappings: MappingOption[],
eventTypeId: string,
): MappingOption[] {
if (!eventTypeId) return [];
return mappings.filter((m) => m.event_type_id === eventTypeId);
}
/** One entry of GET /api/workflows' `definitions`. */
export interface WorkflowOption {
id: string;
name: string;
enabled?: boolean;
/** The inputs the workflow declares, by name. */
inputs?: Record<string, { type: string; required?: boolean }>;
/** none, optional or required; a workflow that declares none needs a repository. */
repository?: string;
}
/** Whether a binding for this workflow may name a repository. */
export function takesRepository(workflow?: WorkflowOption): boolean {
return (workflow?.repository ?? "required") !== "none";
}
/** A mapping's parameters a workflow input of this type can read. */
export function paramsForType(
fields: MappingField[],
type: string,
): MappingField[] {
return fields.filter(
(f) => type === "any" || f.type === "any" || f.type === type,
);
}
/** One input's assignment as the editor holds it: a parameter name, or the
* constant's text. */
interface InputDraft {
param: string;
value: string;
}
/**
* The constant an input's text stands for, in the input's declared type. Text
* that does not read as that type is returned as-is, so the server's type check
* names the mismatch rather than the editor guessing.
*/
export function constantValue(text: string, type: string): unknown {
switch (type) {
case "string":
return text;
case "number":
return text.trim() !== "" && !Number.isNaN(Number(text))
? Number(text)
: text;
case "bool":
return text === "true" ? true : text === "false" ? false : text;
default:
try {
return JSON.parse(text);
} catch {
return text;
}
}
}
/** The Badge variants a binding status maps onto. */
export type StatusKind = "ok" | "warn" | "idle";
const STATUS_LABELS: Record<string, string> = {
pending_approval: "pending approval",
armed: "armed",
paused: "paused",
};
const STATUS_KINDS: Record<string, StatusKind> = {
pending_approval: "warn",
armed: "ok",
paused: "idle",
};
/** A status the daemon grows later renders as itself in the neutral kind,
* rather than as an unlabelled pill. */
export function statusLabel(status?: string): string {
if (!status) return "unknown";
return STATUS_LABELS[status] ?? status;
}
export function statusKind(status?: string): StatusKind {
return STATUS_KINDS[status ?? ""] ?? "idle";
}
/**
* The editor's field state.
*/
export interface BindingDraft {
id: string | null;
name: string;
/** The event type the binding applies to; its source is the binding's. */
eventTypeId: string;
mappingId: string;
filter: string;
workflow: string;
owner: string;
repo: string;
repoParam: string;
inputs: Record<string, InputDraft>;
}
export function emptyDraft(): BindingDraft {
return {
id: null,
name: "",
eventTypeId: "",
mappingId: "",
filter: "",
workflow: "",
owner: "",
repo: "",
repoParam: "",
inputs: {},
};
}
export function draftFromBinding(
binding: Binding,
mappings: MappingOption[],
): BindingDraft {
const mapping = mappings.find((m) => m.id === binding.mapping_id);
return {
id: binding.id,
name: binding.name,
eventTypeId: mapping?.event_type_id || "",
mappingId: binding.mapping_id || "",
filter: binding.filter || "",
workflow: binding.workflow || "",
owner: binding.owner || "",
repo: binding.repo || "",
repoParam: binding.repo_param || "",
inputs: Object.fromEntries(
Object.entries(binding.inputs ?? {}).map(([name, src]) => [
name,
{
param: src.param ?? "",
value: src.param
? ""
: typeof src.value === "string"
? src.value
: JSON.stringify(src.value),
},
]),
),
};
}
/** The body POST /api/bindings and PATCH /api/bindings/{id} both accept. */
export function bindingPayload(
draft: BindingDraft,
eventTypes: EventType[],
workflow?: WorkflowOption,
): Record<string, unknown> {
const eventType = eventTypes.find((t) => t.id === draft.eventTypeId);
const declared = workflow?.inputs ?? {};
const inputs: Record<string, InputSource> = {};
for (const [name, spec] of Object.entries(declared)) {
const src = draft.inputs[name];
if (src?.param) inputs[name] = { param: src.param };
else if (src && src.value !== "")
inputs[name] = { value: constantValue(src.value, spec.type) };
}
const repository = takesRepository(workflow);
return {
name: draft.name,
matcher: { source: eventType?.source || "" },
mapping_id: draft.mappingId,
filter: draft.filter.trim(),
workflow: draft.workflow,
owner: repository && !draft.repoParam ? draft.owner : "",
repo: repository && !draft.repoParam ? draft.repo : "",
repo_param: repository ? draft.repoParam : "",
inputs,
};
}
/** The repo pin a row shows, or an em dash when the binding takes the
* single-configured-repo default. */
export function repoPin(binding: Binding): string {
if (binding.repo_param) return `from ${binding.repo_param}`;
return binding.owner && binding.repo
? `${binding.owner}/${binding.repo}`
: "–";
}
/** The event type a row shows: its mapping's. */
export function bindingEventType(
binding: Binding,
mappings: MappingOption[],
): string | undefined {
return mappings.find((m) => m.id === binding.mapping_id)?.event_type_id;
}
@@ -1,104 +0,0 @@
/**
* The bindings vocabulary on the binary: a binding is a trigger bound to an
* event type, so the wire shape is the trigger's. The status ramp is
* binding-draft.ts's.
*/
import type { EventType } from "@/pages/events/inspector/lib/event-types";
import type { Trigger, TriggerInput } from "@/lib/api";
/** A trigger bound to an event type. id is the trigger's id. */
export interface Binding {
id: string;
name: string;
source: string;
event_type_id?: string;
mapping_id?: string;
workflow_id?: string;
/** The workflow's name. */
workflow?: string;
status?: string;
/** The source takes deliveries with no verification. */
unsigned?: boolean;
}
export function bindingOfTrigger(trigger: Trigger): Binding {
return {
id: trigger.id,
name: trigger.name,
source: trigger.source ?? "",
event_type_id: trigger.event_type_id,
mapping_id: trigger.mapping_id,
workflow_id: trigger.workflow_id,
workflow: trigger.workflow,
status: trigger.status,
unsigned: trigger.unsigned,
};
}
/** The fields of GET /api/mappings this page needs. */
export interface MappingOption {
id: string;
name: string;
event_type_id?: string;
}
/** The mappings that belong to one event type, which are the ones a binding
* on that type can use. */
export function mappingsForEventType(
mappings: MappingOption[],
eventTypeId: string,
): MappingOption[] {
if (!eventTypeId) return [];
return mappings.filter((m) => m.event_type_id === eventTypeId);
}
/** A workflow a binding can start. */
export interface WorkflowOption {
id: string;
name: string;
}
/** The editor's field state. */
export interface BindingDraft {
/** The trigger's id when editing; null for a new binding. */
id: string | null;
name: string;
/** The event type the binding applies to; its source is the binding's. */
eventTypeId: string;
mappingId: string;
/** The id of the workflow the binding starts. */
workflow: string;
}
export function emptyDraft(): BindingDraft {
return { id: null, name: "", eventTypeId: "", mappingId: "", workflow: "" };
}
export function draftFromBinding(binding: Binding): BindingDraft {
return {
id: binding.id,
name: binding.name,
eventTypeId: binding.event_type_id || "",
mappingId: binding.mapping_id || "",
workflow: binding.workflow_id || "",
};
}
/** The body that saving a trigger takes. A saved binding waits for approval
* again. */
export function bindingPayload(
draft: BindingDraft,
eventTypes: EventType[],
): TriggerInput {
const eventType = eventTypes.find((t) => t.id === draft.eventTypeId);
return {
name: draft.name,
source_id: eventType?.source_id ?? "",
event_type_id: draft.eventTypeId,
mapping_id: draft.mappingId || undefined,
workflow_id: draft.workflow,
disabled: false,
pending: true,
};
}
@@ -1,125 +0,0 @@
import { ref } from "vue";
import { api, ApiError, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import type { EventType } from "@/pages/events/inspector/lib/event-types";
import {
bindingOfTrigger,
bindingPayload,
type Binding,
type BindingDraft,
type MappingOption,
type WorkflowOption,
} from "@/pages/events/bindings/lib/binding-trigger";
/**
* Why the page has nothing to show. "unconfigured" is a server that doesn't
* serve triggers (501/503), which reads very differently from one that
* answered badly.
*/
type LoadFailureKind = "unconfigured" | "failed";
export interface LoadFailure {
kind: LoadFailureKind;
message: string;
}
function failureFor(err: unknown): LoadFailure {
const message = describeError(err, errors.common.unknown);
const status = err instanceof ApiError ? err.status : undefined;
return {
kind: status === 501 || status === 503 ? "unconfigured" : "failed",
message,
};
}
/**
* The bindings page's data: the lists the table and the editor read, the load
* that fills them, and the mutations. Every mutation goes through api.* so the
* CSRF and Content-Type headers are sent.
*/
export function useBindings() {
// null means loading, [] means loaded and empty.
const bindings = ref<Binding[] | null>(null);
const mappings = ref<MappingOption[]>([]);
const eventTypes = ref<EventType[]>([]);
const workflows = ref<WorkflowOption[]>([]);
const failure = ref<LoadFailure | null>(null);
// A failed mutation is not a failed load: the list on screen is still
// accurate, so it keeps rendering and the failure lands beside it.
const actionFailure = ref<LoadFailure | null>(null);
const saving = ref(false);
const saveFailure = ref<string | null>(null);
async function load(): Promise<void> {
failure.value = null;
try {
const [triggers, m, w, t] = await Promise.all([
api.triggers(),
api.mappings<{ mappings?: MappingOption[] }>(),
api.workflowList(),
api.eventTypes<{ event_types?: EventType[] }>(),
]);
bindings.value = triggers.filter((x) => x.event_type_id).map(bindingOfTrigger);
mappings.value = m.mappings || [];
eventTypes.value = t.event_types || [];
workflows.value = w.map((d) => ({ id: d.id, name: d.name }));
} catch (err) {
failure.value = failureFor(err);
bindings.value = null;
}
}
function resetSaveFailure(): void {
saveFailure.value = null;
}
/** True when the binding was written, so the caller knows to close. */
async function save(draft: BindingDraft): Promise<boolean> {
saving.value = true;
saveFailure.value = null;
try {
const payload = bindingPayload(draft, eventTypes.value);
await (draft.id ? api.putTrigger(draft.id, payload) : api.createTrigger(payload));
await load();
return true;
} catch (err) {
saveFailure.value = describeError(err, errors.common.unknown);
return false;
} finally {
saving.value = false;
}
}
async function transition(command: (id: string) => Promise<unknown>, binding: Binding): Promise<void> {
actionFailure.value = null;
try {
await command(binding.id);
await load();
} catch (err) {
actionFailure.value = failureFor(err);
}
}
const approve = (binding: Binding) => transition(api.approveTrigger, binding);
const pause = (binding: Binding) => transition(api.pauseTrigger, binding);
const resume = (binding: Binding) => transition(api.resumeTrigger, binding);
const remove = (binding: Binding) => transition(api.deleteTrigger, binding);
return {
bindings,
mappings,
eventTypes,
workflows,
failure,
actionFailure,
saving,
saveFailure,
load,
resetSaveFailure,
save,
approve,
pause,
resume,
remove,
};
}
@@ -13,7 +13,6 @@ import { Badge } from "@/components/ui/badge";
import { Timestamp } from "@/components/ui/timestamp";
import { captureSignature } from "@/pages/events/inspector/lib/capture-signature";
import CapturePayload from "@/pages/events/inspector/components/CapturePayload.vue";
import TriggerRuns from "@/pages/events/bindings/components/TriggerRuns.vue";
import { selected } from "@/pages/events/inspector/lib/state";
/**
@@ -85,10 +84,6 @@ watch(selected, () => {
<div class="flex flex-col gap-5">
<CapturePayload label="Payload" :raw="selected.body" />
<CapturePayload label="Headers" :raw="selected.headers" />
<section class="flex flex-col gap-2">
<h3 class="text-caption font-medium tracking-[0.06em] text-fg-subtle uppercase">Runs</h3>
<TriggerRuns kind="captures" :id="selected.id" />
</section>
</div>
</CardContent>
</Card>
+6 -8
View File
@@ -1,8 +1,8 @@
/**
* The Events chain's counts.
*
* The three-step strip shows one number per step, and reads this. The three
* lists arrive from three separate loaded stores, so counting them inside the
* The chain strip shows one number per step, and reads this. The lists arrive
* from separate loaded stores, so counting them inside the
* page would put a second, quietly divergent answer next to the first. A count
* that could not be read at all is `undefined` --
* blank, never zero -- because "nothing arrived" and "the read failed" are
@@ -13,12 +13,11 @@
/** One count per tab id. A missing entry means that read did not answer. */
export type EventsCounts = Record<string, number | undefined>;
/** The three reads, narrowed to what counting needs so the page's `api` object
/** The two reads, narrowed to what counting needs so the page's `api` object
* fits and a test can stand in for it. */
export interface EventsCountReaders {
captures(limit?: number): Promise<unknown>;
mappings(): Promise<unknown>;
bindings(): Promise<unknown>;
}
/** One step's count: the read that answers it, and the list it counts. */
@@ -35,7 +34,7 @@ interface EventsCountSource {
// operator cannot act on.
const CAPTURE_PAGE = 100;
/** One source per step of the chain, in the order the strip reads them. */
/** One source per counted step of the chain, in the order the strip reads them. */
const COUNT_SOURCES: EventsCountSource[] = [
{
tab: "inspector",
@@ -43,12 +42,11 @@ const COUNT_SOURCES: EventsCountSource[] = [
read: (readers) => readers.captures(CAPTURE_PAGE),
},
{ tab: "mappings", key: "mappings", read: (readers) => readers.mappings() },
{ tab: "bindings", key: "bindings", read: (readers) => readers.bindings() },
];
/**
* loadEventCounts reads the three lists and counts each. One read failing
* leaves its own count blank and does not take the other two down with it: an
* loadEventCounts reads the lists and counts each. One read failing leaves its
* own count blank and does not take the others down with it: an
* unreachable capture service must not blank the mappings count.
*/
export async function loadEventCounts(
+2 -4
View File
@@ -22,7 +22,6 @@ const EVENTS_TABS: EventsTabSpec[] = [
{ id: "triggers", label: "Triggers", section: "events" },
{ id: "inspector", label: "Inspector", section: "captures" },
{ id: "mappings", label: "Mappings", section: "mappings" },
{ id: "bindings", label: "Bindings", section: "bindings" },
];
/**
@@ -63,14 +62,13 @@ export interface EventsStep {
/**
* The strip's own words for each surface. The URL names a panel for what it
* holds -- inspector, mappings, bindings; the strip names the same three panels
* for what the operator does to them. Only one vocabulary is on screen at a
* holds -- inspector, mappings; the strip names the same panels for what the
* operator does to them. Only one vocabulary is on screen at a
* time now, so the two can differ without the operator reading both.
*/
const STEP_COPY: Record<string, { label: string; hint: string }> = {
inspector: { label: "Capture", hint: "webhooks received" },
mappings: { label: "Map", hint: "field mappings" },
bindings: { label: "Bind", hint: "bindings to workflows" },
events: { label: "Events", hint: "events received" },
sources: { label: "Sources", hint: "sources" },
triggers: { label: "Triggers", hint: "triggers" },
@@ -32,7 +32,7 @@ import {
/**
* The mapping's own fields: the name it is saved under, the organisational
* source, and the captured event the payload and the preview resolve
* against. The hint is a note to a human, never a matcher; bindings decide which
* against. The hint is a note to a human, never a matcher; a trigger decides which
* events a mapping applies to.
*
* Each label is bound to its control by id so the association survives a click
-2
View File
@@ -13,7 +13,6 @@ import { useSystemHealth } from "@/lib/system-health";
import HealthCard from "@/dashboard/HealthCard.vue";
import NeedsAttentionCard from "@/dashboard/NeedsAttentionCard.vue";
import RecentRunsCard from "@/dashboard/RecentRunsCard.vue";
import SetupPanel from "@/dashboard/SetupPanel.vue";
/** What is wrong, what waits on you, then what ran. */
const { data: health, error, reload } = useSystemHealth();
@@ -23,7 +22,6 @@ const { data: health, error, reload } = useSystemHealth();
<h1 class="sr-only">Home</h1>
<div class="mx-auto grid max-w-5xl min-w-0 gap-4">
<HealthCard :health="health" :error="error" @retry="reload" />
<SetupPanel :setup="health?.setup ? { steps: health.setup } : undefined" />
<NeedsAttentionCard />
<RecentRunsCard />
</div>
-24
View File
@@ -1,24 +0,0 @@
<script setup lang="ts">
definePage({
name: "logs",
meta: {
label: "Logs",
description: "Daemon log by level and component.",
section: "logs",
},
});
import PageHeader from "@/base/PageHeader.vue";
import LogActions from "@/logs/LogActions.vue";
import LogStream from "@/logs/LogStream.vue";
import { useLogs } from "@/logs/state";
useLogs();
</script>
<template>
<PageHeader title="Logs">
<LogActions />
</PageHeader>
<LogStream />
</template>
+1 -1
View File
@@ -30,7 +30,7 @@ const error = ref("");
// Policies and models act on the caller's own org server-side, so an instance
// admin looking at another org is sent back rather than editing the wrong one.
const OWN_ORG_ONLY = ["/org/audit", "/org/policies", "/org/repositories", "/org/usage"];
const OWN_ORG_ONLY = ["/org/policies"];
const away = computed(() => !!org.value && org.value.id !== homeOrg.value);
const route = useRoute();
const router = useRouter();
-235
View File
@@ -1,235 +0,0 @@
<script setup lang="ts">
definePage({
name: "org-agents",
meta: {
section: "org_agents",
label: "Agents",
navPath: "/org",
description: "Execution identities, their permissions and commit author.",
},
});
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { Item, ItemGroup } from "@/components/ui/item";
import { Alert, AlertDescription } from "@/components/ui/alert";
import PageHeader from "@/base/PageHeader.vue";
import { storeToRefs } from "pinia";
import { onMounted, ref, watch } from "vue";
import { Bot, KeyRound, Plus, ShieldCheck, User } from "@lucide/vue";
import IdentityGrantsCard from "@/settings/IdentityGrantsCard.vue";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { MoreMenu } from "@/components/ui/more-menu";
import { Section } from "@/components/ui/section";
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { useOrgStore, type Identity } from "@/stores/org";
// Agent assignment is independent of membership roles.
const store = useOrgStore();
const { org } = storeToRefs(store);
store.watchIdentities();
const serves = ref(new Set<string>());
const error = ref("");
const busy = ref("");
async function load(): Promise<void> {
const id = org.value?.id;
serves.value = new Set();
if (!id) return;
try {
const response = await api.orgAgents<{ agents: Identity[] }>(id);
if (org.value?.id !== id) return;
serves.value = new Set(response.agents.map((agent) => agent.id));
error.value = "";
} catch (cause) {
if (org.value?.id === id) error.value = describeError(cause, errors.common.unknown);
}
}
onMounted(async () => {
try {
await store.loadOrg();
} catch (cause) {
error.value = describeError(cause, errors.common.unknown);
return;
}
await load();
});
watch(() => org.value?.id, () => void load());
const name = ref("");
const kind = ref<Identity["kind"]>("bot");
async function create(): Promise<void> {
if (await store.createIdentity(name.value.trim(), kind.value)) name.value = "";
}
const renaming = ref<string | null>(null);
const draftName = ref("");
function startRename(value: Identity) {
renaming.value = value.id;
draftName.value = value.display_name;
}
async function finishRename(value: Identity) {
// Enter and the blur that follows it both land here; only the first commits.
if (renaming.value !== value.id) return;
const next = draftName.value.trim();
renaming.value = null;
if (next && next !== value.display_name) await store.identityCommand(value, "rename", next);
}
async function assign(value: Identity): Promise<void> {
if (!org.value) return;
busy.value = value.id;
try {
await api.assignOrgAgent(org.value.id, value.id);
serves.value = new Set([...serves.value, value.id]);
error.value = "";
} catch (cause) {
error.value = describeError(cause, errors.common.unknown);
} finally {
busy.value = "";
}
}
const retiring = ref<Identity | null>(null);
async function retire() {
if (retiring.value) await store.identityCommand(retiring.value, "retire");
retiring.value = null;
}
const icons = { system: ShieldCheck, bot: Bot, service_account: KeyRound, user: User };
const lifecycle = { active: "idle", suspended: "warn", retired: "idle" } as const;
/** A bot or service account serves an org; people join one as members. */
const isAgent = (value: Identity) =>
value.kind === "bot" || value.kind === "service_account";
</script>
<template>
<div>
<PageHeader title="Agents" />
<Alert v-if="store.identityError || error" variant="destructive" class="mb-4"><AlertDescription>
{{ store.identityError || error }}
</AlertDescription></Alert>
<form v-if="store.identitiesAvailable" class="mb-4 flex flex-wrap items-center gap-2" @submit.prevent="create">
<Input v-model="name" class="max-w-64" placeholder="Display name" aria-label="Display name" required />
<Select v-model="kind">
<SelectTrigger class="w-44" aria-label="Kind"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="bot">Bot</SelectItem>
<SelectItem value="service_account">Service account</SelectItem>
<SelectItem value="user">User</SelectItem>
</SelectContent>
</Select>
<Button type="submit" size="sm" :disabled="!name.trim() || !!store.identityBusy"><Plus data-icon="inline-start" />Create</Button>
</form>
<Section>
<ItemGroup aria-label="Agents">
<Item v-for="value in store.identities" :key="value.id" as="li" variant="outline">
<span class="grid size-8 shrink-0 place-items-center rounded-md bg-secondary text-fg-muted">
<component :is="icons[value.kind]" class="size-4" aria-hidden="true" />
</span>
<div class="min-w-0 flex-1">
<Input
v-if="renaming === value.id"
v-model="draftName"
class="max-w-64"
aria-label="Display name"
autofocus
@keydown.enter="finishRename(value)"
@keydown.esc="renaming = null"
@blur="finishRename(value)"
/>
<p v-else class="truncate text-label font-medium" :class="value.lifecycle === 'retired' && 'text-fg-subtle'">
{{ value.display_name }}
</p>
<p class="text-caption text-fg-subtle">{{ value.kind.replace("_", " ") }}</p>
</div>
<Badge v-if="isAgent(value) && serves.has(value.id)" variant="outline" class="font-mono">{{ org?.id }}</Badge>
<Badge v-if="value.lifecycle !== 'active'" :variant="lifecycle[value.lifecycle]" class="capitalize">{{ value.lifecycle }}</Badge>
<div v-if="value.kind !== 'system' && value.lifecycle !== 'retired'" class="flex flex-wrap items-center gap-1">
<Tooltip v-if="isAgent(value) && !serves.has(value.id)">
<TooltipTrigger as-child>
<Button
variant="ghost"
size="sm"
:disabled="busy === value.id"
@click="assign(value)"
>Assign</Button
>
</TooltipTrigger>
<TooltipContent>Assign to {{ org?.name }}</TooltipContent>
</Tooltip>
<MoreMenu :label="`Actions for ${value.display_name || value.id}`">
<DropdownMenuItem :disabled="!!store.identityBusy" @select="startRename(value)">Rename</DropdownMenuItem>
<DropdownMenuItem
v-if="value.lifecycle === 'active'"
:disabled="!!store.identityBusy"
@select="store.identityCommand(value, 'suspend')"
>Suspend</DropdownMenuItem>
<DropdownMenuItem v-else :disabled="!!store.identityBusy" @select="store.identityCommand(value, 'reactivate')">Reactivate</DropdownMenuItem>
<DropdownMenuItem variant="destructive" :disabled="!!store.identityBusy" @select="retiring = value">Retire</DropdownMenuItem>
</MoreMenu>
</div>
</Item>
<li v-if="!store.identitiesLoaded" class="py-3 text-label text-fg-muted" role="status">Loading agents…</li>
<li v-else-if="!store.identitiesAvailable">
<Empty class="py-6">
<EmptyHeader>
<EmptyTitle>Instance identities are unavailable here</EmptyTitle>
</EmptyHeader>
</Empty>
</li>
<li v-else-if="!store.identities.length && !store.identityError">
<Empty class="py-6">
<EmptyHeader>
<EmptyTitle>No identities yet</EmptyTitle>
</EmptyHeader>
</Empty>
</li>
</ItemGroup>
</Section>
<IdentityGrantsCard />
<AlertDialog :open="!!retiring" @update:open="(open) => !open && (retiring = null)">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Retire {{ retiring?.display_name }}?</AlertDialogTitle>
<AlertDialogDescription>This cannot be undone.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction class="bg-destructive text-destructive-foreground" @click="retire">Retire</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</template>
-601
View File
@@ -1,601 +0,0 @@
<script setup lang="ts">
definePage({
name: "audit",
meta: {
section: "org_audit",
label: "Audit",
navPath: "/org",
description: "Settings, access, identity and runtime events.",
},
});
import UserReference from "@/org/UserReference.vue";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { ReadError } from "@/components/ui/read-error";
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import { errors } from "@/copy/errors";
import { describeError } from "@/lib/api";
import { useAccountsStore } from "@/accounts/accounts";
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 {
AlertDialog,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { DropdownMenuItem, DropdownMenuSeparator } from "@/components/ui/dropdown-menu";
import { Empty, EmptyContent, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { MoreMenu } from "@/components/ui/more-menu";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Section } from "@/components/ui/section";
import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
import { Timestamp } from "@/components/ui/timestamp";
import { useSessionStore } from "@/stores/session";
import { useSettingsStore } from "@/stores/settings";
import AuditDetail from "@/audit/AuditDetail.vue";
import AuditExportMenu from "@/audit/AuditExportMenu.vue";
import AuditFilters from "@/audit/AuditFilters.vue";
import {
badgeFor,
dedupeRecords,
emptyMessage,
hasFilters,
hasTarget,
queryFromRoute,
readSavedViews,
recordKey,
routeQueryFor,
targetDetail,
targetHref,
writeSavedViews,
type AuditQuery,
type AuditRecord,
type SavedAuditView,
} from "@/audit/audit";
import { useAuditStore } from "@/audit/store";
const audit = useAuditStore();
const settings = useSettingsStore();
const session = useSessionStore();
const accounts = useAccountsStore();
const route = useRoute();
const router = useRouter();
const { records, facets, loading, loadingMore, error, moreError, hasMore } = storeToRefs(audit);
const query = computed(() => queryFromRoute(route.query));
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, 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("");
const liveError = ref("");
const pending = ref<AuditRecord[]>([]);
const tableHost = ref<HTMLElement | null>(null);
let liveTimer: ReturnType<typeof setTimeout> | undefined;
let liveBusy = false;
let liveAgain = false;
let lastToken: string | null = null;
function reload(): void {
void audit.load(query.value);
}
function loadMore(): void {
void audit.loadMore();
}
onMounted(() => {
void settings.load();
if (!accounts.status) void accounts.load();
});
const stopLive = session.subscribe("audit-head", (data) => {
const token =
typeof (data as { token?: unknown })?.token === "string"
? (data as { token: string }).token
: null;
// The hub republishes the token on its poll; only a new head is a fetch. A
// payload without a token is an older server, so it always refetches.
if (token !== null && token === lastToken) return;
lastToken = token;
clearTimeout(liveTimer);
liveTimer = setTimeout(() => void pullLive(), 400);
});
// A reconnect replays the latest token; forgetting it makes the first frame
// after the connection refetch rather than skip what was missed.
watch(
() => session.connectionRevision,
() => {
lastToken = null;
},
);
onUnmounted(() => {
clearTimeout(liveTimer);
stopLive();
});
// A head token means something was written. Page one is re-read with the same
// filters; rows the operator has not scrolled past prepend, the rest wait.
async function pullLive(): Promise<void> {
if (liveBusy) {
liveAgain = true;
return;
}
if (loading.value || error.value) return;
liveBusy = true;
try {
const incoming = await audit.refresh();
liveError.value = "";
if (!incoming.length) return;
if (window.scrollY > 80) {
pending.value = dedupeRecords([...incoming, ...pending.value]);
status.value = `${pending.value.length} new ${pending.value.length === 1 ? "event" : "events"}`;
} else {
const merged = dedupeRecords([...incoming, ...pending.value]);
audit.prepend(merged);
pending.value = [];
status.value = `${merged.length} new ${merged.length === 1 ? "event" : "events"}`;
}
} catch (err) {
liveError.value = describeError(err, errors.audit.refresh);
status.value = errors.audit.refresh;
lastToken = null;
} finally {
liveBusy = false;
if (liveAgain) {
liveAgain = false;
void pullLive();
}
}
}
async function showPending(): Promise<void> {
const held = pending.value;
if (!held.length) return;
audit.prepend(held);
pending.value = [];
status.value = `${held.length} new ${held.length === 1 ? "event" : "events"}`;
window.scrollTo({ top: 0 });
await nextTick();
const rows = [...(tableHost.value?.querySelectorAll<HTMLElement>("[data-row-key]") ?? [])];
const first = rows.find((row) => row.dataset.rowKey === recordKey(held[0]));
if (first) first.focus({ preventScroll: true });
else tableHost.value?.focus({ preventScroll: true });
}
function changeFilters(patch: Partial<AuditQuery>): void {
const next: AuditQuery = { ...query.value, ...patch };
const keys = Object.keys(patch);
const location = { query: routeQueryFor(next), hash: route.hash };
if (keys.length === 1 && keys[0] === "q") void router.replace(location);
else void router.push(location);
}
function clearFilters(): void {
void router.push({ query: {}, hash: route.hash });
}
// Saved views are this browser's, keyed by the signed-in identity.
const views = ref<SavedAuditView[]>([]);
const identityId = computed(() => accounts.status?.user?.id ?? "");
watch(identityId, (id) => (views.value = readSavedViews(id)), { immediate: true });
const activeView = computed(() => {
const current = queryKey.value;
return views.value.find((view) => JSON.stringify(queryFromRoute(view.query)) === current) ?? null;
});
const ALL_VIEWS = "__all";
const selectedView = computed(() => activeView.value?.name ?? ALL_VIEWS);
function selectView(value: unknown): void {
if (typeof value !== "string") return;
if (value === ALL_VIEWS) {
clearFilters();
return;
}
const view = views.value.find((entry) => entry.name === value);
if (view) void router.push({ query: view.query, hash: route.hash });
}
const saveOpen = ref(false);
const viewName = ref("");
function openSaveView(): void {
viewName.value = activeView.value?.name ?? "";
saveOpen.value = true;
}
function saveView(): void {
const name = viewName.value.trim();
if (!name || !identityId.value) return;
if (views.value.some((view) => view.name === name) && activeView.value?.name !== name && !window.confirm(`Replace the saved view "${name}"?`)) return;
views.value = [
...views.value.filter((view) => view.name !== name),
{ name, query: routeQueryFor(query.value) },
].sort((a, b) => a.name.localeCompare(b.name));
writeSavedViews(identityId.value, views.value);
saveOpen.value = false;
}
function deleteView(): void {
const view = activeView.value;
if (!view || !identityId.value) return;
views.value = views.value.filter((entry) => entry.name !== view.name);
writeSavedViews(identityId.value, views.value);
}
// Revert restores the revision before the audited write. The settings store
// owns the draft, so the existing review sheet and save path do the write.
const revertOpen = ref(false);
const revertTarget = ref<{ record: AuditRecord; kind: string } | null>(null);
const revertError = ref("");
const reverting = ref(false);
watch(
queryKey,
() => {
pending.value = [];
revertError.value = "";
void audit.load(query.value);
},
{ immediate: true },
);
function resourceKind(record: AuditRecord): string {
const kind = record.target?.id;
if (!kind) return "";
return settings.genericResources.some((resource) => resource.kind === kind) ? kind : "";
}
function canRevert(record: AuditRecord): boolean {
return (record.detail?.version ?? 0) > 1 && !!resourceKind(record);
}
const revertUnsaved = computed(() => {
const target = revertTarget.value;
return !!target && settings.changesFor(target.kind).length > 0;
});
function askRevert(record: AuditRecord): void {
const kind = resourceKind(record);
if (!kind) return;
revertError.value = "";
revertTarget.value = { record, kind };
revertOpen.value = true;
}
function onRevertOpen(open: boolean): void {
revertOpen.value = open;
if (!open) {
revertTarget.value = null;
revertError.value = "";
}
}
async function confirmRevert(): Promise<void> {
const target = revertTarget.value;
if (!target || reverting.value) return;
const version = target.record.detail?.version ?? 0;
reverting.value = true;
revertError.value = "";
try {
await settings.loadResource(target.kind);
if (!settings.stateFor(target.kind).resource) {
revertError.value = errors.audit.revert.resourceLoad;
return;
}
const previous = (await settings.history(target.kind)).find(
(revision) => revision.version === version - 1,
);
if (!previous) {
revertError.value = errors.audit.revert.unavailable;
return;
}
settings.stageRestore(target.kind, previous.value);
revertTarget.value = null;
revertOpen.value = false;
} catch (err) {
revertError.value = describeError(err, errors.common.unknown);
} finally {
reverting.value = false;
}
}
// Retention is one instance-only control-plane resource, saved through the
// same versioned replace the settings pages use.
const RETENTION_KIND = "audit-retention";
const retentionOpen = ref(false);
const retentionHours = ref("");
const retentionOverrides = ref<Record<string, string>>({});
const retentionError = ref("");
const retentionSaving = ref(false);
const retentionState = settings.stateFor(RETENTION_KIND);
// The resource is instance-only; offering the item without it leaves a Save
// that can only fail.
const retentionAvailable = computed(() =>
settings.catalog.some((resource) => resource.kind === RETENTION_KIND),
);
// The kinds come from the server so this list cannot drift from the policy
// the sweep enforces.
const retentionKinds = computed(() => facets.value.retention_kinds ?? []);
const RETENTION_LABELS: Record<string, string> = {
agent_transcript: "Agent transcripts",
stage_start: "Stage starts",
agent_finish: "Agent finishes",
config_captured: "Configuration captures",
tool_call: "Tool calls",
log: "Log lines",
turn_completed: "Chat turns",
curator_run: "Curator runs",
curator_action: "Curator actions",
curator_error: "Curator errors",
job_run: "Job runs",
job_error: "Job errors",
};
function retentionLabel(kind: string): string {
return RETENTION_LABELS[kind] ?? kind;
}
function hoursFrom(value: unknown): number {
if (typeof value === "number")
return Number.isInteger(value) && value >= 0 ? value : 0;
if (typeof value !== "string") return 0;
const match = value.trim().match(/^(\d+)h$/);
return match ? Number(match[1]) : 0;
}
async function openRetention(): Promise<void> {
retentionOpen.value = true;
retentionError.value = "";
await settings.loadResource(RETENTION_KIND);
const resource = retentionState.resource;
if (!resource) return;
const value = resource.value as
| { runtime_event_retention?: unknown; event_retention?: Record<string, unknown> | null }
| undefined;
retentionHours.value = String(hoursFrom(value?.runtime_event_retention));
const overrides: Record<string, string> = {};
for (const [kind, hours] of Object.entries(value?.event_retention ?? {})) {
overrides[kind] = String(hoursFrom(hours));
}
retentionOverrides.value = overrides;
}
// retentionWindow validates one input and returns the stored "<n>h" form, or
// null when the operator left it blank (overrides only). It writes the error
// it finds so the caller only has to stop.
function retentionWindow(raw: string, label: string): string | null {
const text = String(raw ?? "").trim();
if (!text) return null;
const hours = Number(text);
if (!Number.isInteger(hours) || hours < 0) {
retentionError.value = `${label}: enter a whole number of hours.`;
return null;
}
if (hours > 0 && hours < 168) {
retentionError.value = `${label}: minimum 168 hours, or 0 to keep forever.`;
return null;
}
return `${hours}h`;
}
async function saveRetention(): Promise<void> {
if (retentionSaving.value) return;
retentionError.value = "";
if (!String(retentionHours.value).trim()) {
retentionError.value = "Enter the default retention in hours.";
return;
}
const fallback = retentionWindow(retentionHours.value, "Default retention");
if (!fallback) return;
const overrides: Record<string, string> = {};
for (const kind of retentionKinds.value) {
const raw = retentionOverrides.value[kind];
if (raw === undefined || !String(raw).trim()) continue;
const window = retentionWindow(raw, retentionLabel(kind));
if (!window) return;
overrides[kind] = window;
}
const state = retentionState;
if (!state.resource) {
retentionError.value = errors.audit.retention.unavailable;
return;
}
retentionSaving.value = true;
const value: { runtime_event_retention: string; event_retention?: Record<string, string> } = {
runtime_event_retention: fallback,
};
if (Object.keys(overrides).length) value.event_retention = overrides;
const saved = await settings.replace(RETENTION_KIND, value, state.resource.version);
retentionSaving.value = false;
if (saved) retentionOpen.value = false;
else retentionError.value = state.error || errors.audit.retention.save;
}
</script>
<template>
<div>
<PageHeader title="Audit">
<Select v-if="views.length" :model-value="selectedView" @update:model-value="selectView">
<SelectTrigger class="w-40" aria-label="Saved view"><SelectValue>{{ activeView?.name || "All events" }}</SelectValue></SelectTrigger>
<SelectContent>
<SelectItem :value="ALL_VIEWS">All events</SelectItem>
<SelectItem v-for="view in views" :key="view.name" :value="view.name">{{ view.name }}</SelectItem>
</SelectContent>
</Select>
<AuditExportMenu :query="query" />
<MoreMenu label="Audit actions">
<DropdownMenuItem :disabled="!identityId" @click="openSaveView">Save view…</DropdownMenuItem>
<DropdownMenuItem v-if="activeView" variant="destructive" @click="deleteView">Delete view</DropdownMenuItem>
<DropdownMenuSeparator v-if="retentionAvailable" />
<DropdownMenuItem v-if="retentionAvailable" @click="openRetention">Retention</DropdownMenuItem>
</MoreMenu>
</PageHeader>
<AuditFilters :query="query" :facets="facets" @change="changeFilters" />
<Alert v-if="liveError" variant="destructive" class="mb-3"><AlertDescription>{{ liveError }}</AlertDescription></Alert>
<div ref="tableHost" tabindex="-1" class="relative outline-none focus-visible:outline-2 focus-visible:outline-ring">
<div v-if="pending.length" class="sticky top-2 z-20 mb-2 flex justify-center">
<Button size="sm" @click="showPending">{{ pending.length }} new {{ pending.length === 1 ? "event" : "events" }}</Button>
</div>
<div v-if="loading" class="space-y-2" role="status" aria-label="Loading audit">
<Skeleton v-for="n in 6" :key="n" class="h-10 w-full" />
</div>
<ReadError v-else-if="error" :message="error" retry-label="Retry" @retry="reload" />
<Section v-else>
<DataTable :key="queryKey" :columns="columns" :rows="records" :row-key="recordKey" storage-key="audit">
<template #cell-event="{ row }">
<div class="min-w-0">
<div class="flex flex-wrap items-start gap-2">
<span class="min-w-0 break-words">{{ row.summary || `${row.category} ${row.action}` }}</span>
<Badge v-if="badgeFor(row)" :variant="badgeFor(row)!.variant">{{ badgeFor(row)!.label }}</Badge>
</div>
<p class="mt-0.5 text-caption text-fg-subtle sm:hidden">
<template v-if="hasTarget(row.target)">
<UserReference v-if="row.target.kind === 'identity'" :id="row.target.id" :name="row.target.label" />
<RouterLink v-else-if="targetHref(row.target)" :to="targetHref(row.target)" class="hover:underline" @click.stop>{{ row.target.label || row.target.id }}</RouterLink>
<span v-else>{{ row.target.label || row.target.id }}</span>
·
</template>
<UserReference :id="row.actor.id" :name="row.actor.name" :kind="row.actor.kind" />
·
<Timestamp :at="row.at" />
</p>
</div>
</template>
<template #cell-target="{ row }">
<UserReference v-if="row.target?.kind === 'identity'" :id="row.target.id" :name="row.target.label" />
<template v-else>
<RouterLink v-if="targetHref(row.target)" :to="targetHref(row.target)" class="hover:underline" @click.stop>{{ row.target.label || row.target.id }}</RouterLink>
<span v-else>{{ row.target?.label || row.target?.id }}</span>
<span class="block text-caption text-fg-subtle">{{ targetDetail(row.target) }}</span>
</template>
</template>
<template #cell-actor="{ row }">
<UserReference :id="row.actor.id" :name="row.actor.name" :kind="row.actor.kind" />
<span class="block text-caption text-fg-subtle">{{ row.actor.kind }}</span>
</template>
<template #cell-when="{ row }"><Timestamp :at="row.at" /></template>
<template #detail="{ row }">
<AuditDetail :record="row" :can-revert="canRevert(row)" @revert="askRevert(row)" />
</template>
<template #empty>
<Empty>
<EmptyHeader>
<EmptyTitle>{{ emptyMessage(query) }}</EmptyTitle>
</EmptyHeader>
<EmptyContent v-if="hasFilters(query)">
<Button variant="outline" size="sm" @click="clearFilters">Clear filters</Button>
</EmptyContent>
</Empty>
</template>
</DataTable>
<div v-if="hasMore" class="mt-3 flex justify-center">
<Button variant="outline" size="sm" :disabled="loadingMore" @click="loadMore"><Spinner v-if="loadingMore" data-icon="inline-start" />Load older</Button>
</div>
<Alert v-if="moreError" variant="destructive" class="mt-2"><AlertDescription>{{ moreError }}</AlertDescription></Alert>
</Section>
</div>
<p class="sr-only" role="status">{{ status }}</p>
<AlertDialog :open="revertOpen" @update:open="onRevertOpen">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Revert this change?</AlertDialogTitle>
<AlertDialogDescription v-if="revertUnsaved">Unsaved changes to this resource will be replaced.</AlertDialogDescription>
<AlertDialogDescription v-else>The previous version opens for review before saving.</AlertDialogDescription>
</AlertDialogHeader>
<Alert v-if="revertError" variant="destructive"><AlertDescription>{{ revertError }}</AlertDescription></Alert>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<Button :disabled="reverting" @click="confirmRevert"><Spinner v-if="reverting" data-icon="inline-start" />Revert</Button>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Dialog v-model:open="saveOpen">
<DialogContent>
<DialogHeader>
<DialogTitle>Save view</DialogTitle>
</DialogHeader>
<div class="grid gap-1.5">
<Label for="audit-view-name">Name</Label>
<Input id="audit-view-name" v-model="viewName" @keydown.enter="saveView" />
</div>
<DialogFooter>
<Button variant="ghost" @click="saveOpen = false">Cancel</Button>
<Button :disabled="!viewName.trim() || !identityId" @click="saveView">Save</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog v-model:open="retentionOpen">
<DialogContent>
<DialogHeader>
<DialogTitle>Audit retention</DialogTitle>
<DialogDescription>Older runtime events are deleted hourly. Settings, access and identity records are kept, and each kind can keep its own window.</DialogDescription>
</DialogHeader>
<div class="grid gap-1.5">
<Label for="audit-retention-hours">Default runtime event retention (hours)</Label>
<Input id="audit-retention-hours" v-model="retentionHours" type="number" min="0" step="1" class="w-32" />
<p class="text-caption text-fg-subtle">0 keeps them forever. Minimum 168 hours.</p>
</div>
<div v-if="retentionKinds.length" class="grid gap-2">
<p class="text-label">Per-kind overrides</p>
<div v-for="kind in retentionKinds" :key="kind" class="flex items-center justify-between gap-2">
<Label :for="`audit-retention-${kind}`">{{ retentionLabel(kind) }}</Label>
<Input
:id="`audit-retention-${kind}`"
v-model="retentionOverrides[kind]"
type="number"
min="0"
step="1"
placeholder="inherit"
class="w-28"
/>
</div>
<p class="text-caption text-fg-subtle">Blank uses the default. Minimum 168 hours, or 0 to keep forever.</p>
</div>
<Alert v-if="retentionError || retentionState.error" variant="destructive"><AlertDescription>{{ retentionError || retentionState.error }}</AlertDescription></Alert>
<DialogFooter>
<Button variant="ghost" @click="retentionOpen = false">Cancel</Button>
<Button :disabled="retentionSaving || retentionState.loading || !retentionState.resource" @click="saveRetention"><Spinner v-if="retentionSaving" data-icon="inline-start" />Save</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</template>
-225
View File
@@ -1,225 +0,0 @@
<script setup lang="ts">
definePage({
name: "org-channels",
meta: {
label: "Channels",
navPath: "/org",
description: "Chat channels.",
section: "channels",
},
});
import { Alert, AlertDescription } from "@/components/ui/alert";
import ApplyStatusRows from "@/settings/ApplyStatusRows.vue";
import HistoryLink from "@/settings/HistoryLink.vue";
import { computed, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import PageHeader from "@/base/PageHeader.vue";
import { Button } from "@/components/ui/button";
import { Field, FieldContent, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import {
TagsInput,
TagsInputInput,
TagsInputItem,
TagsInputItemDelete,
TagsInputItemText,
} from "@/components/ui/tags-input";
import { errors } from "@/copy/errors";
import { api, describeError } from "@/lib/api";
import OptionSelect from "@/components/OptionSelect.vue";
import { useOrgStore, type Identity } from "@/stores/org";
import { Section } from "@/components/ui/section";
import { resourcesForPage, useSettingsStore } from "@/stores/settings";
import { useLiveResource, useSessionStore } from "@/stores/session";
const KIND = "channel-settings";
interface ChannelSettings {
operator: string;
show_tool_calls: boolean;
max_steps: number;
models: string[] | null;
allowed_user_ids: number[] | null;
rate_limit: { window: string; max_requests: number };
unrestricted_filesystem: boolean;
workspace: string;
agent: string;
}
/** What the messaging service reports about a running channel. */
interface ChannelStatus {
id?: string;
state?: string;
detail?: string;
}
const store = useSettingsStore();
const { catalog, catalogError } = storeToRefs(store);
const resources = computed(() => resourcesForPage(catalog.value, "channels"));
const form = computed(() => store.formFor(KIND));
const chat = computed(() => store.draftValue(KIND) as ChannelSettings | undefined);
const error = computed(() => store.pageErrorFor(KIND));
// The instance's own bot, its connection and the session defaults are
// Instance settings; another org runs its own bot as one of its agents, with
// its token bound as a credential, and chooses here which agent answers.
const session = useSessionStore();
const router = useRouter();
const identities = useOrgStore();
const agents = ref<Identity[]>([]);
const agentsError = ref("");
let agentsGeneration = 0;
async function loadAgents(): Promise<void> {
const current = ++agentsGeneration;
agentsError.value = "";
try {
await identities.loadOrg();
const response = await api.orgAgents<{ agents: Identity[] }>(identities.homeOrg);
if (current !== agentsGeneration) return;
agents.value = response.agents.filter((agent) => agent.lifecycle === "active");
} catch (cause) {
if (current !== agentsGeneration) return;
agentsError.value = describeError(cause, errors.common.unknown);
}
}
const agentOptions = computed(() => {
const current = chat.value?.agent ?? "";
const options = agents.value.map((agent) => ({ value: agent.id, label: agent.display_name }));
return current && !agents.value.some((agent) => agent.id === current) ? [{ value: current, label: errors.channels.agents.unknown(current), disabled: true }, ...options] : options;
});
const statuses = ref<ChannelStatus[]>([]);
// A failed status read keeps the last known badges and flags the error, so a
// transient failure neither clears every badge nor passes as "all idle".
const statusError = ref(false);
let statusGeneration = 0;
async function loadStatus() {
const current = ++statusGeneration;
try {
statuses.value = (await api.channels<{ channels?: ChannelStatus[] }>())?.channels ?? [];
if (current !== statusGeneration) return;
statusError.value = false;
} catch {
if (current !== statusGeneration) return;
statusError.value = true;
}
}
useLiveResource(null, () => void loadStatus());
onMounted(async () => {
await session.loadCapabilities();
if (session.systemOrg) {
await router.replace("/settings/channels");
return;
}
await Promise.all([loadStatus(), store.load(), loadAgents()]);
});
// Running state comes only from the messaging service's report; a channel it
// does not mention shows none rather than one guessed from its settings.
function statusOf(id: string) {
const state = statuses.value.find((s) => s.id === id)?.state;
if (!state) return undefined;
if (state === "running") return undefined;
if (state === "failed") return { label: "Failed", tone: "danger" } as const;
if (state === "degraded") return { label: "Degraded", tone: "warn" } as const;
return { label: state[0]!.toUpperCase() + state.slice(1), tone: "idle" } as const;
}
// A channel is set up once its enabling field is filled in, the rule the
// daemon applies when it decides what to start.
const configured = computed(() => ({
telegram: !!chat.value?.agent,
}));
const opened = reactive({ telegram: false });
const shown = (id: keyof typeof opened) => configured.value[id] || opened[id];
const channels = [
{ id: "telegram", title: "Telegram" },
] as const;
const allowedUsers = computed(() => (chat.value?.allowed_user_ids ?? []).map(String));
// Tag lists are edited in script, so they go through the form's API rather
// than a field's handleChange.
function setAllowedUsers(ids: string[]) {
form.value?.api.setFieldValue("allowed_user_ids", ids.filter((id) => /^\d+$/.test(id)).map(Number));
}
</script>
<template>
<div>
<PageHeader title="Channels">
<HistoryLink :kinds="resources.map((r) => r.kind)" />
</PageHeader>
<ApplyStatusRows :kind="KIND" class="mb-4" />
<Alert v-if="catalogError || error" variant="destructive" class="mb-4"><AlertDescription>
{{ catalogError || error }}
</AlertDescription></Alert>
<Alert v-if="statusError" variant="destructive" class="mb-4"><AlertDescription>
{{ errors.channels.status.load }}
<Button variant="link" size="xs" @click="loadStatus">Retry</Button>
</AlertDescription></Alert>
<template v-if="chat">
<Section v-for="channel in channels" :key="channel.id" :title="channel.title" :class="!shown(channel.id) && 'gap-0'">
<template #action>
<div class="flex items-center gap-2">
<Badge v-if="configured[channel.id] && statusOf(channel.id)" :variant="statusOf(channel.id)!.tone">{{
statusOf(channel.id)!.label
}}</Badge>
<Button v-if="!configured[channel.id] && !opened[channel.id]" variant="outline" size="sm" @click="opened[channel.id] = true">Set up</Button>
</div>
</template>
<FieldGroup v-if="form && shown(channel.id) && channel.id === 'telegram'" class="@container/field-group">
<form.Field v-slot="{ field }" name="agent">
<Field orientation="responsive">
<FieldContent><FieldLabel for="channel-agent">Runs as</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<OptionSelect
id="channel-agent"
:model-value="field.state.value"
:options="agentOptions"
aria-label="Agent"
placeholder="Choose an agent"
class="w-44"
@update:model-value="field.handleChange"
/>
</div>
<Alert v-if="agentsError" variant="destructive"><AlertDescription>{{ agentsError }} <Button variant="link" size="xs" @click="loadAgents">Retry</Button></AlertDescription></Alert>
</Field>
</form.Field>
<Field orientation="responsive">
<FieldContent>
<FieldLabel id="channel-allowed-label">Allowed users</FieldLabel>
<FieldDescription>Everyone else is ignored.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<div role="group" aria-labelledby="channel-allowed-label" class="contents"><TagsInput :model-value="allowedUsers" class="font-mono" @update:model-value="(ids) => setAllowedUsers(ids.map(String))">
<TagsInputItem v-for="id in allowedUsers" :key="id" :value="id">
<TagsInputItemText />
<TagsInputItemDelete />
</TagsInputItem>
<TagsInputInput placeholder="Add user ID" aria-label="Allowed users" />
</TagsInput></div>
</div>
</Field>
<form.Field v-slot="{ field }" name="show_tool_calls">
<Field orientation="responsive">
<FieldContent><FieldLabel for="channel-show-tools">Show tool calls</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Switch id="channel-show-tools" :model-value="field.state.value" aria-label="Show tool calls" @update:model-value="field.handleChange" />
</div>
</Field>
</form.Field>
</FieldGroup>
</Section>
</template>
</div>
</template>
-1
View File
@@ -43,7 +43,6 @@ import UserReference from "@/org/UserReference.vue";
* attributable without leaving the page.
*/
const allAreas = [
{ title: "Execution identities", to: "/org/agents" },
{ title: "Extensions", to: "/settings/extensions" },
{ title: "Workspaces", to: "/org/workspaces" },
{ title: "Models", to: "/settings/models" },
-129
View File
@@ -1,129 +0,0 @@
<script setup lang="ts">
definePage({
name: "org-issue-routing",
meta: {
section: "org_work_intake",
label: "Issue routing",
navPath: "/org",
description: "Which workflow an issue runs by its labels.",
},
});
import { ArrowDown, ArrowUp, Trash2 } from "@lucide/vue";
import { computed, onMounted, ref } from "vue";
import PageHeader from "@/base/PageHeader.vue";
import OptionSelect from "@/components/OptionSelect.vue";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Input } from "@/components/ui/input";
import { Section } from "@/components/ui/section";
import { SettingRow } from "@/components/ui/setting-row";
import { useSettingsStore } from "@/stores/settings";
import { useWorkflowsStore } from "@/stores/workflows";
import ApplyStatusRows from "@/settings/ApplyStatusRows.vue";
import HistoryLink from "@/settings/HistoryLink.vue";
import KindGate from "@/settings/KindGate.vue";
const KIND = "intake-routes";
interface IntakeRoutes {
rules: { label: string; workflow: string }[];
default: string;
}
const store = useSettingsStore();
const workflows = useWorkflowsStore();
onMounted(store.load);
const form = computed(() => store.formFor(KIND));
const routes = computed(() => store.draftValue(KIND) as IntakeRoutes | undefined);
const rules = computed(() => routes.value?.rules ?? []);
const error = computed(() => store.catalogError || store.pageErrorFor(KIND));
const options = computed(() => workflows.collection.definitions.map(({ id }) => ({ value: id, label: id })));
const label = ref("");
const workflow = ref("");
const canAdd = computed(() => label.value.trim() !== "" && workflow.value !== "");
function edit(next: Partial<IntakeRoutes>) {
if (routes.value) store.setDraftValue(KIND, { ...routes.value, ...next });
}
function add() {
if (!canAdd.value) return;
edit({ rules: [...rules.value, { label: label.value.trim(), workflow: workflow.value }] });
label.value = "";
}
function remove(index: number) {
edit({ rules: rules.value.filter((_, i) => i !== index) });
}
function move(index: number, by: -1 | 1) {
const next = [...rules.value];
const [rule] = next.splice(index, 1);
next.splice(index + by, 0, rule!);
edit({ rules: next });
}
</script>
<template>
<div>
<PageHeader title="Issue routing"><HistoryLink :kinds="[KIND]" /></PageHeader>
<ApplyStatusRows :kind="KIND" class="mb-4" />
<Alert v-if="error" variant="destructive" class="mb-4"><AlertDescription>{{ error }}</AlertDescription></Alert>
<KindGate v-if="!form" :kind="KIND" />
<template v-else>
<Section title="Rules">
<form class="mb-4 flex flex-wrap items-center gap-2" @submit.prevent="add">
<Input v-model="label" aria-label="Label" placeholder="Label" class="max-w-48 font-mono" />
<OptionSelect v-model="workflow" :options="options" aria-label="Workflow" placeholder="Workflow" class="w-44" />
<Button type="submit" :disabled="!canAdd">Add rule</Button>
</form>
<Empty v-if="!rules.length"><EmptyHeader><EmptyTitle>No rules</EmptyTitle></EmptyHeader></Empty>
<ol v-else class="divide-y divide-border border-y border-border">
<li v-for="(_, i) in rules" :key="i" class="flex flex-wrap items-center gap-2 py-2">
<form.Field v-slot="{ field }" :name="`rules[${i}].label`">
<Input
:model-value="field.state.value"
:aria-label="`Label of rule ${i + 1}`"
class="max-w-48 font-mono"
@blur="field.handleBlur"
@update:model-value="field.handleChange"
/>
</form.Field>
<form.Field v-slot="{ field }" :name="`rules[${i}].workflow`">
<OptionSelect
:model-value="field.state.value"
:options="options"
:aria-label="`Workflow of rule ${i + 1}`"
class="w-44"
@update:model-value="field.handleChange"
/>
</form.Field>
<div class="ml-auto flex items-center">
<Button variant="ghost" size="icon" :disabled="i === 0" :aria-label="`Move rule ${i + 1} up`" @click="move(i, -1)"><ArrowUp /></Button>
<Button variant="ghost" size="icon" :disabled="i === rules.length - 1" :aria-label="`Move rule ${i + 1} down`" @click="move(i, 1)"><ArrowDown /></Button>
<Button variant="ghost" size="icon" :aria-label="`Remove rule ${i + 1}`" @click="remove(i)"><Trash2 /></Button>
</div>
</li>
</ol>
</Section>
<Section title="Default">
<SettingRow label="Default workflow" for="routing-default" class="border-t-0 py-0">
<form.Field v-slot="{ field }" name="default">
<OptionSelect
id="routing-default"
:model-value="field.state.value"
:options="options"
aria-label="Default workflow"
class="w-44"
@update:model-value="field.handleChange"
/>
</form.Field>
</SettingRow>
</Section>
</template>
</div>
</template>
-360
View File
@@ -1,360 +0,0 @@
<script setup lang="ts">
definePage({
name: "org-repositories",
meta: {
section: "org_work_intake",
label: "Repositories",
navPath: "/org",
description: "Repository connections, access checks and execution policies.",
},
});
import { Alert, AlertDescription } from "@/components/ui/alert";
import ApplyStatusRows from "@/settings/ApplyStatusRows.vue";
import { computed, onMounted, ref, watch } from "vue";
import { storeToRefs } from "pinia";
import { Plus } from "@lucide/vue";
import PageHeader from "@/base/PageHeader.vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Field, FieldContent, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { SettingRow } from "@/components/ui/setting-row";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { useOrgStore, type Identity } from "@/stores/org";
import {
NumberField,
NumberFieldContent,
NumberFieldDecrement,
NumberFieldIncrement,
NumberFieldInput,
} from "@/components/ui/number-field";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import {
TagsInput,
TagsInputInput,
TagsInputItem,
TagsInputItemDelete,
TagsInputItemText,
} from "@/components/ui/tags-input";
import { resourcesForPage, useSettingsStore } from "@/stores/settings";
import CardAccordion from "@/settings/CardAccordion.vue";
import CommandListEditor from "@/settings/CommandListEditor.vue";
import DraftHint from "@/settings/DraftHint.vue";
import HistoryLink from "@/settings/HistoryLink.vue";
import KindGate from "@/settings/KindGate.vue";
const KIND = "repository-policies";
interface Repo {
connection: string;
owner: string;
name: string;
base: string;
ecosystem: string;
gate: string[][] | null;
tooling: string[][] | null;
preflight: string[][] | null;
protect: string[] | null;
test_glob: string;
persistent_storage: boolean;
instructions?: string;
max_retries: number;
allow_concurrent: boolean;
}
const store = useSettingsStore();
const { catalog, catalogError } = storeToRefs(store);
const organisation = useOrgStore();
const agents=ref<Identity[]>([]);
const agentError=ref("");
let agentsGeneration=0;
onMounted(async()=>{
void store.load();
const current=++agentsGeneration;
try {
await organisation.loadOrg();
const response=await api.orgAgents<{agents:Identity[]}>(organisation.homeOrg);
if(current!==agentsGeneration)return;
agents.value=response.agents.filter((agent)=>agent.lifecycle==="active");
} catch(cause) {if(current===agentsGeneration)agentError.value=describeError(cause, errors.common.unknown)}
});
const resources = computed(() => resourcesForPage(catalog.value, "repositories"));
const form = computed(() => store.formFor(KIND));
const repos = computed(() => (store.draftValue(KIND) ?? []) as Repo[]);
const connections = computed(() => (store.draftValue("forge-connections") ?? []) as { id: string; name: string }[]);
const error = computed(() => store.pageErrorFor(KIND));
const ecosystems = ["go", "python", "node", "rust", "custom"];
const newRepo = ref("");
const open = ref("0");
const unsaved = computed(() => store.changesFor(KIND).length > 0);
// The repository list is the whole document, so adding and removing rebuild it.
function addRepo() {
if (unsaved.value) return;
const [owner, name] = newRepo.value.trim().split("/");
if (!form.value || !owner || !name) return;
const next: Repo[] = [
...repos.value,
{
owner, name, connection: "", base: "main", ecosystem: "go", gate: [], tooling: null, preflight: null, protect: null,
test_glob: "", persistent_storage: false, max_retries: 0, allow_concurrent: false,
},
];
store.setDraftValue(KIND, next);
newRepo.value = "";
open.value = String(next.length - 1);
}
function removeRepo(index: number) {
store.setDraftValue(KIND, repos.value.filter((_, i) => i !== index));
}
interface AccessCheck { verified?: boolean; account?: string; base_branch?: string; operations?: string[]; message?: string }
const checkAgent=ref("");
const checking=ref("");
const results=ref<Record<string,AccessCheck>>({});
watch([checkAgent,()=>JSON.stringify(repos.value)],()=>{results.value={}});
// Where a repository stands: a missing connection is known from the draft, the
// rest only after an access check.
function readiness(repo: Repo): { variant: "ok" | "warn" | "danger"; label: string } | null {
if (!repo.connection || !connections.value.some((connection) => connection.id === repo.connection)) return { variant: "warn", label: "No connection" };
const result = results.value[`${repo.owner}/${repo.name}`];
if (!result) return null;
return result.verified ? { variant: "ok", label: "Verified" } : { variant: "danger", label: errors.settings.repos.checkFailed };
}
async function checkAccess(repo:Repo):Promise<void>{
if(unsaved.value || !checkAgent.value || checking.value)return;
const key=`${repo.owner}/${repo.name}`;
const input=JSON.stringify([repo,checkAgent.value]);
checking.value=key;
delete results.value[key];
try {
const result=await api.checkRepository<AccessCheck>({owner:repo.owner,repository:repo.name,identity_id:checkAgent.value});
if(input===JSON.stringify([repo,checkAgent.value]))results.value[key]=result;
}catch(cause){
if(input===JSON.stringify([repo,checkAgent.value]))results.value[key]={message:describeError(cause, errors.common.unknown)};
}finally{checking.value=""}
}
</script>
<template>
<div>
<PageHeader title="Repositories">
<HistoryLink :kinds="resources.map((r) => r.kind)" />
</PageHeader>
<ApplyStatusRows v-for="resource in resources" :key="resource.kind" :kind="resource.kind" class="mb-4" />
<Alert v-if="catalogError || error" variant="destructive" class="mb-4"><AlertDescription>{{ catalogError || error }}</AlertDescription></Alert>
<KindGate v-if="!form" :kind="KIND" />
<template v-if="form">
<CardAccordion v-model:open="open" :items="repos" :title="(r) => `${r.owner}/${r.name}`" remove-label="Remove" mono @remove="removeRepo">
<template #aside="{ item }">
<Badge v-if="readiness(item as Repo)" :variant="readiness(item as Repo)!.variant">{{ readiness(item as Repo)!.label }}</Badge>
</template>
<template #default="{ item: repo, index: i }">
<FieldGroup class="@container/field-group">
<Field orientation="responsive">
<FieldContent><FieldLabel>Connection</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<form.Field v-slot="{ field }" :name="`${i}.connection`">
<Select :model-value="field.state.value" @update:model-value="field.handleChange">
<SelectTrigger class="w-64" :aria-label="`Connection for ${repo.name}`"><SelectValue placeholder="Choose a connection" /></SelectTrigger>
<SelectContent>
<SelectItem v-for="connection in connections" :key="connection.id" :value="connection.id">{{ connection.name || connection.id }}</SelectItem>
<SelectItem v-if="repo.connection && !connections.some((connection) => connection.id === repo.connection)" :value="repo.connection" disabled>Unavailable connection</SelectItem>
</SelectContent>
</Select>
</form.Field>
</div>
</Field>
<Field orientation="responsive">
<FieldContent><FieldLabel>Check access</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<div class="grid gap-2">
<Select v-model="checkAgent">
<SelectTrigger class="w-64" :aria-label="`Check ${repo.name} access as`"><SelectValue placeholder="Choose an agent" /></SelectTrigger>
<SelectContent><SelectItem v-for="agent in agents" :key="agent.id" :value="agent.id">{{ agent.display_name }}</SelectItem></SelectContent>
</Select>
<Button type="button" variant="outline" class="w-fit" :disabled="!checkAgent || !repo.connection || unsaved || !!checking" @click="checkAccess(repo)">{{checking===`${repo.owner}/${repo.name}` ? "Checking…" : "Check access"}}</Button>
<p v-if="unsaved" class="text-caption text-fg-muted">Save changes before checking access.</p>
<Alert v-if="agentError" variant="destructive"><AlertDescription>{{agentError}}</AlertDescription></Alert>
<p v-if="results[`${repo.owner}/${repo.name}`]" role="status" class="text-caption" :class="results[`${repo.owner}/${repo.name}`].verified ? 'text-ok' : 'text-danger'">
<template v-if="results[`${repo.owner}/${repo.name}`].verified">{{ results[`${repo.owner}/${repo.name}`].operations?.join(" · ") }} as {{ results[`${repo.owner}/${repo.name}`].account }}</template>
<template v-else>{{ results[`${repo.owner}/${repo.name}`].message }}</template>
</p>
</div>
</div>
</Field>
<form.Field v-slot="{ field }" :name="`${i}.base`">
<Field orientation="responsive">
<FieldContent><FieldLabel :for="`repo-${i}-base`">Base branch</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input :id="`repo-${i}-base`" :model-value="field.state.value" class="max-w-56 font-mono" @blur="field.handleBlur" @update:model-value="field.handleChange" />
<DraftHint :kind="KIND" :path="`${i}.base`" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${i}.ecosystem`">
<Field orientation="responsive">
<FieldContent><FieldLabel>Ecosystem</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Select :model-value="field.state.value" @update:model-value="field.handleChange">
<SelectTrigger class="w-40 font-mono" :aria-label="`Ecosystem for ${repo.name}`"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem v-for="e in ecosystems" :key="e" :value="e">{{ e }}</SelectItem>
</SelectContent>
</Select>
<DraftHint :kind="KIND" :path="`${i}.ecosystem`" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${i}.gate`">
<Field orientation="responsive">
<FieldContent>
<FieldLabel>Quality gate</FieldLabel>
<FieldDescription>Last command runs the tests.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<CommandListEditor :model-value="field.state.value" label="Gate" empty-text="No gate." @update:model-value="field.handleChange" />
<DraftHint :kind="KIND" :path="`${i}.gate`" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${i}.tooling`">
<Field orientation="responsive">
<FieldContent>
<FieldLabel>Tooling</FieldLabel>
<FieldDescription>Installs the gate needs; runs before it.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<CommandListEditor :model-value="field.state.value" label="Tooling" empty-text="Nothing to install." @update:model-value="field.handleChange" />
<DraftHint :kind="KIND" :path="`${i}.tooling`" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${i}.preflight`">
<Field orientation="responsive">
<FieldContent>
<FieldLabel>Preflight</FieldLabel>
<FieldDescription>Empty: ecosystem default.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<CommandListEditor :model-value="field.state.value" label="Preflight" empty-text="Ecosystem default." @update:model-value="field.handleChange" />
<DraftHint :kind="KIND" :path="`${i}.preflight`" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${i}.test_glob`">
<Field orientation="responsive">
<FieldContent>
<FieldLabel :for="`repo-${i}-glob`">Test files</FieldLabel>
<FieldDescription>Empty: ecosystem default.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input :id="`repo-${i}-glob`" :model-value="field.state.value" class="max-w-56 font-mono" placeholder="*_test.go" @blur="field.handleBlur" @update:model-value="field.handleChange" />
<DraftHint :kind="KIND" :path="`${i}.test_glob`" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${i}.instructions`">
<Field orientation="responsive">
<FieldContent><FieldLabel :for="`repo-${i}-instructions`">Instructions</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<div class="grid w-full gap-1">
<Textarea :id="`repo-${i}-instructions`" :model-value="field.state.value" :rows="5" class="font-mono text-label" @blur="field.handleBlur" @update:model-value="field.handleChange" />
<DraftHint :kind="KIND" :path="`${i}.instructions`" />
</div>
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${i}.protect`">
<Field orientation="responsive">
<FieldContent>
<FieldLabel>Protected paths</FieldLabel>
<FieldDescription>Suffixes agents never write.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<TagsInput
:model-value="field.state.value ?? []"
class="font-mono"
:aria-label="`Protected paths for ${repo.name}`"
@update:model-value="(v) => field.handleChange(v as string[])"
>
<TagsInputItem v-for="p in field.state.value ?? []" :key="p" :value="p">
<TagsInputItemText />
<TagsInputItemDelete />
</TagsInputItem>
<TagsInputInput placeholder="_templ.go" />
</TagsInput>
<DraftHint :kind="KIND" :path="`${i}.protect`" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${i}.max_retries`">
<Field orientation="responsive">
<FieldContent>
<FieldLabel>Max retries</FieldLabel>
<FieldDescription>0 = scheduling policy value.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<NumberField :model-value="field.state.value" :min="0" class="w-32" @update:model-value="field.handleChange">
<NumberFieldContent>
<NumberFieldDecrement />
<NumberFieldInput class="font-mono" :aria-label="`Max retries for ${repo.name}`" />
<NumberFieldIncrement />
</NumberFieldContent>
</NumberField>
<DraftHint :kind="KIND" :path="`${i}.max_retries`" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${i}.persistent_storage`">
<Field orientation="responsive">
<FieldContent>
<FieldLabel>Persistent storage</FieldLabel>
<FieldDescription>Kept across tasks.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Switch :model-value="field.state.value" :aria-label="`Persistent storage for ${repo.name}`" @update:model-value="field.handleChange" />
<DraftHint :kind="KIND" :path="`${i}.persistent_storage`" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${i}.allow_concurrent`">
<SettingRow
:tone="repo.allow_concurrent ? 'danger' : 'default'"
label="Concurrent tasks"
hint="Only if worktrees cannot collide."
>
<div class="flex min-w-0 flex-wrap items-center gap-3">
<Switch :model-value="field.state.value" :aria-label="`Concurrent tasks for ${repo.name}`" @update:model-value="field.handleChange" />
<DraftHint :kind="KIND" :path="`${i}.allow_concurrent`" />
</div>
</SettingRow>
</form.Field>
</FieldGroup>
</template>
</CardAccordion>
<div class="flex flex-wrap items-center gap-2">
<Input v-model="newRepo" class="max-w-72 font-mono" placeholder="owner/repository" aria-label="New repository" :disabled="unsaved" @keydown.enter="addRepo" />
<Button variant="outline" size="sm" :disabled="unsaved || !/^[^/\s]+\/[^/\s]+$/.test(newRepo.trim())" @click="addRepo">
<Plus data-icon="inline-start" /> Add repository</Button>
</div>
</template>
</div>
</template>
-202
View File
@@ -1,202 +0,0 @@
<script setup lang="ts">
definePage({
name: "org-scheduling-policy",
meta: {
section: "org_work_intake",
label: "Scheduling policy",
navPath: "/org",
description: "Work discovery and forge labels.",
},
});
import { Alert, AlertDescription } from "@/components/ui/alert";
import ApplyStatusRows from "@/settings/ApplyStatusRows.vue";
import HistoryLink from "@/settings/HistoryLink.vue";
import { computed, onMounted } from "vue";
import { storeToRefs } from "pinia";
import PageHeader from "@/base/PageHeader.vue";
import { DurationInput } from "@/components/ui/duration-input";
import { Field, FieldContent, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import {
NumberField,
NumberFieldContent,
NumberFieldDecrement,
NumberFieldIncrement,
NumberFieldInput,
} from "@/components/ui/number-field";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { Section } from "@/components/ui/section";
import { useSessionStore } from "@/stores/session";
import { resourcesForPage, useSettingsStore } from "@/stores/settings";
import DraftHint from "@/settings/DraftHint.vue";
import { fieldInvalid } from "@/settings/settings-form";
const KIND = "scheduling-policy";
interface SchedulingPolicy {
poll_interval: string;
max_retries: number;
intake_per_pass: number;
label?: string;
dispatch: { trigger: string; ack_reaction: string };
}
const store = useSettingsStore();
// Polling and the retry cap belong to the one daemon, so only the system
// org's admin sees them.
const instance = computed(() => useSessionStore().sections?.settings !== false);
const { catalog, catalogError } = storeToRefs(store);
onMounted(store.load);
const resources = computed(() => resourcesForPage(catalog.value, "scheduling"));
const form = computed(() => store.formFor(KIND));
const policy = computed(() => store.draftValue(KIND) as SchedulingPolicy | undefined);
const error = computed(() => store.pageErrorFor(KIND));
const triggers = [
{ value: "assignee", label: "Assignee" },
{ value: "label", label: "Label" },
{ value: "either", label: "Either" },
];
</script>
<template>
<div>
<PageHeader title="Scheduling policy">
<HistoryLink :kinds="resources.map((r) => r.kind)" />
</PageHeader>
<ApplyStatusRows v-for="resource in resources" :key="resource.kind" :kind="resource.kind" class="mb-4" />
<Alert v-if="catalogError || error" variant="destructive" class="mb-4"><AlertDescription>
{{ catalogError || error }}
</AlertDescription></Alert>
<KindGate v-if="!form" :kind="KIND" />
<template v-if="form">
<Section title="Dispatch">
<FieldGroup class="@container/field-group">
<form.Field v-slot="{ field }" name="dispatch.trigger">
<Field orientation="responsive">
<FieldContent><FieldLabel>Trigger</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<ToggleGroup
type="single"
variant="outline"
size="sm"
:model-value="field.state.value"
aria-label="Trigger"
@update:model-value="(value) => { if (value) field.handleChange(value as string); }"
>
<ToggleGroupItem v-for="option in triggers" :key="option.value" :value="option.value">{{ option.label }}</ToggleGroupItem>
</ToggleGroup>
<DraftHint :kind="KIND" path="dispatch.trigger" />
</div>
</Field>
</form.Field>
<form.Field v-if="policy?.dispatch.trigger !== 'assignee'" v-slot="{ field }" name="label">
<Field orientation="responsive" :data-invalid="fieldInvalid(field)">
<FieldContent><FieldLabel for="sp-label">Label</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-col gap-2 @md/field-group:flex-1">
<div class="flex flex-wrap items-center gap-3">
<Input
id="sp-label"
:model-value="field.state.value ?? ''"
class="max-w-sm font-mono"
:aria-invalid="fieldInvalid(field)"
@blur="field.handleBlur"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="label" />
</div>
<FieldError v-if="fieldInvalid(field)" :errors="field.state.meta.errors" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="dispatch.ack_reaction">
<Field orientation="responsive">
<FieldContent>
<FieldLabel for="sp-ack">Ack reaction</FieldLabel>
<FieldDescription>Empty: none.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input
id="sp-ack"
:model-value="field.state.value"
class="max-w-xs font-mono"
@blur="field.handleBlur"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="dispatch.ack_reaction" />
</div>
</Field>
</form.Field>
</FieldGroup>
</Section>
<Section v-if="instance" title="Retries and polling">
<FieldGroup class="@container/field-group">
<form.Field v-slot="{ field }" name="max_retries">
<Field orientation="responsive">
<FieldContent>
<FieldLabel>Max retries</FieldLabel>
<FieldDescription>Then marked dead.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<NumberField :model-value="field.state.value" :min="0" class="w-32" @update:model-value="field.handleChange">
<NumberFieldContent>
<NumberFieldDecrement />
<NumberFieldInput class="font-mono" aria-label="Max retries" />
<NumberFieldIncrement />
</NumberFieldContent>
</NumberField>
<DraftHint :kind="KIND" path="max_retries" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="intake_per_pass">
<Field orientation="responsive">
<FieldContent>
<FieldLabel>Tasks per poll</FieldLabel>
<FieldDescription>Most tasks one poll creates. The rest follow on later polls.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<NumberField :model-value="field.state.value" :min="0" class="w-32" @update:model-value="field.handleChange">
<NumberFieldContent>
<NumberFieldDecrement />
<NumberFieldInput class="font-mono" aria-label="Tasks per poll" />
<NumberFieldIncrement />
</NumberFieldContent>
</NumberField>
<DraftHint :kind="KIND" path="intake_per_pass" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="poll_interval">
<Field orientation="responsive" :data-invalid="fieldInvalid(field)">
<FieldContent><FieldLabel for="sp-poll">Poll interval</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-col gap-2 @md/field-group:flex-1">
<div class="flex flex-wrap items-center gap-3">
<DurationInput
id="sp-poll"
:model-value="field.state.value"
:units="['s', 'm', 'h']"
:aria-invalid="fieldInvalid(field)"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="poll_interval" />
</div>
<FieldError v-if="fieldInvalid(field)" :errors="field.state.meta.errors" />
</div>
</Field>
</form.Field>
</FieldGroup>
</Section>
</template>
</div>
</template>
-345
View File
@@ -1,345 +0,0 @@
<script setup lang="ts">
definePage({
name: "org-usage",
meta: {
section: "org_usage",
label: "Usage",
navPath: "/org",
description: "Token spend by model, identity and period.",
},
});
import UserReference from "@/org/UserReference.vue";
import { computed, onMounted, ref, watch } from "vue";
import PageHeader from "@/base/PageHeader.vue";
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { MetadataList } from "@/components/ui/metadata-list";
import { ReadError } from "@/components/ui/read-error";
import { Section } from "@/components/ui/section";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { compact, usd } from "@/lib/format";
/**
* What the org's model calls used and cost over a range: the totals, a row per
* day, and the model, source and identity breakdowns that explain them. The
* server derives the org from the caller, so the page names no org.
*/
interface Bucket {
calls: number;
input_tokens: number;
output_tokens: number;
cached_tokens: number;
cost_usd: number | null;
unpriced_calls: number;
}
type DayRow = { day: string } & Bucket;
type ModelRow = { provider: string; model: string } & Bucket;
type SourceRow = { source: string } & Bucket;
type IdentityRow = { identity_id: string; identity_name: string } & Bucket;
interface UsageReport {
days: number;
totals: Bucket;
by_day: DayRow[];
by_model: ModelRow[];
by_source: SourceRow[];
by_identity: IdentityRow[];
}
const RANGES = [
{ value: "7", label: "Last 7 days" },
{ value: "30", label: "Last 30 days" },
{ value: "90", label: "Last 90 days" },
];
const range = ref("30");
const report = ref<UsageReport | null>(null);
const loading = ref(true);
const error = ref("");
// Identifies the current read, so a reply for a range the operator has left is
// dropped instead of painted over the newer one.
let revision = 0;
async function load(): Promise<void> {
const attempt = ++revision;
loading.value = true;
error.value = "";
// The numbers below the control are the numbers for its range, so the
// previous range's report goes before the new read settles.
report.value = null;
try {
const next = await api.usage<UsageReport>(Number(range.value));
if (attempt !== revision) return;
report.value = next;
} catch (cause) {
if (attempt !== revision) return;
error.value = describeError(cause, errors.common.unknown);
} finally {
if (attempt === revision) loading.value = false;
}
}
onMounted(() => void load());
watch(range, () => void load());
/** Prompt and completion tokens; cached tokens are a subset of the input. */
const tokens = (bucket: Bucket): number =>
bucket.input_tokens + bucket.output_tokens;
/** The exact counts behind a compact cell. */
function tokenTitle(bucket: Bucket): string {
const cached = bucket.cached_tokens
? `, ${bucket.cached_tokens.toLocaleString()} cached`
: "";
return `${tokens(bucket).toLocaleString()} tokens (${bucket.input_tokens.toLocaleString()} in, ${bucket.output_tokens.toLocaleString()} out${cached})`;
}
interface TotalRow {
label: string;
value?: string;
mono?: boolean;
title?: string;
}
const totalRows = computed<TotalRow[]>(() => {
const totals = report.value?.totals;
if (!totals) return [];
const rows: TotalRow[] = [
{ label: "Model calls", value: totals.calls.toLocaleString() },
{
label: "Total tokens",
value: compact(tokens(totals)),
mono: true,
title: `${tokens(totals).toLocaleString()} tokens`,
},
{
label: "Input tokens",
value: compact(totals.input_tokens),
mono: true,
title: `${totals.input_tokens.toLocaleString()} tokens`,
},
{
label: "Output tokens",
value: compact(totals.output_tokens),
mono: true,
title: `${totals.output_tokens.toLocaleString()} tokens`,
},
{
label: "Cached tokens",
value: compact(totals.cached_tokens),
mono: true,
title: `${totals.cached_tokens.toLocaleString()} cached tokens, included in input tokens`,
},
{
label: "Cost",
value: usd(totals.cost_usd),
mono: true,
title:
totals.cost_usd == null
? "No call in this range could be priced"
: undefined,
},
];
if (totals.unpriced_calls > 0) {
rows.push({
label: "Unpriced calls",
value: totals.unpriced_calls.toLocaleString(),
title:
"Calls to models without a catalog price count tokens but have no cost.",
});
}
return rows;
});
const dayColumns: DataTableColumn<DayRow>[] = [
{ id: "day", label: "Day", fixed: true, class: "whitespace-nowrap" },
{ 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, 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", 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, 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>
<template>
<div>
<PageHeader title="Usage">
<Select v-model="range">
<SelectTrigger class="w-40" size="sm" aria-label="Date range">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem v-for="option in RANGES" :key="option.value" :value="option.value">
{{ option.label }}
</SelectItem>
</SelectContent>
</Select>
</PageHeader>
<ReadError v-if="error" :message="error" retry-label="Retry" class="mb-4" @retry="load" />
<Section v-else-if="loading">
<p role="status" class="flex items-center gap-2 text-label text-fg-muted">
<Spinner />Loading usage…
</p>
</Section>
<Section v-else-if="!report || report.totals.calls === 0">
<Empty>
<EmptyHeader>
<EmptyTitle>No model calls in this range.</EmptyTitle>
</EmptyHeader>
</Empty>
</Section>
<template v-else>
<Section title="Totals">
<MetadataList :rows="totalRows">
<template #value="{ row }">
<span
class="tabular-nums text-title font-medium"
:class="row.mono && 'font-mono'"
:title="row.title"
>{{ row.value }}</span
>
</template>
</MetadataList>
</Section>
<Section title="Daily">
<DataTable
:columns="dayColumns"
:rows="report?.by_day ?? []"
:row-key="(row) => row.day"
storage-key="usage-daily"
>
<template #empty>
<Empty><EmptyHeader><EmptyTitle>No model calls in this range.</EmptyTitle></EmptyHeader></Empty>
</template>
<template #cell-day="{ row }">
<span class="font-mono text-caption">{{ row.day }}</span>
</template>
<template #cell-calls="{ row }">
<span class="tabular-nums">{{ row.calls.toLocaleString() }}</span>
</template>
<template #cell-tokens="{ row }">
<span class="tabular-nums" :title="tokenTitle(row)">{{ compact(tokens(row)) }}</span>
</template>
<template #cell-cost="{ row }">
<span class="tabular-nums">{{ usd(row.cost_usd) }}</span>
</template>
</DataTable>
</Section>
<Section title="By model">
<DataTable
:columns="modelColumns"
:rows="report?.by_model ?? []"
:row-key="(row) => `${row.provider}/${row.model}`"
storage-key="usage-by-model"
>
<template #empty>
<Empty><EmptyHeader><EmptyTitle>No model calls in this range.</EmptyTitle></EmptyHeader></Empty>
</template>
<template #cell-provider="{ row }">
<span class="font-mono text-caption">{{ row.provider || "–" }}</span>
</template>
<template #cell-model="{ row }">
<span class="font-mono text-caption">{{ row.model || "–" }}</span>
</template>
<template #cell-calls="{ row }">
<span class="tabular-nums">{{ row.calls.toLocaleString() }}</span>
</template>
<template #cell-tokens="{ row }">
<span class="tabular-nums" :title="tokenTitle(row)">{{ compact(tokens(row)) }}</span>
</template>
<template #cell-cost="{ row }">
<span class="tabular-nums">{{ usd(row.cost_usd) }}</span>
</template>
</DataTable>
</Section>
<Section title="By source">
<DataTable
:columns="sourceColumns"
:rows="report?.by_source ?? []"
:row-key="(row) => row.source"
storage-key="usage-by-source"
>
<template #empty>
<Empty><EmptyHeader><EmptyTitle>No model calls in this range.</EmptyTitle></EmptyHeader></Empty>
</template>
<template #cell-source="{ row }">
<span class="font-mono text-caption">{{ row.source || "–" }}</span>
</template>
<template #cell-calls="{ row }">
<span class="tabular-nums">{{ row.calls.toLocaleString() }}</span>
</template>
<template #cell-tokens="{ row }">
<span class="tabular-nums" :title="tokenTitle(row)">{{ compact(tokens(row)) }}</span>
</template>
<template #cell-cost="{ row }">
<span class="tabular-nums">{{ usd(row.cost_usd) }}</span>
</template>
</DataTable>
</Section>
<Section title="By identity">
<DataTable
:columns="identityColumns"
:rows="report?.by_identity ?? []"
:row-key="(row) => row.identity_id || 'unknown'"
storage-key="usage-by-identity"
>
<template #empty>
<Empty><EmptyHeader><EmptyTitle>No model calls in this range.</EmptyTitle></EmptyHeader></Empty>
</template>
<template #cell-identity="{ row }">
<UserReference :id="row.identity_id" :name="row.identity_name" :title="row.identity_id || undefined" fallback="Unknown" />
</template>
<template #cell-calls="{ row }">
<span class="tabular-nums">{{ row.calls.toLocaleString() }}</span>
</template>
<template #cell-tokens="{ row }">
<span class="tabular-nums" :title="tokenTitle(row)">{{ compact(tokens(row)) }}</span>
</template>
<template #cell-cost="{ row }">
<span class="tabular-nums">{{ usd(row.cost_usd) }}</span>
</template>
</DataTable>
</Section>
</template>
</div>
</template>
-113
View File
@@ -1,113 +0,0 @@
<script setup lang="ts">
definePage({
name: "settings-agent-profiles",
meta: {
navPath: "/settings",
settings: true,
label: "Agent profiles",
section: "agent_profiles",
description: "Execution profiles: the image and tools each agent runs with.",
},
});
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { computed, onMounted, ref } from "vue";
import PageHeader from "@/base/PageHeader.vue";
import { Button } from "@/components/ui/button";
import { Field, FieldContent, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { TagsInput, TagsInputInput, TagsInputItem, TagsInputItemDelete, TagsInputItemText } from "@/components/ui/tags-input";
import { useSettingsStore } from "@/stores/settings";
import ApplyStatusRows from "@/settings/ApplyStatusRows.vue";
import CardAccordion from "@/settings/CardAccordion.vue";
import HistoryLink from "@/settings/HistoryLink.vue";
interface Profile { image?: string; tools?: string[] }
const KIND = "agent-profiles";
const store = useSettingsStore();
// A fresh instance seeds the document as null; once the form exists that is
// an empty map, so the empty state shows rather than a bare add form.
const profiles = computed(() => {
const value = store.draftValue(KIND) as Record<string, Profile> | null;
return value ?? (store.formFor(KIND) ? {} : null);
});
const name = ref("");
const open = ref("");
const unsaved = computed(() => store.changesFor(KIND).length > 0);
const entries = computed(() => Object.entries(profiles.value ?? {}));
// Profile names are free text, so a profile is written as a whole map entry
// rather than by a dotted per-profile path.
function add() {
if (unsaved.value || !store.formFor(KIND)) return;
const key = name.value.trim();
if (!key || profiles.value?.[key]) return;
store.setDraftEntry(KIND, key, { image: "", tools: [] });
// Integer-like names sort first in a JS object, so find where the key landed.
open.value = String(entries.value.findIndex(([k]) => k === key));
name.value = "";
}
function removeProfile(index: number) {
const key = entries.value[index]?.[0];
if (!key) return;
store.setDraftEntry(KIND, key, undefined);
}
// A field cleared back to empty is dropped unless the stored profile has it,
// so emptying a field the profile never had is not a change.
function patch(key: string, changes: Partial<Profile>) {
const stored = (store.stateFor(KIND).resource?.value as Record<string, Profile> | null)?.[key];
const next: Record<string, unknown> = { ...profiles.value?.[key], ...changes };
for (const field of Object.keys(changes)) {
const value = next[field];
const empty = Array.isArray(value) ? value.length === 0 : value === "";
if (empty && !(stored && field in stored)) delete next[field];
}
store.setDraftEntry(KIND, key, next);
}
onMounted(() => {
void store.load();
});
</script>
<template>
<div>
<PageHeader title="Agent profiles"><HistoryLink :kinds="[KIND]" /></PageHeader>
<ApplyStatusRows :kind="KIND" class="mb-4" />
<Alert v-if="store.catalogError || store.pageErrorFor(KIND)" variant="destructive" class="mb-4"><AlertDescription>{{ store.catalogError || store.pageErrorFor(KIND) }}</AlertDescription></Alert>
<form class="mb-4 flex flex-wrap gap-2" @submit.prevent="add">
<Input v-model="name" aria-label="Profile name" placeholder="Profile name" class="max-w-xs" :disabled="unsaved" />
<Button type="submit" :disabled="unsaved || !name.trim() || !!profiles?.[name.trim()]">Add profile</Button>
</form>
<Empty v-if="profiles && !entries.length"><EmptyHeader><EmptyTitle>No agent profiles</EmptyTitle></EmptyHeader></Empty>
<CardAccordion v-model:open="open" :items="entries" :title="([key]) => key" remove-label="Remove" mono @remove="removeProfile">
<template #default="{ item: [key, profile] }">
<FieldGroup class="@container/field-group">
<Field orientation="responsive">
<FieldContent>
<FieldLabel :for="`${key}-image`">Image</FieldLabel>
<FieldDescription>Container image reference, such as registry/name:tag. Empty uses the image from Container runtime.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input :id="`${key}-image`" :model-value="profile.image" placeholder="registry/name:tag" @update:model-value="(v) => patch(key, { image: String(v) })" />
</div>
</Field>
<Field orientation="responsive">
<FieldContent>
<FieldLabel :for="`${key}-tools`">Tools</FieldLabel>
<FieldDescription>Names of the MCP servers, repository scripts and skills the agent may use. Empty allows all of them.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<TagsInput :id="`${key}-tools`" class="flex-1" :model-value="profile.tools ?? []" :aria-label="`${key} tools`" @update:model-value="(v) => patch(key, { tools: v.map(String) })">
<TagsInputItem v-for="tool in profile.tools ?? []" :key="tool" :value="tool"><TagsInputItemText /><TagsInputItemDelete /></TagsInputItem>
<TagsInputInput placeholder="Add tool" />
</TagsInput>
</div>
</Field>
</FieldGroup>
</template>
</CardAccordion>
</div>
</template>
-230
View File
@@ -1,230 +0,0 @@
<script setup lang="ts">
definePage({
name: "settings-channels",
meta: {
navPath: "/settings",
settings: true,
label: "Channels",
description: "Chat channel connections and session defaults.",
section: "channels",
},
});
import { Alert, AlertDescription } from "@/components/ui/alert";
import ApplyStatusRows from "@/settings/ApplyStatusRows.vue";
import KindGate from "@/settings/KindGate.vue";
import HistoryLink from "@/settings/HistoryLink.vue";
import { computed, onMounted, ref } from "vue";
import ExtensionChannelSettings from "@/settings/ExtensionChannelSettings.vue";
import { useExtensionsStore } from "@/stores/extensions";
import { storeToRefs } from "pinia";
import PageHeader from "@/base/PageHeader.vue";
import { Button } from "@/components/ui/button";
import { DurationInput } from "@/components/ui/duration-input";
import { Field, FieldContent, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import {
NumberField,
NumberFieldContent,
NumberFieldDecrement,
NumberFieldIncrement,
NumberFieldInput,
} from "@/components/ui/number-field";
import { Switch } from "@/components/ui/switch";
import {
TagsInput,
TagsInputInput,
TagsInputItem,
TagsInputItemDelete,
TagsInputItemText,
} from "@/components/ui/tags-input";
import { api } from "@/lib/api";
import { errors } from "@/copy/errors";
import { Section } from "@/components/ui/section";
import { resourcesForPage, useSettingsStore } from "@/stores/settings";
import { useLiveResource } from "@/stores/session";
const KIND = "channel-settings";
interface ChannelSettings {
operator: string;
show_tool_calls: boolean;
max_steps: number;
models: string[] | null;
rate_limit: { window: string; max_requests: number };
unrestricted_filesystem: boolean;
workspace: string;
agent: string;
}
/** What the messaging service reports about a running channel. */
interface ChannelStatus {
id?: string;
state?: string;
detail?: string;
}
const store = useSettingsStore();
const { catalog, catalogError } = storeToRefs(store);
const resources = computed(() => resourcesForPage(catalog.value, "channels"));
const form = computed(() => store.formFor(KIND));
const chat = computed(() => store.draftValue(KIND) as ChannelSettings | undefined);
const error = computed(() => store.pageErrorFor(KIND));
// Channel packages declare their settings, and each form is built from them.
const extensions = useExtensionsStore();
const extensionChannels = computed(() =>
extensions.extensions.filter((e) => e.capabilities?.deliveries?.length && e.settings_schema?.length),
);
const statuses = ref<ChannelStatus[]>([]);
// A failed status read keeps the last known badges and flags the error, so a
// transient failure neither clears every badge nor passes as "all idle".
const statusError = ref(false);
let statusGeneration = 0;
async function loadStatus() {
const current = ++statusGeneration;
try {
statuses.value = (await api.channels<{ channels?: ChannelStatus[] }>())?.channels ?? [];
if (current !== statusGeneration) return;
statusError.value = false;
} catch {
if (current !== statusGeneration) return;
statusError.value = true;
}
}
useLiveResource(null, () => void loadStatus());
onMounted(() => Promise.all([loadStatus(), store.load(), extensions.loadInstalled()]));
const models = computed(() => chat.value?.models ?? []);
function statusFor(id: string) {
return statuses.value.find((s) => s.id === id);
}
function setModels(list: string[]) {
form.value?.api.setFieldValue("models", list);
}
</script>
<template>
<div>
<PageHeader title="Channels">
<HistoryLink :kinds="resources.map((r) => r.kind)" />
</PageHeader>
<ApplyStatusRows :kind="KIND" class="mb-4" />
<ApplyStatusRows kind="extension-settings" class="mb-4" />
<Alert v-if="catalogError || error" variant="destructive" class="mb-4"><AlertDescription>
{{ catalogError || error }}
</AlertDescription></Alert>
<Alert v-if="extensions.error" variant="destructive" class="mb-4"><AlertDescription>{{ extensions.error }}</AlertDescription></Alert>
<Alert v-if="statusError" variant="destructive" class="mb-4"><AlertDescription>
{{ errors.settings.channels.status }}
<Button variant="link" size="xs" @click="loadStatus">Retry</Button>
</AlertDescription></Alert>
<template v-if="chat">
<ExtensionChannelSettings v-for="extension in extensionChannels" :key="extension.name" :extension="extension" :status="statusFor(extension.name)" />
<Section title="Chat session defaults">
<KindGate v-if="!form" :kind="KIND" />
<FieldGroup v-if="form" class="@container/field-group">
<form.Field v-slot="{ field }" name="workspace">
<Field orientation="responsive">
<FieldContent>
<FieldLabel for="cs-workspace">Workspace</FieldLabel>
<FieldDescription>Empty disables file tools.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input id="cs-workspace" :model-value="field.state.value" class="max-w-md font-mono" @blur="field.handleBlur" @update:model-value="field.handleChange" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="unrestricted_filesystem">
<Field
orientation="responsive"
:class="field.state.value && 'relative isolate before:pointer-events-none before:absolute before:inset-y-0 before:-inset-x-3 before:-z-10 before:rounded-md before:border before:border-danger/40 before:bg-danger-soft'"
>
<FieldContent><FieldLabel for="channel-unrestricted">Unrestricted filesystem</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Switch id="channel-unrestricted" :model-value="field.state.value" aria-label="Unrestricted filesystem" @update:model-value="field.handleChange" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="show_tool_calls">
<Field orientation="responsive">
<FieldContent><FieldLabel for="channel-show-tools">Show tool calls</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Switch id="channel-show-tools" :model-value="field.state.value" aria-label="Show tool calls" @update:model-value="field.handleChange" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="max_steps">
<Field orientation="responsive">
<FieldContent>
<FieldLabel for="channel-max-steps">Max steps</FieldLabel>
<FieldDescription>0 = default (100).</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<NumberField :model-value="field.state.value" :min="0" class="w-32" @update:model-value="field.handleChange">
<NumberFieldContent>
<NumberFieldDecrement />
<NumberFieldInput id="channel-max-steps" class="font-mono" aria-label="Max steps" />
<NumberFieldIncrement />
</NumberFieldContent>
</NumberField>
</div>
</Field>
</form.Field>
<Field orientation="responsive">
<FieldContent>
<FieldLabel id="channel-rate-label">Rate limit</FieldLabel>
<FieldDescription>Per sender. Off while either is 0.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1" role="group" aria-labelledby="channel-rate-label">
<div class="flex flex-wrap items-center gap-2 text-label text-fg-muted">
<form.Field v-slot="{ field }" name="rate_limit.max_requests">
<NumberField :model-value="field.state.value" :min="0" class="w-28" @update:model-value="field.handleChange">
<NumberFieldContent>
<NumberFieldInput class="font-mono" aria-label="Requests" />
</NumberFieldContent>
</NumberField>
</form.Field>
requests per
<form.Field v-slot="{ field }" name="rate_limit.window">
<DurationInput :model-value="field.state.value" :units="['s', 'm', 'h']" @update:model-value="field.handleChange" />
</form.Field>
</div>
</div>
</Field>
<Field orientation="responsive">
<FieldContent>
<FieldLabel id="channel-models-label">Models</FieldLabel>
<FieldDescription>Empty: role models.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<div role="group" aria-labelledby="channel-models-label" class="contents"><TagsInput :model-value="models" class="font-mono" @update:model-value="(list) => setModels(list.map(String))">
<TagsInputItem v-for="model in models" :key="model" :value="model">
<TagsInputItemText />
<TagsInputItemDelete />
</TagsInputItem>
<TagsInputInput placeholder="provider/model" aria-label="Models" />
</TagsInput></div>
</div>
</Field>
<form.Field v-slot="{ field }" name="operator">
<Field orientation="responsive">
<FieldContent><FieldLabel for="cs-operator">Operator</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input id="cs-operator" :model-value="field.state.value" class="max-w-sm" @blur="field.handleBlur" @update:model-value="field.handleChange" />
</div>
</Field>
</form.Field>
</FieldGroup>
</Section>
</template>
</div>
</template>
-384
View File
@@ -1,384 +0,0 @@
<script setup lang="ts">
definePage({
name: "settings-container-runtime",
meta: {
navPath: "/settings",
settings: true,
label: "Container runtime",
description: "How task containers run: runtime, image, limits and egress hosts.",
section: "container_runtime",
},
});
import { Alert, AlertDescription } from "@/components/ui/alert";
import ApplyStatusRows from "@/settings/ApplyStatusRows.vue";
import { computed, onMounted } from "vue";
import { storeToRefs } from "pinia";
import { TriangleAlert } from "@lucide/vue";
import PageHeader from "@/base/PageHeader.vue";
import { DurationInput } from "@/components/ui/duration-input";
import { parseGoDuration } from "@/components/ui/duration-input/duration";
import { Field, FieldContent, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import {
NumberField,
NumberFieldContent,
NumberFieldDecrement,
NumberFieldIncrement,
NumberFieldInput,
} from "@/components/ui/number-field";
import { Textarea } from "@/components/ui/textarea";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { resourcesForPage, useSettingsStore } from "@/stores/settings";
import DraftHint from "@/settings/DraftHint.vue";
import HistoryLink from "@/settings/HistoryLink.vue";
import KindGate from "@/settings/KindGate.vue";
import SecretRefField from "@/settings/SecretRefField.vue";
import { fieldInvalid } from "@/settings/settings-form";
const KIND = "container-runtime-policies";
const EXECUTION_KIND = "workflow-execution-settings";
// The server's own default when execution settings predate the task limit.
const DEFAULT_TASK_RUNTIME_SECONDS = 4 * 60 * 60;
// The stored document is containerRuntimePolicies on the wire: snake_case keys
// and durations as Go duration strings.
interface ContainerRuntime {
image: string;
max_concurrency: number;
max_uptime: string;
volume_ttl: string;
pull_policy: string;
network: string;
runtime: string;
openshell: {
address: string;
workspace: string;
token: { engine: string; key: string };
ca_file: string;
cert_file: string;
key_file: string;
services_host: string;
};
egress_hosts: string[];
}
const store = useSettingsStore();
const { catalog, catalogError } = storeToRefs(store);
onMounted(store.load);
const resources = computed(() => resourcesForPage(catalog.value, "containers"));
const form = computed(() => store.formFor(KIND));
const runtime = computed(() => store.draftValue(KIND) as ContainerRuntime | undefined);
const error = computed(() => store.pageErrorFor(KIND));
const runtimes = [
{ value: "docker", label: "Docker" },
{ value: "openshell", label: "OpenShell" },
];
const onOpenShell = computed(() => runtime.value?.runtime === "openshell");
const pullPolicies = [
{ value: "missing", label: "If missing" },
{ value: "always", label: "Always" },
];
// The daemon kills a container at max uptime, so a task limit longer than it
// can never be reached. Mirrors the warning archied logs when it applies them.
const uptimeWarning = computed(() => {
const uptime = parseGoDuration(runtime.value?.max_uptime ?? "");
if (!uptime) return "";
const execution = store.draftValue(EXECUTION_KIND) as { max_task_runtime_seconds?: number | null } | undefined;
const limitSeconds = execution?.max_task_runtime_seconds ?? DEFAULT_TASK_RUNTIME_SECONDS;
if (limitSeconds > 0 && limitSeconds * 1000 <= uptime) return "";
const limit = limitSeconds > 0 ? `the ${formatHours(limitSeconds)} task limit` : "the task limit, which is off";
return `Shorter than ${limit}, so containers are killed before a task can finish.`;
});
// One host per line; commas and spaces separate too, so a pasted list works.
function splitHosts(values: string[]): string[] {
return [...new Set(values.flatMap((v) => v.split(/[\s,]+/)).filter(Boolean))];
}
function formatHours(seconds: number): string {
return seconds % 3600 === 0 ? `${seconds / 3600}h` : `${Math.round(seconds / 60)}m`;
}
</script>
<template>
<div>
<PageHeader title="Container runtime">
<HistoryLink :kinds="resources.map((r) => r.kind)" />
</PageHeader>
<ApplyStatusRows v-for="resource in resources" :key="resource.kind" :kind="resource.kind" class="mb-4" />
<Alert v-if="catalogError || error" variant="destructive" class="mb-4"><AlertDescription>{{ catalogError || error }}</AlertDescription></Alert>
<KindGate v-if="!form" :kind="KIND" />
<div v-if="form" class="flex flex-col gap-5">
<FieldGroup v-if="form" class="@container/field-group">
<form.Field v-slot="{ field }" name="runtime">
<Field orientation="responsive">
<FieldContent>
<FieldLabel>Runtime</FieldLabel>
<FieldDescription>Applies on restart.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<ToggleGroup
type="single"
variant="outline"
size="sm"
:model-value="field.state.value || 'docker'"
aria-label="Runtime"
@update:model-value="(value) => { if (value) field.handleChange(value); }"
>
<ToggleGroupItem v-for="option in runtimes" :key="option.value" :value="option.value">{{ option.label }}</ToggleGroupItem>
</ToggleGroup>
<DraftHint :kind="KIND" path="runtime" />
</div>
</Field>
</form.Field>
</FieldGroup>
<FieldGroup v-if="form && onOpenShell" class="@container/field-group">
<form.Field v-slot="{ field }" name="openshell.address">
<Field orientation="responsive">
<FieldContent><FieldLabel for="cr-os-address">Gateway</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input
id="cr-os-address"
:model-value="field.state.value"
class="max-w-sm font-mono"
@blur="field.handleBlur"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="openshell.address" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="openshell.workspace">
<Field orientation="responsive">
<FieldContent><FieldLabel for="cr-os-workspace">Workspace</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input
id="cr-os-workspace"
:model-value="field.state.value"
class="max-w-sm font-mono"
placeholder="default"
@blur="field.handleBlur"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="openshell.workspace" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="openshell.token">
<Field orientation="responsive">
<FieldContent><FieldLabel>Token</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<SecretRefField
:model-value="field.state.value ?? { engine: '', key: '' }"
id-prefix="cr-os-token"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="openshell.token" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="openshell.ca_file">
<Field orientation="responsive">
<FieldContent><FieldLabel for="cr-os-ca-file">CA file</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input
id="cr-os-ca-file"
:model-value="field.state.value"
class="max-w-sm font-mono"
@blur="field.handleBlur"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="openshell.ca_file" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="openshell.cert_file">
<Field orientation="responsive">
<FieldContent><FieldLabel for="cr-os-cert-file">Client certificate</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input
id="cr-os-cert-file"
:model-value="field.state.value"
class="max-w-sm font-mono"
@blur="field.handleBlur"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="openshell.cert_file" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="openshell.key_file">
<Field orientation="responsive">
<FieldContent><FieldLabel for="cr-os-key-file">Client key</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input
id="cr-os-key-file"
:model-value="field.state.value"
class="max-w-sm font-mono"
@blur="field.handleBlur"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="openshell.key_file" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="openshell.services_host">
<Field orientation="responsive">
<FieldContent><FieldLabel for="cr-os-services-host">Services host</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input
id="cr-os-services-host"
:model-value="field.state.value"
class="max-w-sm font-mono"
@blur="field.handleBlur"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="openshell.services_host" />
</div>
</Field>
</form.Field>
</FieldGroup>
<FieldGroup v-if="form" class="@container/field-group">
<form.Field v-slot="{ field }" name="image">
<Field orientation="responsive" :data-invalid="fieldInvalid(field)">
<FieldContent><FieldLabel for="cr-image">Image</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input
id="cr-image"
:model-value="field.state.value"
class="font-mono"
:aria-invalid="fieldInvalid(field)"
@blur="field.handleBlur"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="image" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="pull_policy">
<Field v-if="!onOpenShell" orientation="responsive">
<FieldContent><FieldLabel>Pull policy</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<ToggleGroup
type="single"
variant="outline"
size="sm"
:model-value="field.state.value || 'missing'"
aria-label="Pull policy"
@update:model-value="(value) => { if (value) field.handleChange(value); }"
>
<ToggleGroupItem v-for="option in pullPolicies" :key="option.value" :value="option.value">{{ option.label }}</ToggleGroupItem>
</ToggleGroup>
<DraftHint :kind="KIND" path="pull_policy" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="max_concurrency">
<Field orientation="responsive">
<FieldContent>
<FieldLabel>Max concurrency</FieldLabel>
<FieldDescription>0 = no limit.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<NumberField :model-value="field.state.value" :min="0" class="w-32" @update:model-value="field.handleChange">
<NumberFieldContent>
<NumberFieldDecrement />
<NumberFieldInput class="font-mono" aria-label="Max concurrency" />
<NumberFieldIncrement />
</NumberFieldContent>
</NumberField>
<DraftHint :kind="KIND" path="max_concurrency" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="max_uptime">
<Field orientation="responsive" :data-invalid="fieldInvalid(field)">
<FieldContent><FieldLabel for="cr-uptime">Max uptime</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-col gap-2 @md/field-group:flex-1">
<FieldDescription v-if="uptimeWarning" class="flex items-start gap-1.5 text-warn" role="status">
<TriangleAlert class="mt-0.5 size-3.5 shrink-0" />
<span>{{ uptimeWarning }}</span>
</FieldDescription>
<div class="flex flex-wrap items-center gap-3">
<DurationInput
id="cr-uptime"
:model-value="field.state.value"
:units="['m', 'h']"
:aria-invalid="fieldInvalid(field)"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="max_uptime" />
</div>
<FieldError v-if="fieldInvalid(field)" :errors="field.state.meta.errors" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="volume_ttl">
<Field orientation="responsive">
<FieldContent><FieldLabel for="cr-ttl">Volume retention</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<DurationInput id="cr-ttl" :model-value="field.state.value" :units="['h']" @update:model-value="field.handleChange" />
<DraftHint :kind="KIND" path="volume_ttl" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="network">
<Field v-if="!onOpenShell" orientation="responsive">
<FieldContent>
<FieldLabel for="cr-network">Network</FieldLabel>
<FieldDescription>Empty: auto-detect.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input
id="cr-network"
:model-value="field.state.value"
class="max-w-sm font-mono"
@blur="field.handleBlur"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="network" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="egress_hosts">
<Field orientation="responsive">
<FieldContent><FieldLabel>Egress hosts</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Textarea
:model-value="(field.state.value ?? []).join('\n')"
:rows="6"
class="font-mono text-label"
aria-label="Egress hosts"
placeholder="*.example.com:443"
@change="(e: Event) => field.handleChange(splitHosts([(e.target as HTMLTextAreaElement).value]))"
/>
<DraftHint :kind="KIND" path="egress_hosts" />
</div>
</Field>
</form.Field>
</FieldGroup>
</div>
</div>
</template>
-243
View File
@@ -1,243 +0,0 @@
<script setup lang="ts">
definePage({
name: "curators",
meta: {
navPath: "/settings",
settings: true,
label: "Curators",
description: "Scheduled memory and capture curation.",
section: "curators",
},
});
import { Alert, AlertDescription } from "@/components/ui/alert";
import { computed, onMounted, ref, watch } from "vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { DurationInput } from "@/components/ui/duration-input";
import { Section } from "@/components/ui/section";
import { Field, FieldContent, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { TagsInput, TagsInputInput, TagsInputItem, TagsInputItemDelete, TagsInputItemText } from "@/components/ui/tags-input";
import { useSettingsStore } from "@/stores/settings";
import { aliasModelOptions } from "@/settings/model-choices";
import ApplyStatusRows from "@/settings/ApplyStatusRows.vue";
import HistoryLink from "@/settings/HistoryLink.vue";
import PageHeader from "@/base/PageHeader.vue";
import {
Empty,
EmptyDescription,
EmptyHeader,
EmptyTitle,
} from "@/components/ui/empty";
import { errors } from "@/copy/errors";
import { api, describeError } from "@/lib/api";
import { useLiveResource } from "@/stores/session";
import CuratorCard, { type Curator } from "@/curators/CuratorCard.vue";
/**
* Backed by GET /api/curators, which reads the daemon's live curator registry:
* which curators are registered, their point-in-time health, and their recent
* activity, with the reason each action happened.
*/
interface Definition {
name: string; enabled: boolean; instructions: string; interval: string; cooldown: string;
on_input: boolean; tools: string[]; skills: boolean; memory_engine: string; conversations: boolean; model: string;
}
const KIND = "curators";
const store = useSettingsStore();
onMounted(() => {
void store.load();
void store.loadConfig();
});
const form = computed(() => store.formFor(KIND));
const definitions = computed(() => store.draftValue(KIND) as Definition[] | null);
const editing = ref(false);
const newName = ref("");
// The list is the whole document, so adding or removing rebuilds it.
function add() {
const name = newName.value.trim();
if (!name || definitions.value?.some(def => def.name === name)) return;
if (!form.value) return;
const def: Definition = {name,enabled:false,instructions:"",interval:"1h",cooldown:"0s",on_input:false,tools:[],skills:false,memory_engine:"",conversations:false,model:""};
store.setDraftValue(KIND, [...(definitions.value ?? []), def]);
newName.value = "";
}
function remove(index: number) {
store.setDraftValue(KIND, (definitions.value ?? []).filter((_, i) => i !== index));
}
// Models are the configured providers' models from the server's catalog, plus
// whatever the draft already names.
const modelCatalog = computed(() => store.config?.catalog ?? []);
const configuredProviderIds = computed(() =>
Object.keys((store.draftValue("provider-settings") as Record<string, unknown> | undefined) ?? {}),
);
const modelOptions = computed(() => aliasModelOptions(modelCatalog.value, configuredProviderIds.value));
watch(() => store.applyStatusFor(KIND).map(row => row.version).join(","), () => void load());
const curators = ref<Curator[]>([]);
const curatorsLoaded = ref(false);
const loadError = ref<string | null>(null);
let loadGeneration = 0;
async function load() {
const current = ++loadGeneration;
try {
const res = await api.curators<{ curators?: Curator[] }>();
if (current !== loadGeneration) return;
curators.value = res?.curators || [];
loadError.value = null;
} catch (err) {
if (current !== loadGeneration) return;
loadError.value = describeError(err, errors.common.unknown);
} finally {
if (current === loadGeneration) curatorsLoaded.value = true;
}
}
useLiveResource("curators", () => void load());
onMounted(load);
</script>
<template>
<div>
<PageHeader title="Curators"><HistoryLink :kinds="[KIND]" /><Button variant="outline" @click="editing = !editing">{{ editing ? "Hide definitions" : "Edit definitions" }}</Button></PageHeader>
<ApplyStatusRows :kind="KIND" class="mb-4" />
<Alert v-if="store.catalogError || store.pageErrorFor(KIND)" variant="destructive" class="mb-4"><AlertDescription>{{ store.catalogError || store.pageErrorFor(KIND) }}</AlertDescription></Alert>
<div v-if="editing" class="mb-6">
<form class="mb-4 flex gap-2" @submit.prevent="add"><Input v-model="newName" aria-label="Curator name" placeholder="Curator name" class="max-w-xs" /><Button type="submit" :disabled="!newName.trim() || definitions?.some(def => def.name === newName.trim())">Add curator</Button></form>
<Empty v-if="!definitions?.length"><EmptyHeader><EmptyTitle>No custom curator definitions</EmptyTitle></EmptyHeader></Empty>
<Section v-for="(def, index) in definitions" :key="index" :title="def.name">
<template #action><Button variant="ghost" size="sm" @click="remove(index)">Remove curator</Button></template>
<FieldGroup v-if="form" class="@container/field-group">
<form.Field v-slot="{ field }" :name="`${index}.enabled`">
<Field orientation="responsive">
<FieldContent><FieldLabel>Enabled</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Switch :model-value="field.state.value" :aria-label="`${def.name} enabled`" @update:model-value="field.handleChange" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${index}.instructions`">
<Field orientation="responsive">
<FieldContent><FieldLabel :for="`curator-${index}-instructions`">Instructions</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Textarea :id="`curator-${index}-instructions`" :model-value="field.state.value" @blur="field.handleBlur" @update:model-value="field.handleChange" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${index}.interval`">
<Field orientation="responsive">
<FieldContent><FieldLabel :for="`curator-${index}-interval`">Interval</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<DurationInput :id="`curator-${index}-interval`" :model-value="field.state.value" :units="['s', 'm', 'h']" @update:model-value="field.handleChange" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${index}.cooldown`">
<Field orientation="responsive">
<FieldContent><FieldLabel :for="`curator-${index}-cooldown`">Cooldown</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<DurationInput :id="`curator-${index}-cooldown`" :model-value="field.state.value" :units="['s', 'm', 'h']" @update:model-value="field.handleChange" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${index}.on_input`">
<Field orientation="responsive">
<FieldContent><FieldLabel :for="`curator-${index}-wake`">Wake on input</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Switch :id="`curator-${index}-wake`" :model-value="field.state.value" :aria-label="`${def.name} wake on input`" @update:model-value="field.handleChange" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${index}.tools`">
<Field orientation="responsive">
<FieldContent><FieldLabel :for="`curator-${index}-tools`">Tools</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<TagsInput
:id="`curator-${index}-tools`"
class="flex-1"
:model-value="(field.state.value ?? [])"
:aria-label="`${def.name} tools`"
@update:model-value="(value) => field.handleChange(value.map(String))"
>
<TagsInputItem v-for="tool in field.state.value ?? []" :key="tool" :value="tool">
<TagsInputItemText />
<TagsInputItemDelete />
</TagsInputItem>
<TagsInputInput placeholder="Add tool" />
</TagsInput>
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${index}.skills`">
<Field orientation="responsive">
<FieldContent><FieldLabel :for="`curator-${index}-skills`">Skills</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Switch :id="`curator-${index}-skills`" :model-value="field.state.value" :aria-label="`${def.name} skills`" @update:model-value="field.handleChange" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${index}.memory_engine`">
<Field orientation="responsive">
<FieldContent><FieldLabel :for="`curator-${index}-memory`">Memory engine</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input :id="`curator-${index}-memory`" :model-value="field.state.value" @blur="field.handleBlur" @update:model-value="field.handleChange" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${index}.conversations`">
<Field orientation="responsive">
<FieldContent><FieldLabel>Conversations</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Switch :model-value="field.state.value" :aria-label="`${def.name} conversations`" @update:model-value="field.handleChange" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" :name="`${index}.model`">
<Field orientation="responsive">
<FieldContent><FieldLabel :for="`curator-${index}-model`">Model</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Select :model-value="field.state.value || ''" @update:model-value="(v) => field.handleChange(v || undefined)">
<SelectTrigger :id="`curator-${index}-model`" class="w-64 font-mono"><SelectValue placeholder="Default model" /></SelectTrigger>
<SelectContent>
<SelectItem v-for="model in [...new Set([...modelOptions, field.state.value].filter(Boolean))]" :key="model" :value="model" class="font-mono">{{ model }}</SelectItem>
</SelectContent>
</Select>
</div>
</Field>
</form.Field>
</FieldGroup>
</Section>
</div>
<div
class="grid grid-cols-1 gap-4 lg:grid-cols-[repeat(auto-fit,minmax(340px,1fr))]"
>
<Empty v-if="loadError">
<EmptyHeader>
<EmptyTitle>{{ errors.common.unresponsive }}</EmptyTitle>
<EmptyDescription>{{ loadError }}</EmptyDescription>
</EmptyHeader>
</Empty>
<Empty v-else-if="curatorsLoaded && !curators.length">
<EmptyHeader>
<EmptyTitle>No curators registered</EmptyTitle>
</EmptyHeader>
</Empty>
<CuratorCard v-for="c in curators" v-else :key="c.name" :curator="c" />
</div>
</div>
</template>
-75
View File
@@ -1,75 +0,0 @@
<script setup lang="ts">
definePage({
name: "settings-plugins",
meta: {
navPath: "/settings",
settings: true,
label: "Plugins",
description: "Extension directories loaded at startup.",
section: "plugins",
},
});
import { Alert, AlertDescription } from "@/components/ui/alert";
import { computed, onMounted } from "vue";
import { storeToRefs } from "pinia";
import PageHeader from "@/base/PageHeader.vue";
import { Field, FieldContent, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { resourcesForPage, useSettingsStore } from "@/stores/settings";
import ApplyStatusRows from "@/settings/ApplyStatusRows.vue";
import DraftHint from "@/settings/DraftHint.vue";
import HistoryLink from "@/settings/HistoryLink.vue";
import KindGate from "@/settings/KindGate.vue";
import { fieldInvalid } from "@/settings/settings-form";
const KIND = "plugin-settings";
const store = useSettingsStore();
const { catalog, catalogError } = storeToRefs(store);
onMounted(store.load);
const resources = computed(() => resourcesForPage(catalog.value, "plugins"));
const form = computed(() => store.formFor(KIND));
const error = computed(() => store.pageErrorFor(KIND));
</script>
<template>
<div>
<PageHeader title="Plugins">
<HistoryLink :kinds="resources.map((r) => r.kind)" />
</PageHeader>
<Alert v-if="catalogError || error" variant="destructive" class="mb-4"><AlertDescription>{{ catalogError || error }}</AlertDescription></Alert>
<KindGate v-if="!form" :kind="KIND" />
<template v-if="form">
<FieldGroup class="@container/field-group">
<form.Field v-slot="{ field }" name="skills_dir">
<Field orientation="responsive" :data-invalid="fieldInvalid(field)">
<FieldContent>
<FieldLabel for="pl-skills">Skills directory</FieldLabel>
<FieldDescription>Empty: work directory. Applies on restart.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input
id="pl-skills"
:model-value="field.state.value"
class="max-w-md font-mono"
:aria-invalid="fieldInvalid(field)"
@blur="field.handleBlur"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="skills_dir" />
</div>
</Field>
</form.Field>
</FieldGroup>
<!-- A restart-required kind can only be applied by a restart, so its
per-process versions live below: a process on an older one is the
restart owed. -->
<ApplyStatusRows :kind="KIND" class="border-t border-border py-4" />
</template>
</div>
</template>
-111
View File
@@ -1,111 +0,0 @@
<script setup lang="ts">
definePage({
name: "skills",
meta: {
navPath: "/settings",
settings: true,
label: "Skills",
description: "Skills Archie can activate.",
section: "skills",
},
});
import ApplyStatusRows from "@/settings/ApplyStatusRows.vue";
import { useSettingsStore } from "@/stores/settings";
import { computed, onMounted, ref } from "vue";
import PageHeader from "@/base/PageHeader.vue";
import { Section } from "@/components/ui/section";
import { Skeleton } from "@/components/ui/skeleton";
import {
Empty,
EmptyDescription,
EmptyHeader,
EmptyTitle,
} from "@/components/ui/empty";
import { Input } from "@/components/ui/input";
import { errors } from "@/copy/errors";
import { api, describeError } from "@/lib/api";
import { useLiveResource } from "@/stores/session";
import SkillCard, { type Skill } from "@/skills/SkillCard.vue";
const skills = ref<Skill[]>([]);
const loaded = ref(false);
const search = ref("");
const loadError = ref<string | null>(null);
let loadGeneration = 0;
async function load() {
const current = ++loadGeneration;
try {
const res = await api.skills<{ skills?: Skill[] }>();
if (current !== loadGeneration) return;
skills.value = res?.skills || [];
loadError.value = null;
} catch (err) {
if (current !== loadGeneration) return;
loadError.value = describeError(err, errors.common.unknown);
} finally {
if (current === loadGeneration) loaded.value = true;
}
}
useLiveResource("skills", () => void load());
onMounted(load);
onMounted(useSettingsStore().load);
const filtered = computed(() => {
const term = search.value.trim().toLowerCase();
if (!term) return skills.value;
return skills.value.filter((s) =>
`${s.name} ${s.description}`.toLowerCase().includes(term),
);
});
</script>
<template>
<div>
<PageHeader title="Skills" />
<ApplyStatusRows kind="skills" class="mb-4" />
<Section title="Catalogue">
<template #action>
<Input
v-model="search"
type="search"
placeholder="Search skills…"
aria-label="Search skills"
class="w-56 max-w-full"
/>
</template>
<div
class="grid grid-cols-1 gap-4 lg:grid-cols-[repeat(auto-fit,minmax(340px,1fr))]"
>
<Empty v-if="loadError">
<EmptyHeader>
<EmptyTitle>{{ errors.common.unresponsive }}</EmptyTitle>
<EmptyDescription>{{ loadError }}</EmptyDescription>
</EmptyHeader>
</Empty>
<div v-else-if="!loaded" role="status" aria-label="Loading skills" class="space-y-2 py-4"><Skeleton class="h-16 w-full" /><Skeleton class="h-16 w-full" /></div>
<Empty v-else-if="!skills.length">
<EmptyHeader>
<EmptyTitle>No skills discovered yet</EmptyTitle>
<EmptyDescription>Add a SKILL.md under .agents/skills/&lt;name&gt;/ in a project, shared or user-global directory.</EmptyDescription>
</EmptyHeader>
</Empty>
<Empty v-else-if="!filtered.length">
<EmptyHeader>
<EmptyTitle>No skills match "{{ search }}"</EmptyTitle>
</EmptyHeader>
</Empty>
<SkillCard
v-for="skill in filtered"
v-else
:key="skill.name"
:skill="skill"
/>
</div>
</Section>
</div>
</template>
-166
View File
@@ -1,166 +0,0 @@
<script setup lang="ts">
definePage({
name: "system-tasks",
meta: {
navPath: "/settings",
settings: true,
label: "Task execution",
description: "Statuses, operator actions, budgets.",
section: "task_execution",
},
});
import { Alert, AlertDescription } from "@/components/ui/alert";
import ApplyStatusRows from "@/settings/ApplyStatusRows.vue";
import KindGate from "@/settings/KindGate.vue";
import { computed, onMounted, ref } from "vue";
import { storeToRefs } from "pinia";
import PageHeader from "@/base/PageHeader.vue";
import { DurationInput, formatGoDuration, parseGoDuration } from "@/components/ui/duration-input";
import { Field, FieldContent, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import {
NumberField,
NumberFieldContent,
NumberFieldDecrement,
NumberFieldIncrement,
NumberFieldInput,
} from "@/components/ui/number-field";
import { resourcesForPage, useSettingsStore } from "@/stores/settings";
import DraftHint from "@/settings/DraftHint.vue";
import HistoryLink from "@/settings/HistoryLink.vue";
const KIND = "workflow-execution-settings";
interface ExecutionSettings {
max_model_tool_steps: number;
max_runtime_seconds: number;
max_consecutive_gate_failures: number;
max_task_runtime_seconds: number | null;
}
const store = useSettingsStore();
const { catalog, catalogError } = storeToRefs(store);
onMounted(store.load);
const resources = computed(() => resourcesForPage(catalog.value, "tasks"));
const limitsForm = computed(() => store.formFor(KIND));
const limits = computed(() => store.draftValue(KIND) as ExecutionSettings | undefined);
const error = computed(() => store.pageErrorFor(KIND));
// The document counts seconds; the input speaks durations.
function durationText(seconds: number | null | undefined): string {
return formatGoDuration((seconds ?? 0) * 1000);
}
// Undefined for text that is not a duration, so the draft keeps its last value.
const durationErrors = ref<Record<string, string>>({});
function commitDuration(field: { handleChange: (value: number) => void }, id: string, text: string): void {
const seconds = durationSeconds(text);
if (seconds === undefined) {
durationErrors.value = { ...durationErrors.value, [id]: "Enter a duration like 30m or 2h." };
return;
}
const next = { ...durationErrors.value };
delete next[id];
durationErrors.value = next;
field.handleChange(seconds);
}
function durationSeconds(text: string): number | undefined {
const ms = parseGoDuration(text);
return ms === null ? undefined : Math.round(ms / 1000);
}
</script>
<template>
<div>
<PageHeader title="Task execution">
<HistoryLink :kinds="resources.map((r) => r.kind)" />
</PageHeader>
<ApplyStatusRows v-for="resource in resources" :key="resource.kind" :kind="resource.kind" class="mb-4" />
<Alert v-if="catalogError || error" variant="destructive" class="mb-4"><AlertDescription>
{{ catalogError || error }}
</AlertDescription></Alert>
<KindGate v-if="!limitsForm" :kind="KIND" />
<FieldGroup v-if="limitsForm && limits" class="@container/field-group">
<limitsForm.Field v-slot="{ field }" name="max_task_runtime_seconds">
<Field orientation="responsive">
<FieldContent>
<FieldLabel for="te-task">Task time limit</FieldLabel>
<FieldDescription>Parked after this. 0 disables.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<DurationInput
id="te-task"
:model-value="durationText(field.state.value)"
:units="['m', 'h']"
@update:model-value="(text: string) => commitDuration(field, 'te-task', text)"
/>
<p v-if="durationErrors['te-task']" class="text-caption text-danger" role="alert">{{ durationErrors['te-task'] }}</p>
<DraftHint :kind="KIND" path="max_task_runtime_seconds" />
</div>
</Field>
</limitsForm.Field>
<limitsForm.Field v-slot="{ field }" name="max_runtime_seconds">
<Field orientation="responsive">
<FieldContent>
<FieldLabel for="te-call">Agent call time limit</FieldLabel>
<FieldDescription>0 disables.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<DurationInput
id="te-call"
:model-value="durationText(field.state.value)"
:units="['s', 'm', 'h']"
@update:model-value="(text: string) => commitDuration(field, 'te-call', text)"
/>
<p v-if="durationErrors['te-call']" class="text-caption text-danger" role="alert">{{ durationErrors['te-call'] }}</p>
<DraftHint :kind="KIND" path="max_runtime_seconds" />
</div>
</Field>
</limitsForm.Field>
<limitsForm.Field v-slot="{ field }" name="max_model_tool_steps">
<Field orientation="responsive">
<FieldContent>
<FieldLabel>Model tool steps</FieldLabel>
<FieldDescription>Per agent call. 0 disables.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<NumberField :model-value="field.state.value" :min="0" class="w-32" @update:model-value="field.handleChange">
<NumberFieldContent>
<NumberFieldDecrement />
<NumberFieldInput class="font-mono" aria-label="Model tool steps" />
<NumberFieldIncrement />
</NumberFieldContent>
</NumberField>
<DraftHint :kind="KIND" path="max_model_tool_steps" />
</div>
</Field>
</limitsForm.Field>
<limitsForm.Field v-slot="{ field }" name="max_consecutive_gate_failures">
<Field orientation="responsive">
<FieldContent>
<FieldLabel>Gate failures in a row</FieldLabel>
<FieldDescription>Then parked.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<NumberField :model-value="field.state.value" :min="0" class="w-32" @update:model-value="field.handleChange">
<NumberFieldContent>
<NumberFieldDecrement />
<NumberFieldInput class="font-mono" aria-label="Gate failures in a row" />
<NumberFieldIncrement />
</NumberFieldContent>
</NumberField>
<DraftHint :kind="KIND" path="max_consecutive_gate_failures" />
</div>
</Field>
</limitsForm.Field>
</FieldGroup>
</div>
</template>
-284
View File
@@ -1,284 +0,0 @@
<script setup lang="ts">
definePage({
name: "settings-tools",
meta: {
navPath: "/settings",
settings: true,
label: "Tools & MCP",
description: "Agent tools and MCP servers.",
section: "tools",
},
});
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import ApplyStatusRows from "@/settings/ApplyStatusRows.vue";
import HistoryLink from "@/settings/HistoryLink.vue";
import { computed, onMounted, ref, watch } from "vue";
import { storeToRefs } from "pinia";
import { Plus } from "@lucide/vue";
import PageHeader from "@/base/PageHeader.vue";
import { Button } from "@/components/ui/button";
import { ByteSizeInput } from "@/components/ui/byte-size-input";
import { DurationInput } from "@/components/ui/duration-input";
import { Field, FieldContent, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { SettingRow } from "@/components/ui/setting-row";
import { Input } from "@/components/ui/input";
import {
InputGroup,
InputGroupAddon,
InputGroupInput,
InputGroupText,
} from "@/components/ui/input-group";
import { Section } from "@/components/ui/section";
import { Switch } from "@/components/ui/switch";
import { resourcesForPage, useSettingsStore } from "@/stores/settings";
import DraftHint from "@/settings/DraftHint.vue";
import McpServerEditor, { type McpServer } from "@/settings/McpServerEditor.vue";
import SecretRefField from "@/settings/SecretRefField.vue";
const KIND = "tool-settings";
interface ToolSettings {
mcp_servers: McpServer[];
minimax: { base_url?:string; enabled: boolean; api_key_ref: { engine: string; key: string }; credential_configured?: boolean };
policy: { max_result_chars: number; spill_dir: string };
web_fetch: { enabled: boolean | null; timeout: string; max_bytes: number; allow_private_networks: boolean };
}
const store = useSettingsStore();
const { catalog, catalogError } = storeToRefs(store);
onMounted(store.load);
const resources = computed(() => resourcesForPage(catalog.value, "tools"));
const form = computed(() => store.formFor(KIND));
const tools = computed(() => store.draftValue(KIND) as ToolSettings | undefined);
const error = computed(() => store.pageErrorFor(KIND));
// An unset web_fetch.enabled means on.
const webFetchOn = computed(() => tools.value?.web_fetch.enabled !== false);
// A new server is held here, outside the draft, until it is named: opening
// the form is not yet a change to save.
const pending = ref<McpServer | null>(null);
const servers = computed(() => tools.value?.mcp_servers ?? []);
const shown = computed(() => (pending.value ? [...servers.value, pending.value] : servers.value));
// The list is written whole: the draft's servers are replaced, not edited in place.
function setServers(next: McpServer[]): void {
if (tools.value) store.setDraftValue(KIND, { ...tools.value, mcp_servers: next });
}
// Rows are keyed by position, so a pending server keeps its row (and focus)
// when it joins the draft at the same position.
function editAt(i: number, next: McpServer): void {
if (i < servers.value.length) setServers(servers.value.map((s, j) => (j === i ? next : s)));
else pending.value = next;
}
function removeAt(i: number): void {
if (i < servers.value.length) setServers(servers.value.filter((_, j) => j !== i));
else pending.value = null;
}
function addServer() {
pending.value = { name: "", transport: "stdio", parallel_tool_calls: false, headers_configured: false };
}
watch(
() => pending.value?.name,
(name) => {
if (!name?.trim() || !pending.value || !tools.value) return;
setServers([...servers.value, { ...pending.value }]);
pending.value = null;
},
);
// Only numeric text becomes a number, as v-model.number did.
function looseNumber(value: string | number): number | string {
if (typeof value === "number") return value;
const n = parseFloat(value);
return Number.isNaN(n) ? value : n;
}
</script>
<template>
<div>
<PageHeader title="Tools & MCP">
<HistoryLink :kinds="resources.map((r) => r.kind)" />
</PageHeader>
<ApplyStatusRows v-for="resource in resources" :key="resource.kind" :kind="resource.kind" class="mb-4" />
<Alert v-if="catalogError || error" variant="destructive" class="mb-4"><AlertDescription>
{{ catalogError || error }}
</AlertDescription></Alert>
<KindGate v-if="!form" :kind="KIND" />
<template v-if="form && tools">
<Section title="MCP servers">
<div class="grid gap-3">
<McpServerEditor
v-for="(server, i) in shown"
:key="i"
:model-value="server"
@update:model-value="(next: McpServer) => editAt(i, next)"
@remove="removeAt(i)"
/>
<Empty v-if="!servers.length && !pending"><EmptyHeader><EmptyTitle>No MCP servers</EmptyTitle></EmptyHeader></Empty>
<div v-if="!pending">
<Button variant="outline" size="sm" @click="addServer">
<Plus data-icon="inline-start" /> Add MCP server</Button>
</div>
</div>
</Section>
<Section title="MiniMax">
<template #action>
<div class="flex items-center gap-3">
<DraftHint :kind="KIND" path="minimax.enabled" />
<form.Field v-slot="{ field }" name="minimax.enabled">
<Switch :model-value="field.state.value" aria-label="MiniMax enabled" @update:model-value="field.handleChange" />
</form.Field>
</div>
</template>
<FieldGroup class="@container/field-group">
<form.Field v-slot="{ field }" name="minimax.api_key_ref">
<Field orientation="responsive">
<FieldContent><FieldLabel id="tools-api-key-label">API key</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1" role="group" aria-labelledby="tools-api-key-label">
<SecretRefField
:model-value="field.state.value"
id-prefix="minimax-key"
:disabled="!tools.minimax.enabled"
@update:model-value="field.handleChange"
/>
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="minimax.base_url">
<Field orientation="responsive">
<FieldContent><FieldLabel for="minimax-url">URL</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input
id="minimax-url"
:model-value="field.state.value"
class="max-w-md font-mono"
@blur="field.handleBlur"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="minimax.base_url" />
</div>
</Field>
</form.Field>
</FieldGroup>
</Section>
<Section title="Web fetch">
<template #action>
<div class="flex items-center gap-3">
<DraftHint :kind="KIND" path="web_fetch.enabled" />
<form.Field v-slot="{ field }" name="web_fetch.enabled">
<Switch :model-value="webFetchOn" aria-label="Web fetch enabled" @update:model-value="field.handleChange" />
</form.Field>
</div>
</template>
<FieldGroup class="@container/field-group">
<form.Field v-slot="{ field }" name="web_fetch.max_bytes">
<Field orientation="responsive">
<FieldContent><FieldLabel for="wf-bytes">Max download</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<ByteSizeInput
id="wf-bytes"
:model-value="field.state.value"
:disabled="!webFetchOn"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="web_fetch.max_bytes" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="web_fetch.timeout">
<Field orientation="responsive">
<FieldContent><FieldLabel for="wf-timeout">Timeout</FieldLabel></FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<DurationInput
id="wf-timeout"
:model-value="field.state.value"
:units="['s', 'm']"
:disabled="!webFetchOn"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="web_fetch.timeout" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="web_fetch.allow_private_networks">
<SettingRow
:tone="field.state.value ? 'danger' : 'default'"
label="Allow private networks"
hint="Host dashboard and Docker API access."
>
<div class="flex min-w-0 flex-wrap items-center gap-3">
<Switch
:model-value="field.state.value"
aria-label="Allow private networks"
:disabled="!webFetchOn"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="web_fetch.allow_private_networks" />
</div>
</SettingRow>
</form.Field>
</FieldGroup>
</Section>
<Section title="Tool output">
<FieldGroup class="@container/field-group">
<form.Field v-slot="{ field }" name="policy.max_result_chars">
<Field orientation="responsive">
<FieldContent>
<FieldLabel for="tp-chars">Max result length</FieldLabel>
<FieldDescription>{{ `≈ ${Math.round(field.state.value / 4).toLocaleString()} tokens` }}</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<InputGroup class="w-48">
<InputGroupInput
id="tp-chars"
:model-value="field.state.value"
type="number"
min="0"
class="font-mono"
@update:model-value="(value: string | number) => field.handleChange(looseNumber(value))"
/>
<InputGroupAddon align="inline-end">
<InputGroupText class="font-mono text-caption">chars</InputGroupText>
</InputGroupAddon>
</InputGroup>
<DraftHint :kind="KIND" path="policy.max_result_chars" />
</div>
</Field>
</form.Field>
<form.Field v-slot="{ field }" name="policy.spill_dir">
<Field orientation="responsive">
<FieldContent>
<FieldLabel for="tp-spill">Spill directory</FieldLabel>
<FieldDescription>Empty: truncate.</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<Input
id="tp-spill"
:model-value="field.state.value"
class="max-w-md font-mono"
@blur="field.handleBlur"
@update:model-value="field.handleChange"
/>
<DraftHint :kind="KIND" path="policy.spill_dir" />
</div>
</Field>
</form.Field>
</FieldGroup>
</Section>
</template>
</div>
</template>
-88
View File
@@ -1,88 +0,0 @@
<script setup lang="ts">
definePage({
name: "task-detail",
meta: {
label: "Task run",
nav: false,
navPath: "/tasks",
section: "tasks",
},
});
import { computed } from "vue";
import { useRoute } from "vue-router";
import { Card, CardContent } from "@/components/ui/card";
import { Tabs } from "@/components/ui/tabs";
import TabBar from "@/tasks/TabBar.vue";
import TaskDetailNotice from "@/tasks/TaskDetailNotice.vue";
import TaskApproval from "@/tasks/TaskApproval.vue";
import TaskHeader from "@/tasks/TaskHeader.vue";
import TaskReviewGate from "@/tasks/TaskReviewGate.vue";
import TaskNotes from "@/tasks/TaskNotes.vue";
import TaskRunPanels from "@/tasks/TaskRunPanels.vue";
import TaskRail from "@/tasks/TaskRail.vue";
import { parseTaskId } from "@/tasks/task-run";
import { provideTaskRun } from "@/tasks/use-task-run";
/**
* The per-task run detail page, reached at /tasks/:id.
*
* One page, one task: which run it is showing, what each stage of that run did,
* its log, what it changed, the configuration it ran under, and the raw record.
* The task id rides in the path and the view state (`tab`, `attempt`) rides in
* the query string, so every view of this page is a deep link that survives a
* reload -- /tasks/42?tab=changes&attempt=2.
*
* The page is a master-detail split pane (docs/prds/task-run-master-detail.md):
* the stage rail is the master and is always visible, the four context panels
* are the inspector and own the tab bar. Below the `lg` breakpoint the rail
* stacks above the inspector.
*
* This file composes the page and nothing else: the reads and the caches are
* use-task-run, the head, meta bar, notes, restart control, attempt selector,
* rail, tab bar and panel area are each their own component. The router keys
* this component on the path (App.vue), so a different :id gets a fresh
* instance rather than diffing the last task's state in place.
*/
const route = useRoute("task-detail");
const rawId = computed(() => String(route.params.id ?? ""));
const taskId = computed(() => parseTaskId(rawId.value));
const run = provideTaskRun(taskId);
</script>
<template>
<TaskDetailNotice v-if="taskId === null" kind="invalid" :raw="rawId" />
<TaskDetailNotice v-else-if="run.missing" kind="missing" :raw="rawId" />
<div v-else>
<TaskHeader :id="rawId" />
<TaskNotes :id="rawId" />
<TaskReviewGate v-if="run.task" :task="run.task" @done="run.refreshAll()" />
<div class="grid items-start gap-6 @3xl:grid-cols-[minmax(0,1fr)_20rem]">
<div class="flex min-w-0 flex-col gap-6">
<TaskApproval
v-if="run.task?.approval === 'plan' && run.task.plan"
:task="run.task"
@done="run.refreshAll()"
/>
<Card class="min-w-0">
<CardContent>
<Tabs
class="gap-4"
:model-value="run.tab"
@update:model-value="run.setTab"
>
<TabBar />
<TaskRunPanels :id="rawId" />
</Tabs>
</CardContent>
</Card>
</div>
<TaskRail class="order-first @3xl:order-none" />
</div>
</div>
</template>
-244
View File
@@ -1,244 +0,0 @@
<script lang="ts">
// The shell's global reduced-motion rule switches CSS transitions and
// animations, NOT the JS smooth scroll this page performs when it reveals a
// deep-linked row. The decision therefore has to be made here, in JavaScript,
// and is exported so it can be tested directly (jsdom implements neither
// matchMedia nor scrollIntoView).
export function prefersReducedMotion(): boolean {
return (
typeof window !== "undefined" &&
window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches === true
);
}
export function revealBehavior(): ScrollBehavior {
return prefersReducedMotion() ? "auto" : "smooth";
}
</script>
<script setup lang="ts">
import { computed, nextTick, onMounted, ref, shallowRef, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import PageHeader from "@/base/PageHeader.vue";
import { keepRows } from "@/lib/keep-unchanged";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { statusList } from "@/lib/task-meta";
import { useLiveResource } from "@/stores/session";
import TaskFilters from "@/tasks/TaskFilters.vue";
import { boardStatus, initialTaskFilter } from "@/tasks/task-filter";
import type { Task } from "@/tasks/task";
import TaskTable from "@/tasks/TaskTable.vue";
import TasksState from "@/tasks/TasksState.vue";
definePage({
name: "tasks",
meta: {
label: "Tasks",
description: "Picked-up issues and their status.",
section: "tasks",
},
});
/**
* The task board: every issue archied has picked up, and where it stands. It
* owns the two things the query string names -- which status is filtered and
* which task a link pointed at -- and composes the rest.
*/
const route = useRoute();
const router = useRouter();
// null means loading: an empty list and a list that has not arrived are
// different states, and only one of them is worth a spinner.
// Rows are replaced, never mutated, so the list is a shallowRef and a reload
// that changed nothing triggers nothing.
const tasks = shallowRef<Task[] | null>(null);
const next = ref<string | null>(null);
const loadingMore = ref(false);
// A failed page load keeps the rows already shown; only a first-load failure
// takes the whole table down (error).
const moreError = ref<string | null>(null);
const error = ref<string | null>(null);
const search = ref("");
const statusQuery = computed(() =>
typeof route.query.status === "string" ? route.query.status : "",
);
const requestedTaskId = computed(() => {
const raw = route.query.task;
const id = Number(typeof raw === "string" ? raw : NaN);
return Number.isSafeInteger(id) && id > 0 ? id : null;
});
// The filter follows the URL as well as writing to it: a dashboard link or a
// back-button step has to move the control, not just load the page behind it.
// It is derived rather than captured, and the catalog is read inside the
// computed: the served catalog lands after this page sets up, so a drop to the
// freeze-dried defaults here would drop a shared link to a status the server
// serves.
const status = computed(() => boardStatus(statusQuery.value, statusList()));
// The server filters by status; search narrows the rows already loaded.
const visible = computed(() => {
const rows = tasks.value ?? [];
const needle = search.value.trim().toLowerCase();
if (!needle) return rows;
return rows.filter((task) => `${task.title ?? ""} ${task.repo ?? ""}`.toLowerCase().includes(needle));
});
// The repo column only earns its width when the rows differ. On a
// single-repository deployment it repeated one value down every row while the
// title was squeezed, so it goes when every visible row shares it.
const showRepo = computed(() => {
const rows = visible.value;
return rows.length < 2 || rows.some((task) => task.repo !== rows[0].repo);
});
// Chat tasks carry a placeholder issue number, so the column goes when no
// visible row names a real issue.
const showIssue = computed(() =>
visible.value.some((task) => task.source !== "chat" && task.source !== "test" && task.issue_number),
);
const state = computed<"loading" | "error" | "empty" | "no-match">(() => {
if (error.value) return "error";
if (tasks.value === null) return "loading";
if (!tasks.value.length) return "empty";
return "no-match";
});
const PAGE = 100;
// Every read bumps the generation; a response that settles after a newer read
// started is dropped, so the previous filter's rows or next cursor never land
// under the current filter.
let loadGeneration = 0;
// load re-reads the board from the top, as many rows as are showing, so a live
// update or a row action does not collapse pages the operator loaded.
async function load() {
const current = ++loadGeneration;
error.value = null;
const limit = Math.min(Math.max(tasks.value?.length ?? 0, PAGE), 500);
try {
const page = await api.taskPage<Task>({ status: status.value || undefined, limit });
if (current !== loadGeneration) return;
tasks.value = keepRows(tasks.value, page.tasks);
next.value = page.next;
moreError.value = null;
} catch (err) {
if (current !== loadGeneration) return;
const message = describeError(err, errors.common.unknown);
if (tasks.value === null) error.value = message;
else moreError.value = message;
}
}
async function loadMore() {
if (!next.value || loadingMore.value) return;
const current = ++loadGeneration;
loadingMore.value = true;
try {
const page = await api.taskPage<Task>({
status: status.value || undefined,
limit: PAGE,
cursor: next.value,
});
if (current !== loadGeneration) return;
tasks.value = [...(tasks.value ?? []), ...page.tasks];
next.value = page.next;
moreError.value = null;
} catch (err) {
if (current !== loadGeneration) return;
moreError.value = describeError(err, errors.common.unknown);
} finally {
loadingMore.value = false;
}
}
useLiveResource("tasks", () => void load(), 5000);
onMounted(load);
watch(status, () => {
tasks.value = null;
void load();
});
// A filter change is a query-only route change, so it must not remount the
// list: the table keeps its identity and only its rows move. The query is the
// only filter state -- the control re-derives from it -- and an empty status is
// dropped from the query rather than written as `?status=`.
function setStatus(value: string) {
const requested = initialTaskFilter(value, statusList());
const query = { ...route.query };
if (requested) query.status = requested;
else delete query.status;
void router.replace({ query });
}
function clearFilters() {
search.value = "";
setStatus("");
}
// A deep link (?task=<id>) reveals the row it names: focus it, so keyboard and
// screen-reader users land where the link pointed, then scroll it into view.
// Once per id -- a reload after a row action must not move the page under the
// operator.
const revealed = ref<number | null>(null);
watch([requestedTaskId, tasks], () => {
const id = requestedTaskId.value;
if (id === null || tasks.value === null || revealed.value === id) return;
revealed.value = id;
void reveal(id);
});
async function reveal(id: number) {
// The row has to be in the DOM before it can be found or scrolled to.
await nextTick();
requestAnimationFrame(() => {
const row = document.querySelector<HTMLElement>(`[data-row-key="${id}"]`);
if (!row) return;
row.focus({ preventScroll: true });
// Optional call: focusing a deep-linked row is a nicety, and not every
// environment implements scrollIntoView on an element.
row.scrollIntoView?.({ block: "center", behavior: revealBehavior() });
});
}
</script>
<template>
<PageHeader title="Tasks">
<TaskFilters
v-if="!error"
:status="status"
:search="search"
@update:status="setStatus"
@update:search="search = $event"
/>
</PageHeader>
<Card>
<CardContent class="flex flex-col gap-3">
<TasksState v-if="error" kind="error" :detail="error" />
<template v-else>
<!--
An action can change what a task is and what it still offers, so the
list is re-read from the server rather than patched in place: the
server owns both the status vocabulary and the controls a status
allows.
-->
<TaskTable :tasks="visible" :show-repo="showRepo" :show-issue="showIssue" @done="load">
<template #state>
<TasksState :kind="state" @retry="load" :detail="search.trim() && next ? 'Search covers the loaded rows only; more pages are not loaded yet.' : null" @clear="clearFilters" />
</template>
</TaskTable>
<Button v-if="next" variant="outline" class="self-center" :disabled="loadingMore" @click="loadMore">Load more</Button>
<p v-if="moreError" class="text-center text-caption text-danger" role="alert">{{ moreError }}</p>
</template>
</CardContent>
</Card>
</template>
-199
View File
@@ -1,199 +0,0 @@
<script setup lang="ts">
import { CheckIcon } from "@lucide/vue";
import { Checkbox, CheckboxGroup, CheckboxIndicator } from "@ui-sdk/vue/checkbox";
import { Field, FieldLabel } from "@ui-sdk/vue/field";
import { Input as SdkInput } from "@ui-sdk/vue/input";
import { NumberInput, NumberInputControl, NumberInputGroup } from "@ui-sdk/vue/number-input";
import { Radio, RadioGroup, RadioIndicator } from "@ui-sdk/vue/radio";
import { TimeInput } from "@ui-sdk/vue/time-input";
import { computed, ref, watch } from "vue";
import { cronForRule, parseCronRule } from "./cron-rule";
import { cronWords } from "./schedule";
type Cadence = "daily" | "weekly" | "monthly" | "custom";
const model = defineModel<string>({ default: "0 9 * * 1-5" });
const cadence = ref<Cadence>("weekly");
const time = ref<string | null>("09:00");
const weekdays = ref<string[]>(["1", "2", "3", "4", "5"]);
const monthDay = ref<number | null>(1);
const customExpression = ref("");
const cadenceOptions: readonly { value: Cadence; label: string }[] = [
{ value: "daily", label: "Daily" },
{ value: "weekly", label: "Weekly" },
{ value: "monthly", label: "Monthly" },
{ value: "custom", label: "Custom" },
];
const weekdayOptions = [
{ value: "0", label: "Sun" },
{ value: "1", label: "Mon" },
{ value: "2", label: "Tue" },
{ value: "3", label: "Wed" },
{ value: "4", label: "Thu" },
{ value: "5", label: "Fri" },
{ value: "6", label: "Sat" },
] as const;
let syncingFromModel = false;
function hydrateFromExpression(expression: string): void {
syncingFromModel = true;
const parsed = parseCronRule(expression);
if (!parsed) {
cadence.value = "custom";
customExpression.value = expression;
} else {
cadence.value = parsed.cadence;
time.value = parsed.time;
if (parsed.cadence === "weekly") {
weekdays.value = parsed.weekdays.map(String);
} else if (parsed.cadence === "monthly") {
monthDay.value = parsed.day;
}
customExpression.value = expression;
}
syncingFromModel = false;
}
watch(
model,
(value) => {
if (value === generatedExpression.value) return;
hydrateFromExpression(value ?? "");
},
{ immediate: true },
);
const generatedExpression = computed<string | null>(() => {
if (cadence.value === "custom") {
return customExpression.value.trim() || null;
}
const clock = time.value;
if (!clock) return null;
if (cadence.value === "weekly") {
return cronForRule({ cadence: "weekly", time: clock, weekdays: weekdays.value.map(Number) });
}
if (cadence.value === "monthly") {
return monthDay.value === null ? null : cronForRule({ cadence: "monthly", time: clock, day: monthDay.value });
}
return cronForRule({ cadence: "daily", time: clock });
});
watch(generatedExpression, (expr) => {
if (syncingFromModel || expr === null) return;
if (model.value !== expr) {
model.value = expr;
}
});
function onCadenceChange(value: string | null): void {
if (!value) return;
const next = value as Cadence;
cadence.value = next;
if (next === "custom") {
customExpression.value = model.value || "0 9 * * 1-5";
} else if (!time.value) {
time.value = "09:00";
}
}
const previewWords = computed(() => {
const expr = generatedExpression.value;
if (!expr) return "";
const words = cronWords(expr);
return words === expr ? "" : words;
});
const validationHint = computed(() => {
if (cadence.value === "custom") return customExpression.value.trim() ? "" : "Enter a five-field cron expression.";
if (!time.value) return "Choose a valid time.";
if (cadence.value === "weekly" && weekdays.value.length === 0) return "Select at least one day.";
if (cadence.value === "monthly" && (monthDay.value === null || monthDay.value < 1 || monthDay.value > 31)) {
return "Choose a day from 1 to 31.";
}
return "";
});
</script>
<template>
<div class="space-y-3">
<Field class="flex flex-col gap-1.5">
<FieldLabel class="text-caption font-medium text-fg-muted">Repeats</FieldLabel>
<RadioGroup :value="cadence" class="grid grid-cols-2 gap-1.5 sm:grid-cols-4" @update:value="onCadenceChange">
<label
v-for="option in cadenceOptions"
:key="option.value"
class="flex cursor-pointer items-center gap-2 rounded-md border border-border bg-background px-2.5 py-2 text-label font-medium transition-colors hover:bg-muted/50 focus-within:ring-2 focus-within:ring-ring has-[[data-checked]]:border-primary has-[[data-checked]]:bg-primary/5 has-[[data-checked]]:text-primary motion-reduce:transition-none"
>
<Radio
:value="option.value"
class="grid size-3.5 shrink-0 place-items-center rounded-full border border-input bg-background text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring data-checked:border-primary"
>
<RadioIndicator class="size-1.5 rounded-full bg-current" />
</Radio>
{{ option.label }}
</label>
</RadioGroup>
</Field>
<div v-if="cadence !== 'custom'" class="grid gap-3 sm:grid-cols-2">
<Field class="flex flex-col gap-1.5">
<FieldLabel class="text-caption font-medium text-fg-muted">Time</FieldLabel>
<TimeInput
v-model:value="time"
:hour-cycle="24"
class="inline-flex h-9 w-fit items-center gap-1 rounded-md border border-input bg-background px-2.5 font-mono text-label shadow-xs focus-within:ring-2 focus-within:ring-ring/40"
/>
</Field>
<Field v-if="cadence === 'monthly'" class="flex flex-col gap-1.5">
<FieldLabel class="text-caption font-medium text-fg-muted">Day of month</FieldLabel>
<NumberInput v-model:value="monthDay" :min="1" :max="31" class="w-28">
<NumberInputGroup class="flex h-9 items-center rounded-md border border-input bg-background shadow-xs focus-within:ring-2 focus-within:ring-ring/40">
<NumberInputControl aria-label="Day of month" class="h-9 w-full bg-transparent px-2.5 font-mono text-label outline-none" />
</NumberInputGroup>
</NumberInput>
</Field>
</div>
<Field v-if="cadence === 'weekly'" class="flex flex-col gap-1.5">
<FieldLabel class="text-caption font-medium text-fg-muted">Days</FieldLabel>
<CheckboxGroup v-model:value="weekdays" class="grid grid-cols-4 gap-1.5 sm:grid-cols-7">
<label
v-for="day in weekdayOptions"
:key="day.value"
class="flex cursor-pointer items-center justify-center gap-1 rounded-md border border-border bg-background px-1.5 py-1.5 text-caption font-medium transition-colors hover:bg-muted/50 focus-within:ring-2 focus-within:ring-ring has-[[data-checked]]:border-primary has-[[data-checked]]:bg-primary/5 has-[[data-checked]]:text-primary motion-reduce:transition-none"
>
<Checkbox
:value="day.value"
class="grid size-3.5 shrink-0 place-items-center rounded border border-input bg-background text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring data-checked:border-primary"
>
<CheckboxIndicator class="size-2.5"><CheckIcon aria-hidden="true" class="size-2.5" /></CheckboxIndicator>
</Checkbox>
{{ day.label }}
</label>
</CheckboxGroup>
</Field>
<Field v-if="cadence === 'custom'" class="flex flex-col gap-1.5">
<FieldLabel class="text-caption font-medium text-fg-muted">Cron expression</FieldLabel>
<SdkInput
v-model:value="customExpression"
placeholder="0 9 * * 1-5"
class="h-9 w-56 rounded-md border border-input bg-background px-2.5 font-mono text-label shadow-xs outline-none focus-visible:ring-2 focus-visible:ring-ring/40"
/>
</Field>
<div class="flex flex-wrap items-baseline justify-between gap-2 rounded-md border border-border bg-muted/40 px-3 py-2">
<output aria-live="polite" class="font-mono text-label font-medium text-foreground">
{{ generatedExpression ?? "— — — — —" }}
</output>
<span v-if="previewWords" class="text-caption text-fg-muted">{{ previewWords }}</span>
<span v-else-if="validationHint" class="text-caption text-danger" role="status">{{ validationHint }}</span>
</div>
</div>
</template>
-105
View File
@@ -1,105 +0,0 @@
<script setup lang="ts">
import { Alert, AlertDescription } from "@/components/ui/alert";
import { computed, ref, watch } from "vue";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { DurationInput } from "@/components/ui/duration-input";
import { Input } from "@/components/ui/input";
import { SettingRow } from "@/components/ui/setting-row";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { useAppearanceStore } from "@/stores/appearance";
import CronRuleBuilder from "./CronRuleBuilder.vue";
import { fromWallTime, toWallTime, type Schedule, type ScheduleTiming } from "./schedule";
/**
* Creates or edits one schedule. A built-in schedule keeps its name; only its
* timing changes here.
*/
const props = defineProps<{ schedule: Schedule | null; title: string }>();
const open = defineModel<boolean>("open", { required: true });
const emit = defineEmits<{ saved: [Schedule] }>();
const appearance = useAppearanceStore();
const name = ref("");
const timing = ref<ScheduleTiming>({ kind: "interval", interval: "24h0m0s" });
const saving = ref(false);
const error = ref("");
watch(
() => [open.value, props.schedule] as const,
([isOpen, schedule]) => {
if (!isOpen || !schedule) return;
name.value = schedule.name;
timing.value = { ...schedule.timing };
error.value = "";
},
{ immediate: true },
);
const kinds = [
{ value: "interval", label: "Every" },
{ value: "cron", label: "Cron" },
{ value: "once", label: "Once" },
] as const;
function chooseKind(value: unknown): void {
if (value === "interval") timing.value = { kind: "interval", interval: "24h0m0s" };
else if (value === "cron") timing.value = { kind: "cron", cron: "0 9 * * 1-5" };
else if (value === "once") timing.value = { kind: "once" };
}
const wallTime = computed({
get: () => toWallTime(timing.value.at, appearance.timeZone),
set: (value: string) => (timing.value.at = fromWallTime(value, appearance.timeZone)),
});
async function save(): Promise<void> {
if (!props.schedule) return;
saving.value = true;
error.value = "";
try {
const saved = await api.scheduleSave<Schedule>(props.schedule.id, {
...props.schedule,
name: name.value.trim(),
timing: timing.value,
});
emit("saved", saved);
open.value = false;
} catch (err) {
error.value = describeError(err, errors.common.unknown);
} finally {
saving.value = false;
}
}
</script>
<template>
<Dialog v-model:open="open">
<DialogContent class="sm:max-w-xl">
<DialogHeader><DialogTitle>{{ title }}</DialogTitle></DialogHeader>
<form v-if="schedule" class="space-y-1" @submit.prevent="save">
<SettingRow label="Name" for="schedule-name">
<Input id="schedule-name" v-model="name" :disabled="schedule.built_in" required />
</SettingRow>
<SettingRow label="When">
<div class="flex flex-col gap-3">
<ToggleGroup type="single" variant="outline" size="sm" :model-value="timing.kind" aria-label="When" @update:model-value="chooseKind">
<ToggleGroupItem v-for="option in kinds" :key="option.value" :value="option.value">{{ option.label }}</ToggleGroupItem>
</ToggleGroup>
<DurationInput v-if="timing.kind === 'interval'" v-model="timing.interval!" :units="['m', 'h']" />
<CronRuleBuilder v-else-if="timing.kind === 'cron'" v-model="timing.cron" />
<Input v-else v-model="wallTime" type="datetime-local" class="w-60 font-mono" aria-label="Run at" required />
</div>
</SettingRow>
<Alert v-if="error" variant="destructive"><AlertDescription>{{ error }}</AlertDescription></Alert>
<DialogFooter>
<Button type="button" variant="ghost" @click="open = false">Cancel</Button>
<Button type="submit" :disabled="saving || !name.trim()">Save</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</template>
-85
View File
@@ -1,85 +0,0 @@
export type CronRule =
| { cadence: "daily"; time: string }
| { cadence: "weekly"; time: string; weekdays: readonly number[] }
| { cadence: "monthly"; time: string; day: number };
const NUMBER = /^\d+$/;
function clockFields(time: string): [number, number] | null {
const match = /^(\d{2}):(\d{2})$/.exec(time);
if (!match) return null;
const hour = Number(match[1]);
const minute = Number(match[2]);
if (hour > 23 || minute > 59) return null;
return [hour, minute];
}
function weekdayField(values: readonly number[]): string | null {
if (!values.length || values.some((day) => !Number.isInteger(day) || day < 0 || day > 6)) {
return null;
}
const days = [...new Set(values)].sort((a, b) => a - b);
if (days.length === 7) return "*";
if (days.join(",") === "1,2,3,4,5") return "1-5";
if (days.join(",") === "0,6") return "0,6";
return days.join(",");
}
function parseWeekdays(field: string): number[] | null {
if (field === "1-5") return [1, 2, 3, 4, 5];
const parts = field.split(",");
if (!parts.length) return null;
const days: number[] = [];
for (const part of parts) {
if (!NUMBER.test(part)) return null;
const value = Number(part);
if (value < 0 || value > 7) return null;
days.push(value % 7);
}
return [...new Set(days)].sort((a, b) => a - b);
}
/** Emits a canonical 5-field cron expression for a guided recurrence rule. */
export function cronForRule(rule: CronRule): string | null {
const clock = clockFields(rule.time);
if (!clock) return null;
const [hour, minute] = clock;
if (rule.cadence === "daily") return `${minute} ${hour} * * *`;
if (rule.cadence === "weekly") {
const weekdays = weekdayField(rule.weekdays);
return weekdays === null ? null : `${minute} ${hour} * * ${weekdays}`;
}
if (rule.cadence === "monthly") {
return Number.isInteger(rule.day) && rule.day >= 1 && rule.day <= 31
? `${minute} ${hour} ${rule.day} * *`
: null;
}
return null;
}
/** Parses a 5-field cron expression into a guided recurrence rule, or null if custom. */
export function parseCronRule(expression: string | undefined): CronRule | null {
const fields = (expression ?? "").trim().split(/\s+/);
if (fields.length !== 5) return null;
const [minuteField, hourField, domField, monthField, dowField] = fields as [
string,
string,
string,
string,
string,
];
if (monthField !== "*" || !NUMBER.test(minuteField) || !NUMBER.test(hourField)) return null;
const minute = Number(minuteField);
const hour = Number(hourField);
if (minute > 59 || hour > 23) return null;
const time = `${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`;
if (domField !== "*") {
if (dowField !== "*" || !NUMBER.test(domField)) return null;
const day = Number(domField);
return day >= 1 && day <= 31 ? { cadence: "monthly", time, day } : null;
}
if (dowField === "*") return { cadence: "daily", time };
const weekdays = parseWeekdays(dowField);
return weekdays?.length ? { cadence: "weekly", time, weekdays } : null;
}
-177
View File
@@ -1,177 +0,0 @@
/**
* The schedules vocabulary: the wire shapes /api/schedules serves and the
* words a schedule's timing reads as. Pure, no fetches.
*/
import { parseGoDuration } from "@/components/ui/duration-input";
import { duration } from "../lib/format.ts";
/** What a schedule belongs to; name is resolved by the server. */
interface ScheduleOwner {
kind: "instance" | "org";
id?: string;
name?: string;
}
export interface ScheduleTiming {
kind: "interval" | "cron" | "once";
/** A Go duration string, for interval. */
interval?: string;
cron?: string;
/** RFC 3339 UTC instant, for once. */
at?: string;
}
export type RunResult = "pending" | "running" | "succeeded" | "failed" | "skipped";
export interface ScheduleRun {
id: number;
schedule_id: string;
scheduled_for: string;
started?: string;
finished?: string;
result: RunResult;
error?: string;
/** Tasks the run's firing started through schedule triggers. */
task_ids?: number[];
}
export interface Schedule {
id: string;
name: string;
owner: ScheduleOwner;
enabled: boolean;
built_in: boolean;
timing: ScheduleTiming;
next_run?: string;
last_run?: ScheduleRun | null;
}
/** The instance's schedule-settings document. */
export interface ScheduleSettings {
time_zone: string;
run_retention: string;
run_retention_count: number;
}
const DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
function plural(n: number, unit: string): string {
return `${n} ${unit}${n === 1 ? "" : "s"}`;
}
/** "Every 6 hours", from a Go duration string. */
function intervalWords(interval: string | undefined): string {
const ms = parseGoDuration(interval ?? "");
if (!ms) return "Every interval";
const minutes = Math.round(ms / 60_000);
if (minutes % 10080 === 0) return minutes === 10080 ? "Every week" : `Every ${plural(minutes / 10080, "week")}`;
if (minutes % 1440 === 0) return minutes === 1440 ? "Every day" : `Every ${plural(minutes / 1440, "day")}`;
if (minutes % 60 === 0) return minutes === 60 ? "Every hour" : `Every ${plural(minutes / 60, "hour")}`;
return minutes === 1 ? "Every minute" : `Every ${plural(minutes, "minute")}`;
}
const NUMBER = /^\d+$/;
function dayWords(field: string): string | null {
if (field === "*") return "Every day";
if (field === "1-5") return "Weekdays";
if (field === "0,6" || field === "6,0") return "Weekends";
const days = field.split(",");
if (!days.every((d) => NUMBER.test(d) && Number(d) <= 7)) return null;
return days.map((d) => DAYS[Number(d) % 7]).join(", ");
}
/**
* A cron expression in words for the common shapes: a fixed time on some
* days, every N minutes, or hourly. Anything else reads as the expression.
*/
export function cronWords(expression: string | undefined): string {
const fields = (expression ?? "").trim().split(/\s+/);
if (fields.length !== 5) return expression ?? "";
const [minute, hour, dom, month, dow] = fields as [string, string, string, string, string];
if (month !== "*") return expression!;
const step = /^\*\/(\d+)$/.exec(minute);
if (step && hour === "*" && dom === "*" && dow === "*") return `Every ${plural(Number(step[1]), "minute")}`;
if (NUMBER.test(minute) && hour === "*" && dom === "*" && dow === "*") return `Hourly at :${minute.padStart(2, "0")}`;
if (!NUMBER.test(minute) || !NUMBER.test(hour)) return expression!;
const at = `${hour.padStart(2, "0")}:${minute.padStart(2, "0")}`;
if (dom !== "*") {
if (dow !== "*" || !NUMBER.test(dom)) return expression!;
return `Monthly on day ${dom} at ${at}`;
}
const days = dayWords(dow);
return days ? `${days} at ${at}` : expression!;
}
/** The schedule's timing in words, with the zone a cron is read in. */
export function timingWords(timing: ScheduleTiming, zone: string, format: (at: string) => string): string {
switch (timing.kind) {
case "interval":
return intervalWords(timing.interval);
case "cron":
return `${cronWords(timing.cron)} (${zone})`;
case "once":
return timing.at ? `Once, ${format(timing.at)}` : "Once";
}
}
/** A run's duration in the one shared format, or "" while it has not finished. */
export function runDuration(run: ScheduleRun | null | undefined): string {
if (!run?.started || !run.finished) return "";
return duration(Date.parse(run.finished) - Date.parse(run.started));
}
// The zone's offset from UTC at instant, in ms. Empty zone is the browser's.
function zoneOffset(instant: number, zone: string): number {
const parts = new Intl.DateTimeFormat("en-US", {
timeZone: zone || undefined,
hourCycle: "h23",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
}).formatToParts(new Date(instant));
const get = (type: string) => Number(parts.find((p) => p.type === type)?.value);
const wall = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour"), get("minute"), get("second"));
return wall - Math.floor(instant / 1000) * 1000;
}
/** A datetime-local value ("2026-10-26T09:00") for an instant, in zone. */
export function toWallTime(iso: string | undefined, zone: string): string {
if (!iso) return "";
const instant = Date.parse(iso);
if (!Number.isFinite(instant)) return "";
return new Date(instant + zoneOffset(instant, zone)).toISOString().slice(0, 16);
}
/** The UTC instant a datetime-local value names in zone. */
export function fromWallTime(wall: string, zone: string): string | undefined {
if (!wall) return undefined;
const guess = Date.parse(`${wall}:00Z`);
if (!Number.isFinite(guess)) return undefined;
const first = guess - zoneOffset(guess, zone);
return new Date(guess - zoneOffset(first, zone)).toISOString();
}
export const RESULT_TONE: Record<RunResult, "ok" | "warn" | "danger" | "idle"> = {
pending: "idle",
running: "idle",
succeeded: "ok",
failed: "danger",
skipped: "warn",
};
/** A new schedule's starting values: runs daily, owned by the instance. */
export function blankSchedule(): Schedule {
return {
id: crypto.randomUUID(),
name: "",
owner: { kind: "instance" },
enabled: true,
built_in: false,
timing: { kind: "interval", interval: "24h0m0s" },
};
}
-47
View File
@@ -1,47 +0,0 @@
<script setup lang="ts">
import { Button } from "@/components/ui/button";
import { computed } from "vue";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import type { ApplyState } from "@/stores/settings";
import { useSettingsStore } from "@/stores/settings";
import { applyStateLabel, applyStateTone } from "./apply-status";
/**
* The processes that have not applied a resource. Silent while every process
* runs the stored version: a row per healthy process is noise. A restart owed
* is the Restart pending banner's, so it is not repeated here.
*/
const props = defineProps<{ kind: string; compact?: boolean }>();
const store = useSettingsStore();
const PROBLEMS: ApplyState[] = ["failed", "unknown", "not-reporting"];
const problems = computed(() =>
store.applyStatusFor(props.kind).filter((row) => PROBLEMS.includes(row.state)),
);
const mode = computed(() => store.catalog.find((item) => item.kind === props.kind)?.apply_mode);
const title = computed(() => store.catalog.find((item) => item.kind === props.kind)?.title ?? props.kind);
</script>
<template>
<Popover v-if="problems.length && compact">
<PopoverTrigger as-child>
<Button type="button" variant="ghost" class="h-auto rounded-sm p-0" :aria-label="`Apply status: ${applyStateLabel(problems[0]!.state, mode)}`">
<Badge :variant="applyStateTone(problems[0]!.state, mode)">{{ applyStateLabel(problems[0]!.state, mode) }}</Badge>
</Button>
</PopoverTrigger>
<PopoverContent align="end" class="w-80">
<ApplyStatusRows :kind="kind" />
</PopoverContent>
</Popover>
<Alert v-else-if="problems.length">
<AlertTitle>{{ title }} is not applied everywhere</AlertTitle>
<AlertDescription>
<p v-for="row in problems" :key="row.process">
<span class="font-mono">{{ row.process }}</span>: {{ applyStateLabel(row.state, mode) }}<template v-if="row.error">. {{ row.error }}</template>
</p>
</AlertDescription>
</Alert>
</template>
-47
View File
@@ -1,47 +0,0 @@
<script setup lang="ts" generic="T">
import { Trash2 } from "@lucide/vue";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import { Button } from "@/components/ui/button";
/**
* A list of configuration cards where one is open at a time. The owning page
* opens a new card when it adds one and refuses to add another while unsaved
* changes exist.
*/
const props = defineProps<{
items: T[];
title: (item: T, index: number) => string;
removeLabel: string;
mono?: boolean;
}>();
const open = defineModel<string>("open", { default: "" });
defineEmits<{ remove: [index: number] }>();
// Keyed by the item's own id when it has one, so removing a card does not
// move another card's child state onto it.
function keyOf(item: T, index: number): string {
return typeof item === "object" && item !== null && "id" in item ? String((item as { id: unknown }).id) : props.title(item, index);
}
</script>
<template>
<Accordion v-model="open" type="single" collapsible class="mb-4 gap-4">
<AccordionItem
v-for="(item, i) in items"
:key="keyOf(item, i)"
:value="String(i)"
class="rounded-xl bg-card px-4 ring-1 ring-foreground/10 not-last:border-b-0"
>
<header class="flex items-center gap-2 [&>h3]:min-w-0 [&>h3]:flex-1">
<AccordionTrigger class="min-w-0 flex-1 items-center text-title hover:no-underline" :class="mono && 'font-mono'">
<span class="truncate">{{ title(item, i) }}</span>
</AccordionTrigger>
<slot name="aside" :item="item" :index="i" />
<Button variant="ghost" size="icon" :aria-label="`${removeLabel} ${title(item, i)}`" @click="$emit('remove', i)"><Trash2 /></Button>
</header>
<AccordionContent>
<slot :item="item" :index="i" />
</AccordionContent>
</AccordionItem>
</Accordion>
</template>
-48
View File
@@ -1,48 +0,0 @@
<script setup lang="ts">
import { Plus, Trash2 } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { joinArgv, splitArgv } from "@/lib/argv";
/** A list of commands, each stored as an argv array and edited as one
* shell-quoted line. */
const props = defineProps<{ label: string; emptyText?: string }>();
const commands = defineModel<string[][] | null>({ required: true });
function add() {
commands.value = [...(commands.value ?? []), []];
}
function remove(i: number) {
const next = [...(commands.value ?? [])];
next.splice(i, 1);
commands.value = next;
}
function set(i: number, argv: string[]) {
const next = [...(commands.value ?? [])];
next[i] = argv;
commands.value = next;
}
</script>
<template>
<div class="grid w-full min-w-0 gap-2">
<p v-if="!commands?.length && props.emptyText" class="text-caption text-fg-subtle">{{ props.emptyText }}</p>
<div v-for="(argv, i) in commands ?? []" :key="i" class="flex min-w-0 items-start gap-2">
<span class="w-5 pt-2 text-right font-mono text-caption text-fg-subtle">{{ i + 1 }}</span>
<Textarea
:model-value="joinArgv(argv)"
rows="1"
class="min-h-9 w-full min-w-0 flex-1 resize-none font-mono text-caption [field-sizing:content]"
placeholder="command"
spellcheck="false"
:aria-label="`${props.label} command ${i + 1}`"
@change="(e: Event) => set(i, splitArgv((e.target as HTMLTextAreaElement).value))"
/>
<Button variant="ghost" size="icon" :aria-label="`Remove ${props.label} command ${i + 1}`" @click="remove(i)"><Trash2 /></Button>
</div>
<div>
<Button variant="outline" size="sm" @click="add"><Plus data-icon="inline-start" />Add command</Button>
</div>
</div>
</template>
-22
View File
@@ -1,22 +0,0 @@
<script setup lang="ts">
import { computed } from "vue";
import { useSettingsStore } from "@/stores/settings";
import { formatValue } from "@/lib/changes";
/**
* The previous value of an edited field, inline at the control: "was 1m0s".
*
* It reads the same per-kind diff the save bar and the route guard read, so
* the hint, the review drawer and the dirty count can never disagree about
* whether a field changed.
*/
const props = defineProps<{ kind: string; path: string }>();
const store = useSettingsStore();
const change = computed(() => store.changeFor(props.kind, props.path));
</script>
<template>
<span v-if="change" class="text-caption whitespace-nowrap text-fg-subtle">was <s class="font-mono">{{ formatValue(change.before) }}</s>
</span>
</template>
@@ -1,100 +0,0 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { X } from "@lucide/vue";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Field, FieldContent, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Section } from "@/components/ui/section";
import { useExtensionsStore, type Extension } from "@/stores/extensions";
import ExtensionSettingField from "./ExtensionSettingField.vue";
const props = defineProps<{
extension: Extension;
/** The messaging service's report for this channel, when it has one. */
status?: { state?: string; detail?: string };
}>();
const store = useExtensionsStore();
const draft = ref<Record<string, string>>({});
watch(() => props.extension.settings, (saved) => { draft.value = { ...saved }; }, { immediate: true });
// Stored keys this version no longer declares. The server refuses them, so
// they are listed and must be removed before the form saves.
const undeclared = computed(() =>
Object.keys(draft.value).filter((key) => !props.extension.settings_schema.some((spec) => spec.key === key)),
);
const dirty = computed(() => {
const saved = props.extension.settings;
const keys = new Set([...Object.keys(saved), ...Object.keys(draft.value)]);
return [...keys].some((key) => (draft.value[key] ?? "").trim() !== (saved[key] ?? ""));
});
function removeKey(key: string): void {
const { [key]: _removed, ...rest } = draft.value;
draft.value = rest;
}
const missing = computed(() =>
props.extension.settings_schema.filter((spec) => spec.required && !(draft.value[spec.key] ?? "").trim()).map((spec) => spec.label),
);
function save(): void {
void store.saveSettings(props.extension, draft.value);
}
function setValue(key: string, value: string): void {
draft.value = { ...draft.value, [key]: value };
}
const badge = computed(() => {
if (!props.extension.enabled) return { label: "Off", tone: "idle" } as const;
const state = props.status?.state;
if (state === "failed") return { label: "Failed", tone: "danger" } as const;
if (state === "degraded") return { label: "Degraded", tone: "warn" } as const;
if (state === "stopped") return { label: "Stopped", tone: "idle" } as const;
return undefined;
});
// The service reports why an enabled channel did not start: missing settings,
// or the error its last run ended with.
const problem = computed(() => (props.extension.enabled && props.status?.state !== "running" ? props.status?.detail : ""));
</script>
<template>
<Section :title="extension.display_name || extension.name">
<template #action>
<Badge v-if="badge" :variant="badge.tone">{{ badge.label }}</Badge>
</template>
<Alert v-if="problem" variant="destructive"><AlertDescription>{{ problem }}</AlertDescription></Alert>
<Alert v-if="undeclared.length" variant="warn">
<AlertDescription>
<p>No longer used by this version. Remove to save:</p>
<ul class="mt-1 flex flex-wrap gap-2">
<li v-for="key in undeclared" :key="key">
<Badge variant="outline" class="gap-1 font-mono">{{ key }}
<button type="button" class="rounded-sm hover:text-fg focus-visible:outline-2" :aria-label="`Remove ${key}`" @click="removeKey(key)"><X class="size-3" /></button>
</Badge>
</li>
</ul>
</AlertDescription>
</Alert>
<FieldGroup class="@container/field-group">
<Field v-for="spec in extension.settings_schema" :key="spec.key" orientation="responsive">
<FieldContent>
<FieldLabel :for="`${extension.name}-${spec.key}`">{{ spec.label }}</FieldLabel>
<FieldDescription v-if="spec.description">{{ spec.description }}</FieldDescription>
</FieldContent>
<div class="flex min-w-0 flex-wrap items-center gap-3 @md/field-group:flex-1">
<ExtensionSettingField
:id="`${extension.name}-${spec.key}`"
:spec="spec"
:model-value="draft[spec.key] ?? ''"
@update:model-value="(value) => setValue(spec.key, value)"
/>
</div>
</Field>
</FieldGroup>
<div class="flex flex-wrap items-center justify-end gap-3">
<span v-if="dirty && missing.length" class="text-caption text-fg-muted">Missing {{ missing.join(", ") }}</span>
<Button size="sm" :disabled="!dirty || undeclared.length > 0 || store.busy === extension.name" @click="save">Save</Button>
</div>
</Section>
</template>
-15
View File
@@ -1,15 +0,0 @@
<script setup lang="ts">
import { History } from "@lucide/vue";
import { Button } from "@/components/ui/button";
/** Opens Settings > Audit filtered to these resource kinds. */
const props = defineProps<{ kinds: string[] }>();
</script>
<template>
<Button variant="ghost" size="sm" as-child>
<RouterLink :to="{ path: '/org/audit', query: { section: props.kinds.join(',') } }">
<History data-icon="inline-start" /> Audit</RouterLink>
</Button>
</template>
-82
View File
@@ -1,82 +0,0 @@
<script setup lang="ts">
import { Item, ItemGroup } from "@/components/ui/item";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { computed, onMounted } from "vue";
import { Plus, X } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Section } from "@/components/ui/section";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { useOrgStore } from "@/stores/org";
import { useSettingsStore } from "@/stores/settings";
import DraftHint from "./DraftHint.vue";
import KindGate from "./KindGate.vue";
/** The identity-grants document: credential services per identity ID. The
* System entry is the default; another identity's list replaces it. */
interface IdentityGrants {
identities?: Record<string, string[] | null>;
}
const SYSTEM_ID = "00000000-0000-5000-8000-000000000001";
const KIND = "identity-grants";
const store = useSettingsStore();
const org = useOrgStore();
onMounted(() => {
void store.load();
org.watchIdentities();
});
const form = computed(() => store.formFor(KIND));
const grants = computed(() => store.draftValue(KIND) as IdentityGrants | undefined);
const error = computed(() => store.pageErrorFor(KIND));
const addable = computed(() =>
org.activeIdentities.filter((a) => a.kind !== "user" && a.kind !== "system" && !(a.id in (grants.value?.identities ?? {}))),
);
const others = computed(() => Object.entries(grants.value?.identities ?? {}).filter(([id]) => id !== SYSTEM_ID));
// Identity ids are free text, so identities are written as whole maps rather
// than by a dotted per-id path.
function setIdentity(id: string, services: string[]) {
form.value?.api.setFieldValue("identities", (prev: Record<string, string[] | null> | undefined) => ({ ...prev, [id]: services }));
}
function removeIdentity(id: string) {
form.value?.api.setFieldValue("identities", (prev: Record<string, string[] | null> | undefined) => {
const { [id]: _, ...rest } = prev ?? {};
return rest;
});
}
</script>
<template>
<Section title="Credential grants">
<Alert v-if="error" variant="destructive" class="mb-3"><AlertDescription>{{ error }}</AlertDescription></Alert>
<KindGate v-if="!grants" :kind="KIND" />
<ItemGroup v-if="grants">
<Item as="div" role="listitem" variant="outline" size="sm" class="flex-wrap">
<span class="w-40 shrink-0 text-label @max-xl:w-24 @max-xl:truncate">Default</span>
<ToggleGroup class="flex-wrap" type="multiple" variant="outline" size="sm" :model-value="grants.identities?.[SYSTEM_ID] ?? []" aria-label="Default grants" @update:model-value="(v) => setIdentity(SYSTEM_ID, v as string[])">
<ToggleGroupItem v-for="service in store.credentialServices" :key="service" :value="service" class="font-mono text-caption">{{ service }}</ToggleGroupItem>
</ToggleGroup>
<DraftHint :kind="KIND" path="identities" />
</Item>
<Item v-for="[id, services] in others" :key="id" as="div" role="listitem" variant="outline" size="sm">
<span class="w-40 shrink-0 truncate text-label @max-xl:w-24">{{ org.identityName(String(id)) }}</span>
<ToggleGroup class="flex-wrap" type="multiple" variant="outline" size="sm" :model-value="services ?? []" :aria-label="`${org.identityName(String(id))} grants`" @update:model-value="(v) => setIdentity(String(id), v as string[])">
<ToggleGroupItem v-for="service in store.credentialServices" :key="service" :value="service" class="font-mono text-caption">{{ service }}</ToggleGroupItem>
</ToggleGroup>
<Button variant="ghost" size="sm" class="ml-auto" :aria-label="`Remove ${org.identityName(String(id))}`" @click="removeIdentity(String(id))"><X /></Button>
</Item>
<div v-if="addable.length" class="py-2.5">
<Select :model-value="undefined" @update:model-value="(id) => setIdentity(String(id), [])">
<SelectTrigger class="w-56" aria-label="Add identity"><Plus class="size-4" /><SelectValue placeholder="Add identity" /></SelectTrigger>
<SelectContent><SelectGroup>
<SelectItem v-for="actor in addable" :key="actor.id" :value="actor.id">{{ actor.display_name || actor.id }}</SelectItem>
</SelectGroup></SelectContent>
</Select>
</div>
</ItemGroup>
</Section>
</template>
-26
View File
@@ -1,26 +0,0 @@
<script setup lang="ts">
import { computed } from "vue";
import { ReadError } from "@/components/ui/read-error";
import { Skeleton } from "@/components/ui/skeleton";
import { useSettingsStore } from "@/stores/settings";
/**
* What a settings page shows until its kind's draft has loaded: the read
* error with Retry, else a skeleton. The store already tracks loading and
* error per kind; this renders them where the form would be.
*/
const props = defineProps<{ kind: string }>();
const store = useSettingsStore();
const state = computed(() => store.stateFor(props.kind));
const error = computed(() => store.pageErrorFor(props.kind));
</script>
<template>
<ReadError v-if="!state.resource && error" :message="error" retry-label="Retry" @retry="store.load()" />
<div v-else role="status" aria-label="Loading settings" class="space-y-2 py-2">
<Skeleton class="h-8 w-full" />
<Skeleton class="h-8 w-full" />
<Skeleton class="h-24 w-full" />
</div>
</template>
-112
View File
@@ -1,112 +0,0 @@
<script setup lang="ts">
import { Label } from "@/components/ui/label";
import { computed, useId } from "vue";
import { Trash2 } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { Section } from "@/components/ui/section";
import { Switch } from "@/components/ui/switch";
import {
TagsInput,
TagsInputInput,
TagsInputItem,
TagsInputItemDelete,
TagsInputItemText,
} from "@/components/ui/tags-input";
export interface McpServer {
name: string;
transport: string;
command?: string;
args?: string[];
work_dir?: string;
url?: string;
sse_endpoint?: string;
parallel_tool_calls: boolean;
headers_configured: boolean;
}
const server = defineModel<McpServer>({ required: true });
// The bound server belongs to a settings form, so an edit emits a new one
// rather than writing into it: a write in place never reaches the form.
function patch(change: Partial<McpServer>): void {
server.value = { ...server.value, ...change };
}
defineEmits<{ remove: [] }>();
const id = useId();
// "" and "stdio" are the same transport to the daemon; "streamablehttp" is
// the long spelling of "http".
const transport = computed({
get: () =>
server.value.transport === "" ? "stdio" : server.value.transport === "streamablehttp" ? "http" : server.value.transport,
set: (value: string) => patch({ transport: value }),
});
const transports = [
{ value: "stdio", label: "stdio" },
{ value: "http", label: "HTTP" },
{ value: "sse", label: "SSE" },
];
const args = computed({
get: () => server.value.args ?? [],
set: (value: string[]) => patch({ args: value }),
});
</script>
<template>
<Section class="mb-0">
<div class="grid gap-4">
<div class="flex items-center gap-3">
<Input
:id="`${id}-name`"
:model-value="server.name"
@update:model-value="(value: string | number) => patch({ name: String(value) })"
aria-label="Server name"
placeholder="name"
class="max-w-56 font-mono"
/>
<ToggleGroup type="single" variant="outline" size="sm" :model-value="transport" aria-label="Transport" @update:model-value="(value) => { if (value) transport = value as typeof transport; }">
<ToggleGroupItem v-for="option in transports" :key="option.value" :value="option.value">{{ option.label }}</ToggleGroupItem>
</ToggleGroup>
<Button variant="ghost" size="icon" class="ml-auto" aria-label="Remove server" @click="$emit('remove')">
<Trash2 />
</Button>
</div>
<template v-if="transport === 'stdio'">
<Label class="grid gap-1 text-caption text-fg-subtle">Command
<Input :model-value="server.command"
@update:model-value="(value: string | number) => patch({ command: String(value) })" class="font-mono" placeholder="npx" />
</Label>
<div class="grid gap-1 text-caption text-fg-subtle">
<span :id="`${id}-args`">Arguments</span>
<TagsInput v-model="args" :aria-labelledby="`${id}-args`" class="font-mono">
<TagsInputItem v-for="arg in args" :key="arg" :value="arg">
<TagsInputItemText />
<TagsInputItemDelete />
</TagsInputItem>
<TagsInputInput placeholder="Add argument" />
</TagsInput>
</div>
<Label class="grid gap-1 text-caption text-fg-subtle">Working directory
<Input :model-value="server.work_dir"
@update:model-value="(value: string | number) => patch({ work_dir: String(value) })" class="font-mono" placeholder="the daemon's working directory" />
</Label>
</template>
<Label v-else-if="transport === 'http'" class="grid gap-1 text-caption text-fg-subtle">URL
<Input :model-value="server.url"
@update:model-value="(value: string | number) => patch({ url: String(value) })" class="font-mono" placeholder="https://host/mcp" />
</Label>
<Label v-else class="grid gap-1 text-caption text-fg-subtle">SSE endpoint
<Input :model-value="server.sse_endpoint"
@update:model-value="(value: string | number) => patch({ sse_endpoint: String(value) })" class="font-mono" />
</Label>
<Label class="flex items-center gap-2 text-label">
<Switch :model-value="server.parallel_tool_calls" @update:model-value="(value: boolean) => patch({ parallel_tool_calls: value })" />
Parallel tool calls</Label>
</div>
</Section>
</template>
-25
View File
@@ -1,25 +0,0 @@
<script setup lang="ts">
import { computed } from "vue";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { useSettingsStore } from "@/stores/settings";
import { restartPendingTitles } from "./apply-status";
const store = useSettingsStore();
// Read from what each process reports it is running, never from this page's
// own saves: a restart that already happened clears it. A restart-required
// kind earns this banner while some process still runs the version it had at
// boot; a live-apply kind reports its lag in its own applied-version rows
// rather than here.
const pending = computed(() =>
restartPendingTitles(store.genericResources, (kind) => store.applyStatusFor(kind)),
);
</script>
<template>
<Alert v-if="pending.length" role="status" variant="warn" class="mb-6">
<AlertTitle class="text-warn">Restart pending</AlertTitle>
<AlertDescription class="text-fg-muted">{{ pending.join(", ") }}</AlertDescription>
</Alert>
</template>
-25
View File
@@ -8,8 +8,6 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { SecretReference } from "@/components/ui/secret-reference";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { api, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { useSecretEnginesStore } from "@/stores/secret-engines";
/** Where a secret lives. Archie resolves it; the value never reaches the UI. */
@@ -37,22 +35,6 @@ const engines = useSecretEnginesStore();
const missing = computed(() => !!engines.engines && !!model.value.engine && !engines.engines.some((engine) => engine.name === model.value.engine));
watch(editing, (open) => { if (open) void engines.load(); });
useIntervalFn(() => { if (editing.value) void engines.load(); }, 15_000);
const checked = ref<boolean>();
const checking = ref(false);
const checkError = ref("");
watch(() => `${model.value.engine}\n${model.value.key}`, () => { checked.value = undefined; checkError.value = ""; });
async function check() {
const ref = { ...model.value };
checking.value = true;
checked.value = undefined;
checkError.value = "";
try {
const result = await api.checkSecret(ref);
if (ref.engine === model.value.engine && ref.key === model.value.key) checked.value = result.resolved;
} catch (cause) {
if (ref.engine === model.value.engine && ref.key === model.value.key) checkError.value = describeError(cause, errors.common.unknown);
} finally { checking.value = false; }
}
</script>
<template>
@@ -85,11 +67,4 @@ async function check() {
<Button variant="ghost" size="sm" @click="editing = false">Done</Button>
</div>
<Alert v-if="editing && engines.error" variant="destructive" class="mt-1"><AlertDescription>{{ engines.error }}</AlertDescription></Alert>
<div v-if="model.engine && model.key" class="mt-1 flex flex-wrap items-center gap-2 text-caption">
<Button variant="ghost" size="sm" :disabled="disabled || checking" @click="check">Check reference</Button>
<span v-if="checking" role="status">Checking…</span>
<span v-else-if="checked" role="status" class="text-ok">Secret available in {{ model.engine }}</span>
<span v-else-if="checked === false" role="status" class="text-danger">No secret at this key in {{ model.engine }}. Store it there or change the key.</span>
<span v-if="checkError" class="text-danger" role="alert">{{ checkError }}</span>
</div>
</template>
+9 -27
View File
@@ -15,33 +15,21 @@ import {
import { Section } from "@/components/ui/section";
import { StatusDot } from "@/components/ui/status-dot";
import { Spinner } from "@/components/ui/spinner";
import { Badge } from "@/components/ui/badge";
import { useSettingsStore } from "@/stores/settings";
import ChangeList from "@/components/ChangeList.vue";
import { diffValues } from "@/lib/changes";
import type { SettingsSchema } from "@/workflows/workflow-yaml";
const store = useSettingsStore();
const { reviewing, savingDrafts: saving } = storeToRefs(store);
onUnmounted(() => { reviewing.value = false; });
const titleOf = (kind: string) =>
store.moduleTitle(kind) ?? store.catalog.find((item) => item.kind === kind)?.title ?? kind;
function fieldLabel(kind: string, path: string): string {
let schema: SettingsSchema;
try { schema = JSON.parse(store.catalog.find((item) => item.kind === kind)?.schema_json || "{}"); }
catch { schema = {}; }
return path.split(".").map((part) => {
if (/^\d+$/.test(part)) {
schema = schema.items ?? {};
return `Item ${Number(part) + 1}`;
}
const named = schema.properties?.[part];
schema = named ?? schema.additionalProperties ?? {};
// A map entry is named by its key; its schema title names every entry alike.
return named ? schema.title || part.replaceAll("_", " ") : part;
}).join(" · ");
}
const titleOf = (kind: string) => store.moduleTitle(kind) ?? kind;
// A map entry is named by its key, so a path reads as its own segments.
const fieldLabel = (path: string) =>
path
.split(".")
.map((part) => (/^\d+$/.test(part) ? `Item ${Number(part) + 1}` : part.replaceAll("_", " ")))
.join(" · ");
const sections = computed(() =>
store.dirtyKinds.map((kind) => ({
kind,
@@ -49,9 +37,6 @@ const sections = computed(() =>
changes: store.changesFor(kind).flatMap((change) => diffValues(change.before, change.after, change.path, true)),
issues: store.issuesFor(kind),
error: store.stateFor(kind).error,
restart:
store.catalog.find((item) => item.kind === kind)?.apply_mode ===
"restart-required",
})),
);
const count = computed(() =>
@@ -116,14 +101,11 @@ async function save() {
{{ invalid.length }} invalid {{ invalid.length === 1 ? "field" : "fields" }} must be fixed before saving.</AlertDescription></Alert>
<Section v-for="section in sections" :key="section.kind" :title="section.title" class="mb-0">
<template #action>
<div class="flex items-center gap-2">
<Badge v-if="section.restart" variant="warn">After restart</Badge>
<Button variant="ghost" size="sm" :disabled="saving" @click="store.resetDraft(section.kind)">Revert</Button>
</div>
<Button variant="ghost" size="sm" :disabled="saving" @click="store.resetDraft(section.kind)">Revert</Button>
</template>
<ChangeList
:changes="section.changes"
:label="(path) => fieldLabel(section.kind, path)"
:label="fieldLabel"
:revertable="!saving"
@revert="(change) => store.revertDraftChange(section.kind, change)"
/>
+1 -3
View File
@@ -5,11 +5,10 @@ import { useRoute } from "vue-router";
import { hiddenPaths, orgNav, settingsNav } from "@/lib/nav";
import { cn } from "@/lib/utils";
import { useSessionStore } from "@/stores/session";
import RestartPendingBanner from "./RestartPendingBanner.vue";
import SettingsSaveBar from "./SettingsSaveBar.vue";
/** The configuration frame shared by the Instance and Organisation areas: the
* scope's sidebar, the restart banner, and the one save bar. */
* scope's sidebar and the one save bar. */
const props = withDefaults(defineProps<{ scope?: "instance" | "org" }>(), {
scope: "instance",
});
@@ -52,7 +51,6 @@ const items = computed(() =>
<!-- At least a screen tall, so the sticky save bar always rests at the
viewport's bottom edge rather than under the last setting. -->
<div class="mx-auto flex min-h-screen w-full min-w-0 max-w-[80ch] flex-1 flex-col">
<RestartPendingBanner />
<!-- Room below the last setting, so it can be scrolled up to eye level. -->
<div class="pb-[40vh]">
<slot />
-70
View File
@@ -1,70 +0,0 @@
import type {
ApplyState,
ApplyStatusRow,
ResourceDescriptor,
} from "../stores/settings.ts";
/** A resource's apply mode, as the control-plane catalog serves it. */
export type ApplyMode = ResourceDescriptor["apply_mode"];
/** Badge tones a row or banner can carry. */
export type ApplyTone = "ok" | "warn" | "danger" | "idle";
/** A change to a restart-required resource cannot apply in-process: only a
* process restart carries it. Every other mode applies without one, so a
* process reporting an older version is a reporting lag, not a restart owed. */
function needsRestart(mode: ApplyMode): boolean {
return mode === "restart-required";
}
/** Titles of restart-required resources whose processes have not all caught
* up: the Restart pending banner's whole content. A live-apply resource is
* never listed, however far behind a process reports. */
export function restartPendingTitles(
resources: Pick<ResourceDescriptor, "kind" | "title" | "apply_mode">[],
rowsFor: (kind: string) => ApplyStatusRow[],
): string[] {
return resources
.filter((resource) => needsRestart(resource.apply_mode))
.filter((resource) =>
rowsFor(resource.kind).some((row) => row.state === "pending-restart"),
)
.map((resource) => resource.title);
}
const LABELS: Record<ApplyState, string> = {
running: "Running",
"pending-restart": "Restart pending",
failed: "Failed",
unknown: "Not reporting",
"not-reporting": "Never reported",
"not-applicable": "Does not apply",
};
/** The wording for one row's state. The derived state is apply-mode-agnostic:
* `pending-restart` only says the process reports an older version, and the
* mode says whether that is a restart owed or a reporting lag. A live kind
* reads as applied, and a lag never borrows the restart wording. */
export function applyStateLabel(state: ApplyState, applyMode: ApplyMode): string {
if (applyMode === "live") {
if (state === "running") return "Applied";
if (state === "pending-restart") return "Behind";
}
return LABELS[state];
}
const TONES: Record<ApplyState, ApplyTone> = {
running: "ok",
"pending-restart": "warn",
failed: "danger",
unknown: "warn",
"not-reporting": "idle",
"not-applicable": "idle",
};
/** The badge tone for one row's state. A live kind that is behind is not a
* warning: nothing is broken and no restart is owed, so it stays neutral. */
export function applyStateTone(state: ApplyState, applyMode: ApplyMode): ApplyTone {
if (state === "pending-restart" && applyMode === "live") return "idle";
return TONES[state];
}
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff. Show more