feat(webui): one save flow for Settings

Edits live in the control-plane store as drafts against the version they
started from, so they survive moving between Settings pages. A sticky bar
counts unsaved changes; the review drawer shows a field-level diff per
section with Revert, and saves the sections one at a time, stopping at the
first failure. A conflicting save rebases the draft onto the latest value.
Restart pending is read from apply status. Per-card Save buttons, Live and
Version badges go; leaving Settings with edits asks first.
This commit is contained in:
sam committed 2026-09-25 15:09:38 +10:00
1 parent 63b08480e8
commit 992c77d9ce
11 files changed
+367 -51

No files matched your search

+4 -2
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import {
Card,
CardAction,
CardContent,
CardDescription,
CardHeader,
@@ -15,14 +16,15 @@ import {
* The card owns its own bottom margin: the pages stack cards directly, with
* nothing between them.
*/
defineProps<{ title?: string; description?: string }>();
defineProps<{ title?: string; description?: string; edited?: boolean }>();
</script>
<template>
<Card class="mb-4">
<Card class="mb-4" :class="edited && 'ring-primary/60'">
<CardHeader v-if="title || description">
<CardTitle v-if="title">{{ title }}</CardTitle>
<CardDescription v-if="description">{{ description }}</CardDescription>
<CardAction v-if="$slots.action"><slot name="action" /></CardAction>
</CardHeader>
<CardContent>
<slot />
+31
View File
@@ -0,0 +1,31 @@
<script setup lang="ts">
import { computed } from "vue";
import { useControlPlaneStore } from "@/stores/control-plane";
const store = useControlPlaneStore();
// Read from what each process reports it is running, never from this page's
// own saves: a restart that already happened clears it.
const pending = computed(() =>
store.genericResources
.filter((item) => item.apply_mode === "restart-required")
.filter((item) =>
store.applyStatusFor(item.kind).some((row) => row.state === "pending-restart"),
)
.map((item) => item.title),
);
</script>
<template>
<div
v-if="pending.length"
role="status"
class="mb-6 rounded-md border border-warn/40 bg-warn-soft px-4 py-3 text-sm"
>
<p class="font-medium text-warn">Restart pending</p>
<p class="mt-0.5 text-fg-muted">
{{ pending.join(", ") }} saved; running processes pick them up when archied restarts.
</p>
</div>
</template>
+120
View File
@@ -0,0 +1,120 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import { Button } from "@/components/ui/button";
import {
Sheet,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import { Spinner } from "@/components/ui/spinner";
import { StatusPill } from "@/components/ui/status-pill";
import { useControlPlaneStore } from "@/stores/control-plane";
import { formatValue } from "./changes";
const store = useControlPlaneStore();
const reviewing = ref(false);
const saving = ref(false);
const titleOf = (kind: string) =>
store.catalog.find((item) => item.kind === kind)?.title ?? kind;
const sections = computed(() =>
store.dirtyKinds.map((kind) => ({
kind,
title: titleOf(kind),
changes: store.changesFor(kind),
error: store.stateFor(kind).error,
restart:
store.catalog.find((item) => item.kind === kind)?.apply_mode ===
"restart-required",
})),
);
const count = computed(() =>
sections.value.reduce((n, s) => n + s.changes.length, 0),
);
const needsRestart = computed(() => sections.value.some((s) => s.restart));
function discardAll() {
for (const kind of store.dirtyKinds) store.resetDraft(kind);
reviewing.value = false;
}
async function save() {
saving.value = true;
try {
const outcome = await store.saveDrafts();
if (!outcome.failed) reviewing.value = false;
} finally {
saving.value = false;
}
}
</script>
<template>
<div
v-if="count > 0"
class="sticky bottom-0 z-30 mt-6 flex items-center gap-3 rounded-lg border border-border bg-popover px-4 py-3 shadow-[var(--shadow-md)]"
role="region"
aria-label="Unsaved changes"
>
<span class="size-2 shrink-0 rounded-full bg-primary" aria-hidden="true" />
<p class="min-w-0 flex-1 truncate text-sm">
<span class="font-medium">{{ count }} unsaved {{ count === 1 ? "change" : "changes" }}</span>
<span class="text-fg-subtle"> · {{ sections.map((s) => s.title).join(", ") }}</span>
</p>
<Button variant="ghost" size="sm" @click="discardAll">Discard</Button>
<Button size="sm" @click="reviewing = true">Review and save</Button>
</div>
<Sheet v-model:open="reviewing">
<SheetContent class="flex w-full flex-col gap-0 sm:max-w-[480px]">
<SheetHeader>
<SheetTitle>Review {{ count }} {{ count === 1 ? "change" : "changes" }}</SheetTitle>
<SheetDescription>
{{ sections.length }} {{ sections.length === 1 ? "section" : "sections" }},
each saved as its own version, in this order. A failure stops the rest.
</SheetDescription>
</SheetHeader>
<div class="flex-1 space-y-3 overflow-y-auto px-4 pb-4">
<p
v-if="needsRestart"
class="rounded-md border border-warn/40 bg-warn-soft px-3 py-2 text-sm text-warn"
>
Some of these apply after archied restarts.
</p>
<section
v-for="section in sections"
:key="section.kind"
class="rounded-lg border border-border bg-card"
>
<header class="flex items-center gap-2 border-b border-border px-3 py-2">
<h3 class="flex-1 truncate text-sm font-medium">{{ section.title }}</h3>
<StatusPill v-if="section.restart" tone="warn">After restart</StatusPill>
<Button variant="ghost" size="sm" @click="store.resetDraft(section.kind)">
Revert
</Button>
</header>
<ul class="divide-y divide-border font-mono text-xs">
<li v-for="change in section.changes" :key="change.path" class="px-3 py-2">
<p class="mb-1 text-fg-subtle">{{ change.path }}</p>
<p class="truncate text-danger">− {{ formatValue(change.before) }}</p>
<p class="truncate text-ok">+ {{ formatValue(change.after) }}</p>
</li>
</ul>
<p v-if="section.error" class="border-t border-border px-3 py-2 text-sm text-danger" role="alert">
{{ section.error }}
</p>
</section>
</div>
<SheetFooter class="flex-row justify-end gap-2 border-t border-border">
<Button variant="ghost" @click="discardAll">Discard all</Button>
<Button :disabled="saving" @click="save">
<Spinner v-if="saving" data-icon="inline-start" /> Save
</Button>
</SheetFooter>
</SheetContent>
</Sheet>
</template>
+24 -2
View File
@@ -1,13 +1,33 @@
<script setup lang="ts">
import { computed } from "vue";
import { useRoute } from "vue-router";
import { computed, onBeforeUnmount, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { hidden } from "@/lib/capabilities";
import { settingsNav } from "@/lib/nav";
import { cn } from "@/lib/utils";
import { useControlPlaneStore } from "@/stores/control-plane";
import RestartPendingBanner from "./RestartPendingBanner.vue";
import SettingsSaveBar from "./SettingsSaveBar.vue";
const route = useRoute();
const items = computed(() => settingsNav(hidden.value));
// Drafts live in the store, so moving between Settings pages keeps them;
// leaving Settings, or the page, with edits unsaved asks first.
const store = useControlPlaneStore();
const dirty = () => store.dirtyKinds.length > 0;
const removeGuard = useRouter().beforeEach((to) => {
if (to.meta.settings || !dirty()) return true;
return window.confirm("Leave Settings with unsaved changes?");
});
const warnUnload = (event: BeforeUnloadEvent) => {
if (dirty()) event.preventDefault();
};
onMounted(() => window.addEventListener("beforeunload", warnUnload));
onBeforeUnmount(() => {
removeGuard();
window.removeEventListener("beforeunload", warnUnload);
});
</script>
<template>
@@ -41,7 +61,9 @@ const items = computed(() => settingsNav(hidden.value));
</ul>
</nav>
<div class="min-w-0 max-w-[960px] flex-1">
<RestartPendingBanner />
<slot />
<SettingsSaveBar />
</div>
</div>
</template>
+17 -40
View File
@@ -1,11 +1,8 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { computed } from "vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { StatusPill } from "@/components/ui/status-pill";
import {
cloneControlPlaneValue,
useControlPlaneStore,
type ResourceDescriptor,
} from "@/stores/control-plane";
@@ -19,7 +16,6 @@ const props = defineProps<{
}>();
const store = useControlPlaneStore();
const state = computed(() => store.stateFor(props.descriptor.kind));
const draft = ref<unknown>({});
// The schema the descriptor derives from its document type: the editor reads
// it for labels, hints, formatted placeholders and the shape of a new row. A
@@ -27,25 +23,24 @@ const draft = ref<unknown>({});
// rendering the value alone.
const schema = computed(() => parseSchema(props.descriptor.schema_json));
watch(
() => state.value.resource,
(resource) => {
if (resource) draft.value = cloneControlPlaneValue(resource.value);
// Edits land in the store's draft; the Settings save bar saves every edited
// resource together.
const draft = computed({
get: () => store.drafts[props.descriptor.kind]?.value,
set: (value) => {
const current = store.drafts[props.descriptor.kind];
if (current) current.value = value;
},
{ immediate: true },
);
async function save(): Promise<void> {
await store.replace(
props.descriptor.kind,
cloneControlPlaneValue(draft.value),
);
}
});
const edited = computed(() => store.changesFor(props.descriptor.kind).length > 0);
</script>
<template>
<ConfigCard :title="descriptor.title">
<form class="space-y-5" @submit.prevent="save">
<ConfigCard :title="descriptor.title" :edited="edited">
<template v-if="descriptor.apply_mode === 'restart-required'" #action>
<StatusPill tone="warn">Applies after restart</StatusPill>
</template>
<div v-if="draft !== undefined" class="space-y-5">
<StructuredValueEditor
v-model="draft"
:path="rootPath ?? descriptor.kind"
@@ -55,24 +50,6 @@ async function save(): Promise<void> {
<p v-if="state.error" class="text-sm text-destructive" role="alert">
{{ state.error }}
</p>
<div class="flex flex-wrap items-center justify-between gap-3">
<div class="flex items-center gap-2">
<Badge :variant="state.stream === 'live' ? 'ok' : 'warn'">{{
state.stream === "live" ? "Live" : "Connecting"
}}</Badge>
<Badge
v-if="descriptor.apply_mode === 'restart-required'"
variant="warn"
>Restart required</Badge
>
<span v-if="state.resource" class="text-xs text-muted-foreground"
>Version {{ state.resource.version }}</span
>
</div>
<Button type="submit" :disabled="state.saving || state.loading">
<Spinner v-if="state.saving" data-icon="inline-start" /> Save changes
</Button>
</div>
</form>
</div>
</ConfigCard>
</template>
+1 -1
View File
@@ -16,7 +16,7 @@ onMounted(controlPlane.load);
<template>
<div>
<PageHeader title="Task settings" />
<PageHeader title="Task execution" />
<p v-if="catalogError" class="text-sm text-destructive" role="alert">
{{ catalogError }}
+58
View File
@@ -0,0 +1,58 @@
/** One changed leaf of a settings document. */
export interface Change {
path: string;
before: unknown;
after: unknown;
}
const isRecord = (v: unknown): v is Record<string, unknown> =>
typeof v === "object" && v !== null && !Array.isArray(v);
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
/**
* diffValues lists what changed between two settings documents, one entry per
* changed leaf. Objects recurse by key and arrays of objects by index; an
* array of plain values is one leaf, because its entries have no identity of
* their own. A row added or removed is a single change.
*/
export function diffValues(before: unknown, after: unknown, path = ""): Change[] {
if (same(before, after)) return [];
const at = (key: string | number) => (path ? `${path}.${key}` : String(key));
if (isRecord(before) && isRecord(after)) {
const keys = [...new Set([...Object.keys(before), ...Object.keys(after)])];
return keys.flatMap((key) => diffValues(before[key], after[key], at(key)));
}
const rows = (v: unknown) => Array.isArray(v) && v.some(isRecord);
if (Array.isArray(before) && Array.isArray(after) && (rows(before) || rows(after))) {
const length = Math.max(before.length, after.length);
return Array.from({ length }, (_, i) => diffValues(before[i], after[i], at(i))).flat();
}
return [{ path, before, after }];
}
/**
* saveInOrder saves each kind in turn and stops at the first failure: saves
* are not atomic across kinds, so the ones after a failure stay unsaved
* rather than landing on top of a half-applied set.
*/
export async function saveInOrder(
kinds: string[],
save: (kind: string) => Promise<boolean>,
): Promise<{ saved: string[]; failed: string | undefined; untouched: string[] }> {
const saved: string[] = [];
for (const [i, kind] of kinds.entries()) {
if (!(await save(kind)))
return { saved, failed: kind, untouched: kinds.slice(i + 1) };
saved.push(kind);
}
return { saved, failed: undefined, untouched: [] };
}
/** formatValue renders one side of a change for the review diff. */
export function formatValue(value: unknown): string {
if (value === undefined) return "unset";
if (typeof value === "string") return value === "" ? '""' : value;
return JSON.stringify(value);
}
+55 -2
View File
@@ -2,6 +2,8 @@ import { defineStore } from "pinia";
import { computed, onScopeDispose, reactive, ref, watch } from "vue";
import { useLiveUpdatesStore } from "./live-updates.ts";
import { diffValues, saveInOrder, type Change } from "../settings/changes.ts";
export interface ResourceDescriptor {
kind: string;
title: string;
@@ -226,6 +228,11 @@ export function commandBody(value: unknown, expectedVersion: number): string {
return JSON.stringify({ value, expected_version: expectedVersion });
}
interface Draft {
base: ControlPlaneResource;
value: unknown;
}
export const useControlPlaneStore = defineStore("control-plane", () => {
const catalog = ref<ResourceDescriptor[]>([]);
const catalogError = ref("");
@@ -259,6 +266,43 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
state.resource = resource;
state.error = undefined;
state.conflict = false;
if (changesFor(resource.kind).length === 0) resetDraft(resource.kind);
}
// An edit in progress, against the version it started from. A save sends
// that version, so a change made elsewhere meanwhile is a conflict rather
// than silently overwritten.
const drafts = reactive<Record<string, Draft>>({});
function resetDraft(kind: string): void {
const resource = stateFor(kind).resource;
if (resource)
drafts[kind] = { base: resource, value: cloneControlPlaneValue(resource.value) };
}
function changesFor(kind: string): Change[] {
const draft = drafts[kind];
return draft ? diffValues(draft.base.value, draft.value) : [];
}
const dirtyKinds = computed(() =>
genericResources.value
.map(({ kind }) => kind)
.filter((kind) => changesFor(kind).length > 0),
);
async function saveDraft(kind: string): Promise<boolean> {
const draft = drafts[kind];
if (!draft) return true;
const saved = await replace(kind, cloneControlPlaneValue(draft.value), draft.base.version);
if (saved) resetDraft(kind);
else if (stateFor(kind).conflict && stateFor(kind).resource)
drafts[kind] = { base: stateFor(kind).resource!, value: draft.value };
return saved;
}
function saveDrafts() {
return saveInOrder(dirtyKinds.value, saveDraft);
}
async function loadResource(kind: string): Promise<void> {
@@ -334,7 +378,11 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
}
}
async function replace(kind: string, value: unknown): Promise<boolean> {
async function replace(
kind: string,
value: unknown,
expectedVersion?: number,
): Promise<boolean> {
const state = stateFor(kind);
if (!state.resource || state.saving) return false;
state.saving = true;
@@ -343,7 +391,7 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
try {
const response = await request<ResourceResponse>(
`/api/control-plane/resources/${encodeURIComponent(kind)}/commands/replace`,
{ method: "POST", body: commandBody(value, state.resource.version) },
{ method: "POST", body: commandBody(value, expectedVersion ?? state.resource.version) },
);
apply(response.resource);
await loadApplyStatus();
@@ -393,6 +441,11 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
return {
applyStatusFor,
changesFor,
dirtyKinds,
drafts,
resetDraft,
saveDrafts,
catalog,
catalogError,
states,