Files
archie/ui/src/stores/control-plane.ts
T
sam 3944f544e8 feat(controlplane): runtime administration over the State Store's gRPC server
The Web UI and messaging channels now read and write Archie's runtime
settings through one versioned, audited control-plane API hosted on the
State Store's existing gRPC server: catalog, query, command, watch. Each
feature owns its resource, validation and commands; storage only writes
versions and audit records.

Workflows move with it. Definitions become portable YAML compiled through
a closed, typed step registry and stored as a control-plane resource, so
the yaegi interpretation paths (internal/gate, wfeval, wfextract,
gateeval, gateextract, skillbuild) are deleted rather than carried.

The UI process reads definitions as data: the JSON projection lives in
internal/domain/workflow/task so a dashboard decodes the stored
collection without linking the workflow engine, which cmd/archie-ui's
deletion gate forbids. Shipped definitions ride the catalog descriptor
rather than a bespoke REST route, keeping the API to its four operations.

archie-messaging gains -state-store-target/-state-store-token and reads
channel settings from the database, failing closed when the State Store
is unreachable: the database is authoritative for those settings.
2026-09-21 08:17:42 +10:00

194 lines
7.0 KiB
TypeScript

import { defineStore } from "pinia";
import { computed, reactive, ref } from "vue";
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 }
export interface ResourceState {
resource?: ControlPlaneResource;
loading: boolean;
saving: boolean;
error?: string;
conflict: boolean;
stream: "connecting" | "live" | "reconnecting";
}
class ControlPlaneError extends Error {
readonly status: number;
constructor(message: string, status: number) {
super(message);
this.status = status;
}
}
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
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<T>;
}
export type ControlPlanePage = "tasks" | "models" | "repositories" | "channels" | "advanced" | "workflows";
const PAGE_RESOURCES: Record<ControlPlanePage, string[]> = {
tasks: ["workflow-execution-settings"],
models: ["provider-settings", "model-role-assignments"],
repositories: ["repository-policies"],
channels: ["channel-settings"],
advanced: ["personas", "schedules", "scheduling-policy", "tool-settings", "plugin-settings", "container-runtime-policies"],
workflows: ["workflow-definitions"],
};
export interface WorkflowDefinitionEntry { id: string; yaml: string }
export interface WorkflowDefinitionCollection { definitions: WorkflowDefinitionEntry[] }
export function cloneControlPlaneValue<T>(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 upsertWorkflowDefinition(collection: WorkflowDefinitionCollection, entry: WorkflowDefinitionEntry): WorkflowDefinitionCollection {
const found = collection.definitions.some(({ id }) => id === entry.id);
return { definitions: found
? collection.definitions.map((definition) => definition.id === entry.id ? entry : definition)
: [...collection.definitions, entry] };
}
export function removeWorkflowDefinition(collection: WorkflowDefinitionCollection, id: string): WorkflowDefinitionCollection {
return { definitions: collection.definitions.filter((definition) => definition.id !== id) };
}
export function commandBody(value: unknown, expectedVersion: number): string {
return JSON.stringify({ value, expected_version: expectedVersion });
}
export const useControlPlaneStore = defineStore("control-plane", () => {
const catalog = ref<ResourceDescriptor[]>([]);
const catalogError = ref("");
const states = reactive<Record<string, ResourceState>>({});
const streams = new Map<string, EventSource>();
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, stream: "connecting" };
return states[kind];
}
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;
}
async function loadResource(kind: string): Promise<void> {
const state = stateFor(kind);
state.loading = true;
try {
apply((await request<ResourceResponse>(`/api/control-plane/resources/${encodeURIComponent(kind)}`)).resource);
} catch (error) {
state.error = String((error as Error).message || error);
} finally {
state.loading = false;
}
}
function watchResource(kind: string): void {
if (streams.has(kind)) return;
const state = stateFor(kind);
const after = state.resource?.version ?? 0;
const stream = new EventSource(`/api/control-plane/watch/${encodeURIComponent(kind)}?after=${after}`);
stream.onopen = () => { state.stream = "live"; };
stream.onerror = () => { state.stream = "reconnecting"; };
stream.onmessage = (event) => {
try { apply((JSON.parse(event.data) as ResourceResponse).resource); } catch { state.error = "Invalid live update"; }
};
streams.set(kind, stream);
}
async function load(): Promise<void> {
try {
const response = await request<{ resources?: ResourceDescriptor[] }>("/api/control-plane/catalog");
catalog.value = response.resources ?? [];
catalogError.value = "";
await Promise.all(genericResources.value.map(async ({ kind }) => {
await loadResource(kind);
watchResource(kind);
}));
} catch (error) {
catalogError.value = String((error as Error).message || error);
}
}
async function replace(kind: string, value: unknown): Promise<boolean> {
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<ResourceResponse>(
`/api/control-plane/resources/${encodeURIComponent(kind)}/commands/replace`,
{ method: "POST", body: commandBody(value, state.resource.version) },
);
apply(response.resource);
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;
}
}
/** The shipped definitions the catalog offers as "restore shipped". */
function shippedWorkflows(): WorkflowDefinitionCollection {
const defaults = catalog.value.find((resource) => resource.kind === "workflow-definitions")?.defaults_json;
if (!defaults) return { definitions: [] };
try {
return JSON.parse(defaults) as WorkflowDefinitionCollection;
} catch {
return { definitions: [] };
}
}
return { catalog, catalogError, states, genericResources, load, replace, shippedWorkflows, stateFor };
});