import { defineStore } from "pinia"; import { computed, onScopeDispose, reactive, ref, shallowReactive, watch } from "vue"; import { useSessionStore } from "./session.ts"; import { api } from "../lib/api.ts"; import type { ConfigView } from "../settings/types.ts"; import { diffValues, revertChange, saveInOrder, type Change } from "../lib/changes.ts"; import { collectIssues, draftValidators, type BlockingField, type FieldIssue, } from "../settings/validation.ts"; import { createSettingsForm, type SettingsForm } from "../settings/settings-form.ts"; export interface ResourceDescriptor { kind: string; title: string; schema_json: string; commands: string[]; apply_mode?: "live" | "restart-required" | "domain-managed"; query_service?: string; command_service?: string; /** Factory value this resource can be restored to, as JSON. */ defaults_json?: string; } export interface ControlPlaneResource { kind: string; version: number; value: unknown; updated_at?: string; } interface ResourceResponse { resource: ControlPlaneResource; } /** One process's report about one resource kind, as the server derives it. * `state` is liveness only: the server knows whether a record went stale, not * which version the page is showing. */ export interface ApplyStatusRecord { process: string; kind: string; applied_version: number; error?: string; reported_at: string; state: "current" | "failed" | "unknown"; } export interface ApplyStatusResponse { records: ApplyStatusRecord[]; processes: string[]; applicability?: Record; } /** What the settings page says about one process for one resource. */ export type ApplyState = "running" | "pending-restart" | "failed" | "unknown" | "not-reporting" | "not-applicable"; export interface ApplyStatusRow { process: string; state: ApplyState; version: number; error: string; storedVersion?: number; reportedAt?: string; } /** applyStatusForKind reads every known process against the stored version, so * a process that has never reported is a row saying so rather than a missing * one. Staleness wins over the version comparison: a record that stopped being * re-stamped describes a process that may no longer exist, so it can never * read as running. */ export function applyStatusForKind( records: ApplyStatusRecord[], processes: string[], kind: string, storedVersion: number, applicability?: Record, ): ApplyStatusRow[] { return processes.map((process) => { if (applicability && !(applicability[kind] ?? []).includes(process)) return { process, state: "not-applicable" as const, version: 0, error: "", storedVersion }; const record = records.find( (entry) => entry.process === process && entry.kind === kind, ); if (!record) return { process, state: "not-reporting" as const, version: 0, storedVersion, error: "", }; const row = { process, version: record.applied_version, storedVersion, reportedAt: record.reported_at, error: record.error ?? "", }; if (record.state === "unknown") return { ...row, state: "unknown" as const }; if (record.state === "failed") return { ...row, state: "failed" as const }; if (record.applied_version < storedVersion) return { ...row, state: "pending-restart" as const }; return { ...row, state: "running" as const }; }); } /** One entry of a resource's audit trail. `value` is what that version held, * which is also the payload a restore replays through the replace command. */ export interface ResourceRevision { version: number; value: unknown; actor: string; actor_name?: string; source: string; request_id: string; at?: string; } /** The revisions the resource history endpoint returns. */ interface HistoryResponse { revisions?: ResourceRevision[]; } export interface ResourceState { resource?: ControlPlaneResource; loading: boolean; saving: boolean; error?: string; conflict: boolean; } class ControlPlaneError extends Error { readonly status: number; constructor(message: string, status: number) { super(message); this.status = status; } } async function request(path: string, init: RequestInit = {}): Promise { const headers = new Headers(init.headers); headers.set("Accept", "application/json"); if (init.method && init.method !== "GET") { headers.set("Content-Type", "application/json"); headers.set("X-Archie-CSRF", "1"); } const response = await fetch(path, { ...init, headers, signal: AbortSignal.timeout(15_000), }); if (!response.ok) throw new ControlPlaneError( (await response.text()).trim() || response.statusText, response.status, ); return response.json() as Promise; } export type ControlPlanePage = | "tasks" | "alerts" | "models" | "repositories" | "connections" | "channels" | "scheduling" | "tools" | "soul" | "schedules" | "plugins" | "containers" | "review"; const PAGE_RESOURCES: Record = { tasks: ["workflow-execution-settings"], alerts: ["task-policy"], models: ["provider-settings", "model-aliases", "org-model-policy"], repositories: ["repository-policies"], connections: ["forge-connections"], channels: ["channel-settings"], scheduling: ["scheduling-policy"], tools: ["tool-settings"], soul: ["soul"], schedules: ["schedule-settings"], plugins: ["plugin-settings"], containers: ["container-runtime-policies"], review: ["review-settings"], }; export function cloneControlPlaneValue(value: T): T { return JSON.parse(JSON.stringify(value)) as T; } export function resourcesForPage( catalog: ResourceDescriptor[], page: ControlPlanePage, ): ResourceDescriptor[] { const ownership = PAGE_RESOURCES[page]; return ownership.flatMap((kind) => catalog.filter((descriptor) => descriptor.kind === kind), ); } export function commandBody(value: unknown, expectedVersion: number): string { return JSON.stringify({ value, expected_version: expectedVersion }); } export const useSettingsStore = defineStore("settings", () => { /** The daemon's published configuration projection: what is in force. */ const config = ref(null); async function loadConfig(): Promise { try { config.value = await api.config(); } catch { // Keep whatever was last read: the projection is context, not the page. } } const catalog = ref([]); const catalogError = ref(""); const reviewing = ref(false); const states = reactive>({}); const live = useSessionStore(); const applyStatus = ref({ records: [], processes: [] }); const genericResources = computed(() => catalog.value.filter( (item) => item.apply_mode !== "domain-managed" && !item.query_service && item.commands.includes("replace"), ), ); function stateFor(kind: string): ResourceState { if (!states[kind]) states[kind] = { loading: false, saving: false, conflict: false, }; return states[kind]; } function pageErrorFor(kind: string): string | undefined { return reviewing.value && changesFor(kind).length > 0 ? undefined : stateFor(kind).error; } function apply(resource: ControlPlaneResource): void { const state = stateFor(resource.kind); if (!state.resource || resource.version >= state.resource.version) state.resource = resource; state.error = undefined; state.conflict = false; if (!forms[resource.kind]) createForm(resource); else if (changesFor(resource.kind).length === 0) resetDraft(resource.kind); } // One edit form per kind, against the version its edit started from. A save // sends that version, so a change made elsewhere meanwhile is a conflict // rather than silently overwritten. const forms = shallowReactive>({}); const bases = shallowReactive>({}); function createForm(resource: ControlPlaneResource): void { const kind = resource.kind; bases[kind] = resource; forms[kind] = createSettingsForm( cloneControlPlaneValue(resource.value), draftValidators[kind], (value) => saveValue(kind, value), ); } /** The form a page binds its fields to; undefined until the kind loads. */ function formFor(kind: string): SettingsForm | undefined { return forms[kind]; } /** The edited value of a kind, read-only: edits go through its form. */ function draftValue(kind: string): unknown { return forms[kind]?.values.value; } /** Replaces a form's values, keeping the version the edit started from. */ function setDraftValue(kind: string, value: unknown): void { forms[kind]?.reset(cloneControlPlaneValue(value), { keepDefaultValues: true }); } /** Sets or, with undefined, removes one entry of a map-shaped kind. Map keys * are free text (alias names, profile names, identity IDs), and a key holding * "." or "[" is not a usable TanStack field path, so map entries are written * through the whole value rather than setFieldValue. */ function setDraftEntry(kind: string, key: string, value: unknown): void { const current = (draftValue(kind) ?? {}) as Record; const { [key]: _, ...rest } = current; setDraftValue(kind, value === undefined ? rest : { ...current, [key]: value }); } function resetDraft(kind: string): void { const resource = stateFor(kind).resource; const form = forms[kind]; if (!resource || !form) return; bases[kind] = resource; form.reset(cloneControlPlaneValue(resource.value)); } /** Undoes one change in a draft and keeps the rest. */ function revertDraftChange(kind: string, change: Change): void { if (forms[kind]) setDraftValue(kind, revertChange(draftValue(kind), change)); } /** Loads an earlier version into the draft and opens the review, so a restore * is applied the same deliberate way an edit is. */ function stageRestore(kind: string, value: unknown): void { const resource = stateFor(kind).resource; if (!resource || !forms[kind]) return; bases[kind] = resource; setDraftValue(kind, value); reviewing.value = true; } // The diff for every form, computed once per change. The save bar, the // inline "was old" hint, the inline errors and the route guard all read // this one map, so no consumer forks its own notion of what is dirty. const changesByKind = computed>(() => { const byKind: Record = {}; for (const [kind, form] of Object.entries(forms)) byKind[kind] = diffValues(bases[kind]!.value, form.values.value); return byKind; }); function changesFor(kind: string): Change[] { return changesByKind.value[kind] ?? []; } /** The change for one dotted leaf path, the lookup the inline "was old" * hint uses. */ function changeFor(kind: string, path: string): Change | undefined { return changesFor(kind).find((change) => change.path === path); } const dirtyKinds = computed(() => genericResources.value .map(({ kind }) => kind) .filter((kind) => changesFor(kind).length > 0), ); // Drafts survive in-app navigation; only unloading the document can lose them. const warnUnload = (event: BeforeUnloadEvent) => event.preventDefault(); if (typeof window !== "undefined") { watch(dirtyKinds, (kinds) => { window.removeEventListener("beforeunload", warnUnload); if (kinds.length) window.addEventListener("beforeunload", warnUnload); }); onScopeDispose(() => window.removeEventListener("beforeunload", warnUnload)); } /** Invalid fields across every dirty section. Derived from dirtyKinds, so a * save can only be blocked by a section that has something to save. */ const invalidFields = computed(() => collectIssues(dirtyKinds.value, draftValue, draftValidators), ); /** The issues for one section, empty unless it has unsaved changes. The * pages read this, so an inline error and the save bar can never disagree. */ function issuesFor(kind: string): FieldIssue[] { if (changesFor(kind).length === 0) return []; const validate = draftValidators[kind]; return validate ? validate(draftValue(kind)) : []; } // The form's submit handler: validation has passed by the time this runs. async function saveValue(kind: string, value: unknown): Promise { const base = bases[kind]; if (!base) return false; const saved = await replace(kind, cloneControlPlaneValue(value), base.version); if (saved) resetDraft(kind); // A conflict keeps the operator's values against the latest version, so a // second save is a deliberate overwrite of what they have now seen. else if (stateFor(kind).conflict && stateFor(kind).resource) bases[kind] = stateFor(kind).resource!; return saved; } function saveDraft(kind: string): Promise { const form = forms[kind]; return form ? form.submit() : Promise.resolve(true); } function saveDrafts() { return saveInOrder(dirtyKinds.value, saveDraft); } async function loadResource(kind: string): Promise { const state = stateFor(kind); state.loading = true; try { apply( ( await request( `/api/control-plane/resources/${encodeURIComponent(kind)}`, ) ).resource, ); } catch (error) { state.error = String((error as Error).message || error); } finally { state.loading = false; } } const stopResource = live.subscribe("control-plane", (data) => { const resource = (data as ResourceResponse).resource; if (resource?.kind) apply(resource); }); const stopStatus = live.subscribe("apply-status", (data) => { applyStatus.value = data as ApplyStatusResponse; }); onScopeDispose(() => { stopResource(); stopStatus(); }); /** Re-read on every load and after each save, so the page reflects what the * processes did with the edit rather than what was stored. A failure leaves * the previous rows: apply status is a diagnostic, and losing it must not * take the settings page with it. */ async function loadApplyStatus(): Promise { try { applyStatus.value = await request( "/api/control-plane/apply-status", ); } catch { // Keep whatever was last read. } } /** Rows for one resource, every known process included. */ function applyStatusFor(kind: string): ApplyStatusRow[] { return applyStatusForKind( applyStatus.value.records, applyStatus.value.processes, kind, stateFor(kind).resource?.version ?? 0, applyStatus.value.applicability, ); } async function load(): Promise { try { const response = await request<{ resources?: ResourceDescriptor[] }>( "/api/control-plane/catalog", ); catalog.value = response.resources ?? []; catalogError.value = ""; await loadApplyStatus(); await Promise.all(genericResources.value.map(({ kind }) => loadResource(kind))); } catch (error) { catalogError.value = String((error as Error).message || error); } } async function replace( kind: string, value: unknown, expectedVersion?: number, ): Promise { const state = stateFor(kind); if (!state.resource || state.saving) return false; state.saving = true; state.error = undefined; state.conflict = false; try { const response = await request( `/api/control-plane/resources/${encodeURIComponent(kind)}/commands/replace`, { method: "POST", body: commandBody(value, expectedVersion ?? state.resource.version) }, ); apply(response.resource); await loadApplyStatus(); return true; } catch (error) { if (error instanceof ControlPlaneError && error.status === 409) { state.conflict = true; state.error = "Changed elsewhere. Latest values loaded."; await loadResource(kind); } else { state.error = String((error as Error).message || error); } return false; } finally { state.saving = false; } } async function history(kind: string): Promise { const response = await request( `/api/control-plane/resources/${encodeURIComponent(kind)}/history`, ); return response.revisions ?? []; } /** Services the credential bindings define, which identity grants choose from. */ const credentialServices = computed(() => { const bindings = (draftValue("credential-bindings") ?? []) as { service: string }[]; return [...new Set(bindings.map((b) => b.service))].sort(); }); return { credentialServices, config, loadConfig, reviewing, pageErrorFor, applyStatusFor, changesFor, changeFor, dirtyKinds, invalidFields, issuesFor, formFor, draftValue, setDraftValue, setDraftEntry, resetDraft, revertDraftChange, stageRestore, saveDrafts, catalog, catalogError, genericResources, history, load, loadResource, replace, stateFor, }; });