Refactor channels, settings, logs, and memory to use Preact components

This commit is contained in:
sam committed 2026-09-03 00:20:43 +10:00
1 parent 09d85149ee
commit 4e189b605e
6 files changed
+951 -837

No files matched your search

+93 -70
View File
@@ -1,77 +1,19 @@
import { h } from "preact";
import { useState, useEffect } from "preact/hooks";
import "./channels.css";
import { api } from "../base/api.jsx";
import { el, empty, mount, pill } from "../base/dom.jsx";
/**
* How you reach Archie. Backed by GET /api/channels, which derives from
* [chat] in config.toml -- see internal/webui/api_config.go's
* handleChannels. Each channel is a card with a connected/not-configured
* pill and one line explaining what turning it on gets you, because
* "token_env unset" means nothing to someone who hasn't read config.toml.
*/
export function channelsPage() {
const root = el("div");
const cardGrid = el("div.grid.grid-2");
export function Pill({ text, kind = "idle" }) {
return <span className={`pill pill-${kind}`}>{text}</span>;
}
render();
load();
function render() {
mount(
root,
el(
"div.page-head",
el(
"div",
el("h1.page-title", "Channels"),
el("p.page-sub", "The conversational front-ends Archie can be reached through."),
),
el("div.page-actions", el("button.btn", { onclick: load }, "Refresh")),
),
cardGrid,
);
}
async function load() {
try {
const res = await api.channels();
renderCards(res?.channels || []);
} catch (err) {
mount(cardGrid, empty("Cannot reach archied", String(err.message || err)));
}
}
function renderCards(channels) {
if (!channels.length) {
mount(
cardGrid,
empty(
"No channels configured",
"Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.",
),
);
return;
}
mount(cardGrid, ...channels.map(channelCard));
}
function channelCard(channel) {
return el(
"div.card.channel-card",
el(
"div.card-head",
el("h3.card-title", channel.name),
pill(channel.state || (channel.configured ? "configured" : "stopped"), stateTone(channel.state, channel.configured)),
),
el("p.channel-desc", channel.description),
el("p.channel-detail", channel.detail),
channel.reload_supported
? el("button.btn", { onclick: async (event) => { event.currentTarget.disabled = true; try { await api.channelReload(channel.id || channel.name.toLowerCase()); await load(); } catch (err) { event.currentTarget.disabled = false; } } }, "Reload")
: el("p.channel-detail", "Reload requires a daemon restart for this adapter."),
);
}
return root;
export function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
function stateTone(state, configured) {
@@ -79,3 +21,84 @@ function stateTone(state, configured) {
if (state === "failed" || state === "degraded") return "warn";
return configured ? "idle" : "idle";
}
function ChannelsApp() {
const [channels, setChannels] = useState([]);
const [error, setError] = useState(null);
const load = async () => {
try {
const res = await api.channels();
setChannels(res?.channels || []);
setError(null);
} catch (err) {
setError(String(err.message || err));
}
};
useEffect(() => {
load();
}, []);
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Channels</h1>
<p className="page-sub">The conversational front-ends Archie can be reached through.</p>
</div>
<div className="page-actions">
<button className="btn" onClick={load}>Refresh</button>
</div>
</div>
<div className="grid grid-2">
{error ? (
<Empty title="Cannot reach archied" detail={error} />
) : channels.length === 0 ? (
<Empty
title="No channels configured"
detail="Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard."
/>
) : (
channels.map(channel => (
<div className="card channel-card" key={channel.id || channel.name}>
<div className="card-head">
<h3 className="card-title">{channel.name}</h3>
<Pill
text={channel.state || (channel.configured ? "configured" : "stopped")}
kind={stateTone(channel.state, channel.configured)}
/>
</div>
<p className="channel-desc">{channel.description}</p>
<p className="channel-detail">{channel.detail}</p>
{channel.reload_supported ? (
<button
className="btn"
onClick={async (event) => {
event.currentTarget.disabled = true;
try {
await api.channelReload(channel.id || channel.name.toLowerCase());
await load();
} catch (err) {
// skip
} finally {
if (event.currentTarget) event.currentTarget.disabled = false;
}
}}
>
Reload
</button>
) : (
<p className="channel-detail">Reload requires a daemon restart for this adapter.</p>
)}
</div>
))
)}
</div>
</div>
);
}
export function channelsPage(query) {
return <ChannelsApp query={query} />;
}
+203 -145
View File
@@ -1,17 +1,59 @@
import { h } from "preact";
import { useState, useEffect, useRef, useMemo } from "preact/hooks";
import "./logs.css";
import { api, subscribeLogs } from "../base/api.jsx";
import { el, empty, mount, pill } from "../base/dom.jsx";
import { logRow } from "../base/log-row.jsx";
/**
* The log view: history from the file on disk, then live lines appended from
* the event stream.
*
* Filtering is applied server-side for history (the file is far larger than a
* page of it) and client-side for live lines (they are already in hand). Both
* paths go through the same matcher shape so a filter means the same thing
* either side of the join.
*/
function Pill({ text, kind = "idle" }) {
return <span className={`pill pill-${kind}`}>{text}</span>;
}
function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
export function levelKind(level) {
switch ((level || "").toUpperCase()) {
case "ERROR": return "danger";
case "WARN": return "warn";
case "DEBUG": return "idle";
default: return "info";
}
}
export function fmtValue(v) {
if (v == null) return "";
return typeof v === "object" ? JSON.stringify(v) : v;
}
export function shortTime(value) {
const d = value instanceof Date ? value : new Date(value);
if (Number.isNaN(d.getTime())) return "--:--:--";
return d.toTimeString().slice(0, 8);
}
function LogRow({ entry }) {
const fields = entry.fields || {};
return (
<div className={`log-row log-${levelKind(entry.level)}`}>
<span className="log-time mono">{shortTime(entry.time)}</span>
<span className="log-level">{(entry.level || "info").toUpperCase()}</span>
<span className="log-body">
<span className="log-msg">{entry.message || entry.msg || ""}</span>
{Object.entries(fields).map(([k, v]) => (
<span className="log-field" key={k}>
<span className="log-field-key">{k}</span>
{String(fmtValue(v))}
</span>
))}
</span>
</div>
);
}
const LEVELS = [
{ value: "", label: "All levels" },
@@ -21,83 +63,25 @@ const LEVELS = [
{ value: "DEBUG", label: "Debug only" },
];
export function logsPage() {
const root = el("div");
const list = el("div.log-list");
const streamState = pill("connecting", "idle");
const meta = el("span.log-meta");
function entryKey(entry) {
return `${entry.time || ""}|${entry.level || ""}|${entry.message || entry.msg || ""}|${JSON.stringify(entry.fields || {})}`;
}
let filters = { level: "", component: "", q: "" };
let paused = false;
let componentOptions = [];
let historyEntries = [];
const liveEntries = new Map();
let durableUnavailable = false;
function LogsApp() {
const [filters, setFilters] = useState({ level: "", component: "", q: "" });
const [paused, setPaused] = useState(false);
const [componentOptions, setComponentOptions] = useState([]);
const [historyEntries, setHistoryEntries] = useState([]);
const liveEntriesRef = useRef(new Map());
const [liveEntriesCounter, setLiveEntriesCounter] = useState(0);
const [durableUnavailable, setDurableUnavailable] = useState(false);
const [streamState, setStreamState] = useState("connecting");
const [meta, setMeta] = useState("Refreshing…");
const listRef = useRef(null);
const searchTimeout = useRef(null);
const levelSelect = el(
"select.log-select",
{ onchange: (e) => set({ level: e.target.value }) },
...LEVELS.map((l) => el("option", { value: l.value }, l.label)),
);
const componentSelect = el("select.log-select", {
onchange: (e) => set({ component: e.target.value }),
});
const search = el("input.log-search", {
type: "search",
placeholder: "Search messages and fields…",
oninput: debounce((e) => set({ q: e.target.value }), 250),
});
const pauseBtn = el("button.btn", { onclick: togglePause }, "Pause");
render();
const unsubscribe = subscribeLogs(
(event) => appendLive(event),
(state) => {
streamState.className = `pill pill-${state === "live" ? "ok" : "warn"}`;
streamState.textContent = state;
},
);
root.addEventListener("archie:teardown", unsubscribe);
load();
function set(patch) {
filters = { ...filters, ...patch };
load();
}
function togglePause() {
paused = !paused;
pauseBtn.textContent = paused ? "Resume" : "Pause";
pauseBtn.classList.toggle("btn-primary", paused);
}
function render() {
mount(
root,
el(
"div.page-head",
el(
"div",
el("h1.page-title", "Logs"),
el("p.page-sub", "What Archie has been doing, newest last."),
),
el("div.page-actions", pauseBtn, el("button.btn", { onclick: load }, "Refresh")),
),
el(
"div.card",
el(
"div.card-head",
el("div.log-filters", levelSelect, componentSelect, search),
el("div.log-status", meta, streamState),
),
list,
),
);
}
async function load() {
meta.textContent = "Refreshing…";
const load = async () => {
setMeta("Refreshing…");
try {
const res = await api.logs({
level: filters.level,
@@ -106,55 +90,57 @@ export function logsPage() {
limit: 500,
});
syncComponents(res.components || []);
durableUnavailable = !!res.disabled;
meta.textContent = res.disabled ? "Durable history unavailable; live daemon logs continue." : res.truncated
setComponentOptions(prev => {
const newComps = res.components || [];
if (prev.length === newComps.length && prev.every((v, i) => v === newComps[i])) return prev;
return newComps;
});
setDurableUnavailable(!!res.disabled);
const newMeta = res.disabled ? "Durable history unavailable; live daemon logs continue." : res.truncated
? `showing the most recent matches from ${res.file}`
: res.file || "";
historyEntries = res.entries || [];
renderEntries();
setMeta(newMeta);
setHistoryEntries(res.entries || []);
} catch (err) {
mount(list, empty("Cannot read logs", String(err.message || err)));
setMeta("Cannot read logs");
}
}
};
// Rebuild the component filter from what the log actually contains, so the
// options never drift from reality.
function syncComponents(components) {
if (sameList(components, componentOptions)) return;
componentOptions = components;
const current = filters.component;
mount(
componentSelect,
el("option", { value: "" }, "All components"),
...components.map((c) => el("option", { value: c }, c)),
useEffect(() => {
load();
}, [filters]);
useEffect(() => {
const handleEvent = (event) => {
if (pausedRef.current) return;
const entry = event;
if (!matchesLocallyRef.current(entry)) return;
liveEntriesRef.current.set(entryKey(entry), entry);
if (entry.fields?.component) {
setComponentOptions(prev => {
if (!prev.includes(entry.fields.component)) return [...prev, entry.fields.component];
return prev;
});
}
setLiveEntriesCounter(c => c + 1);
};
const unsubscribe = subscribeLogs(
handleEvent,
(state) => {
setStreamState(state);
}
);
componentSelect.value = current;
}
return () => unsubscribe();
}, []); // Only run once
function appendLive(event) {
if (paused) return;
const entry = event;
if (!matchesLocally(entry)) return;
liveEntries.set(entryKey(entry), entry);
if (entry.fields?.component) syncComponents([...componentOptions, entry.fields.component]);
renderEntries();
}
const pausedRef = useRef(paused);
pausedRef.current = paused;
function renderEntries() {
const byID = new Map();
for (const entry of historyEntries) byID.set(entryKey(entry), entry);
for (const [id, entry] of liveEntries) byID.set(id, entry);
const entries = [...byID.values()].filter(matchesLocally).slice(-1000);
if (!entries.length) {
mount(list, empty(durableUnavailable ? "Durable history unavailable" : "Nothing matches", durableUnavailable ? "Live daemon logs will appear here while this page is open." : "Try a wider level or clear the search."));
return;
}
mount(list, ...entries.map(logRow));
list.scrollTop = list.scrollHeight;
}
function matchesLocally(entry) {
const matchesLocally = (entry) => {
if (filters.level && !filters.level.split(",").includes((entry.level || "").toUpperCase())) {
return false;
}
@@ -165,23 +151,95 @@ export function logsPage() {
if (!hay.includes(needle)) return false;
}
return true;
}
return root;
}
function entryKey(entry) {
return `${entry.time || ""}|${entry.level || ""}|${entry.message || entry.msg || ""}|${JSON.stringify(entry.fields || {})}`;
}
function sameList(a, b) {
return a.length === b.length && a.every((v, i) => v === b[i]);
}
function debounce(fn, ms) {
let t;
return (...args) => {
clearTimeout(t);
t = setTimeout(() => fn(...args), ms);
};
const matchesLocallyRef = useRef(matchesLocally);
matchesLocallyRef.current = matchesLocally;
const entriesToRender = useMemo(() => {
const byID = new Map();
for (const entry of historyEntries) byID.set(entryKey(entry), entry);
for (const [id, entry] of liveEntriesRef.current) byID.set(id, entry);
return [...byID.values()].filter(matchesLocally).slice(-1000);
}, [historyEntries, liveEntriesCounter, filters]);
useEffect(() => {
if (listRef.current) {
listRef.current.scrollTop = listRef.current.scrollHeight;
}
}, [entriesToRender]);
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Logs</h1>
<p className="page-sub">What Archie has been doing, newest last.</p>
</div>
<div className="page-actions">
<button
className={`btn ${paused ? "btn-primary" : ""}`}
onClick={() => setPaused(!paused)}
>
{paused ? "Resume" : "Pause"}
</button>
<button className="btn" onClick={load}>Refresh</button>
</div>
</div>
<div className="card">
<div className="card-head">
<div className="log-filters">
<select
className="log-select"
value={filters.level}
onChange={(e) => setFilters(f => ({ ...f, level: e.target.value }))}
>
{LEVELS.map(l => <option key={l.value} value={l.value}>{l.label}</option>)}
</select>
<select
className="log-select"
value={filters.component}
onChange={(e) => setFilters(f => ({ ...f, component: e.target.value }))}
>
<option value="">All components</option>
{componentOptions.map(c => <option key={c} value={c}>{c}</option>)}
</select>
<input
className="log-search"
type="search"
placeholder="Search messages and fields…"
onInput={(e) => {
const v = e.target.value;
if (searchTimeout.current) clearTimeout(searchTimeout.current);
searchTimeout.current = setTimeout(() => {
setFilters(f => ({ ...f, q: v }));
}, 250);
}}
/>
</div>
<div className="log-status">
<span className="log-meta">{meta}</span>
<Pill text={streamState} kind={streamState === "live" ? "ok" : "warn"} />
</div>
</div>
<div className="log-list" ref={listRef}>
{meta === "Cannot read logs" ? (
<Empty title="Cannot read logs" />
) : !entriesToRender.length ? (
<Empty
title={durableUnavailable ? "Durable history unavailable" : "Nothing matches"}
detail={durableUnavailable ? "Live daemon logs will appear here while this page is open." : "Try a wider level or clear the search."}
/>
) : (
entriesToRender.map(entry => <LogRow key={entryKey(entry)} entry={entry} />)
)}
</div>
</div>
</div>
);
}
export function logsPage(query) {
return <LogsApp query={query} />;
}
+105 -89
View File
@@ -1,102 +1,118 @@
import { h } from "preact";
import { useState, useEffect } from "preact/hooks";
import "./memory.css";
import { api } from "../base/api.jsx";
import { el, empty, mount, pill } from "../base/dom.jsx";
import { icon } from "../base/icons.jsx";
/**
* Memory: what Archie can recall, and with what.
*
* Memory is otherwise invisible -- it is a set of tools handed to the model at
* discovery time, so without this page the only way to know what the agent can
* remember is to read the provider source.
*/
export function memoryPage() {
const root = el("div");
const body = el("div");
render();
load();
function render() {
mount(
root,
el(
"div.page-head",
el(
"div",
el("h1.page-title", "Memory"),
el("p.page-sub", "What Archie can recall between conversations, and the tools it uses to do it."),
),
el("div.page-actions", el("button.btn", { onclick: load }, icon("refresh", { size: 15 }), "Refresh")),
),
body,
);
}
async function load() {
mount(body, el("div.card", el("div.mem-loading", "Loading…")));
try {
const res = await api.memory();
if (!res.enabled || !res.providers?.length) {
mount(
body,
el(
"div.card",
empty(
"Memory is not configured",
"Without a provider, Archie starts every conversation with no recollection of earlier ones.",
),
),
);
return;
}
mount(body, el("div.grid.grid-2", ...res.providers.map(providerCard)));
} catch (err) {
mount(body, el("div.card", empty("Cannot read memory providers", String(err.message || err))));
}
}
return root;
function Pill({ text, kind = "idle" }) {
return <span className={`pill pill-${kind}`}>{text}</span>;
}
function providerCard(p) {
const tools = p.tools || [];
return el(
"div.card",
el(
"div.card-head",
el(
"div",
el("h2.card-title", p.name || "provider"),
el("p.card-sub", roleLabel(p.role)),
),
p.available
? pill("ready", "ok")
: pill("unavailable", "danger"),
),
!p.available &&
el(
"p.mem-warning",
"Configured but not usable right now — a required binary or connection may be missing.",
),
tools.length
? el(
"ul.mem-tools",
...tools.map((t) =>
el(
"li.mem-tool",
el("div.mem-tool-name.mono", t.name),
t.description && el("div.mem-tool-desc", t.description),
),
),
)
: el("p.mem-warning", "This provider exposes no tools, so the agent cannot use it."),
function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
// Plain language: "builtin" and "external" are implementation words.
function roleLabel(role) {
return role === "external"
? "Added by you — an external store Archie was given"
: "Built in — always available to Archie";
}
function ProviderCard({ provider: p }) {
const tools = p.tools || [];
return (
<div className="card">
<div className="card-head">
<div>
<h2 className="card-title">{p.name || "provider"}</h2>
<p className="card-sub">{roleLabel(p.role)}</p>
</div>
{p.available ? <Pill text="ready" kind="ok" /> : <Pill text="unavailable" kind="danger" />}
</div>
{!p.available && (
<p className="mem-warning">
Configured but not usable right now — a required binary or connection may be missing.
</p>
)}
{tools.length ? (
<ul className="mem-tools">
{tools.map((t, idx) => (
<li className="mem-tool" key={idx}>
<div className="mem-tool-name mono">{t.name}</div>
{t.description && <div className="mem-tool-desc">{t.description}</div>}
</li>
))}
</ul>
) : (
<p className="mem-warning">This provider exposes no tools, so the agent cannot use it.</p>
)}
</div>
);
}
function MemoryApp() {
const [providers, setProviders] = useState(null);
const [enabled, setEnabled] = useState(true);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
const load = async () => {
setLoading(true);
setError(null);
try {
const res = await api.memory();
setEnabled(!!res.enabled);
setProviders(res.providers || []);
} catch (err) {
setError(String(err.message || err));
} finally {
setLoading(false);
}
};
useEffect(() => {
load();
}, []);
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Memory</h1>
<p className="page-sub">What Archie can recall between conversations, and the tools it uses to do it.</p>
</div>
<div className="page-actions">
<button className="btn" onClick={load}>Refresh</button>
</div>
</div>
<div>
{loading ? (
<div className="card"><div className="mem-loading">Loading…</div></div>
) : error ? (
<div className="card"><Empty title="Cannot read memory providers" detail={error} /></div>
) : !enabled || !providers.length ? (
<div className="card">
<Empty
title="Memory is not configured"
detail="Without a provider, Archie starts every conversation with no recollection of earlier ones."
/>
</div>
) : (
<div className="grid grid-2">
{providers.map((p, idx) => (
<ProviderCard key={idx} provider={p} />
))}
</div>
)}
</div>
</div>
);
}
export function memoryPage(query) {
return <MemoryApp query={query} />;
}
+121 -145
View File
@@ -1,176 +1,152 @@
import { h } from "preact";
import { useState, useRef, useEffect } from "preact/hooks";
import { api } from "../base/api.jsx";
import { el, mount } from "../base/dom.jsx";
/**
* One key/value row on the Configuration page, and its inline edit flow.
*
* Split out of settings.js so it can be unit-tested: settings.js imports
* its own stylesheet, which the node test shim cannot parse. Same reason
* tasks/task-row.js exists separately from tasks.js.
*
* A row renders as a three-column grid: label, value, actions. That shape
* is the fix for three faults in the previous flex layout, all of which
* were visible on screen:
*
* - label and value were pushed to opposite ends of a full-width card by
* `justify-content: space-between`, so reading a pair meant tracking
* across the viewport;
* - the value could not shrink (no `min-width: 0`), so long values
* overflowed into the Edit button and appeared truncated ("400" as
* "40");
* - the locked reason sat beside the overflowing value and ran onto the
* end of it, rendering "...archie/work" and "pins the daemon's working
* layout" as one unbroken string.
*/
// valueText normalises a config value for display. 0 and false are real
// values and must not collapse to the em dash the way null or an unset
// string does, so the emptiness test is explicit rather than falsy.
export function valueText(value) {
if (value === null || value === undefined || value === "") return "—";
return String(value);
}
// row renders one label/value pair. opts.key makes it editable via a
// PATCH to /api/config; opts.locked[key] disables it with the server's
// reason; opts.overridden marks a key whose file value is shadowed by the
// runtime overlay and offers a reset; no key means a plain read-only row
// (structured values and provenance).
//
// The value carries a title attribute because the column truncates with
// an ellipsis: a long path or gate command must stay recoverable without
// widening the row back into the action column.
export function row(label, value, opts) {
export function Row({ label, value, opts }) {
const text = valueText(value);
// opts.hint (a field's backend-authored description, e.g. "0 means
// unlimited.") rides as a tooltip on the label rather than its own DOM
// node, so a generic schema-driven field can carry an explanation
// without every hardcoded caller having to pass one.
const labelEl = el("span.kv-label", opts?.hint ? { title: opts.hint } : {}, label);
const valueEl = el(`span.kv-value.mono${text === "—" ? ".is-empty" : ""}`, { title: text }, text);
const [isEditing, setIsEditing] = useState(false);
const [editValue, setEditValue] = useState("");
const [error, setError] = useState(null);
const [saving, setSaving] = useState(false);
const [resetting, setResetting] = useState(false);
if (!opts?.key) return el("div.kv", labelEl, valueEl);
const key = opts?.key;
if (!key) {
return (
<div className="kv">
<span className="kv-label" title={opts?.hint}>{label}</span>
<span className={`kv-value mono ${text === "—" ? "is-empty" : ""}`} title={text}>{text}</span>
</div>
);
}
const lockedReason = opts.locked?.[opts.key];
const lockedReason = opts.locked?.[key];
if (lockedReason) {
// The reason gets its own grid line rather than sitting beside the
// value, which is what produced the run-together string above.
return el("div.kv.is-locked", labelEl, valueEl, el("span.kv-note", lockedReason));
return (
<div className="kv is-locked">
<span className="kv-label" title={opts.hint}>{label}</span>
<span className={`kv-value mono ${text === "—" ? "is-empty" : ""}`} title={text}>{text}</span>
<span className="kv-note">{lockedReason}</span>
</div>
);
}
// opts.editable distinguishes a field the schema marks not-yet-editable
// (e.g. a structured field with no dedicated editor) from a locked one:
// no reason to show, just no edit affordance.
if (opts.editable === false) return el("div.kv", labelEl, valueEl);
const overridden = opts.overridden?.includes(opts.key);
const editBtn = el("button.kv-btn", { type: "button", title: `Edit ${label}` }, "Edit");
const resetBtn = overridden
? el("button.kv-btn", { type: "button", title: "Discard the dashboard value and fall back to the config file" }, "Reset")
: null;
const actions = el(
"div.kv-actions",
overridden && el("span.kv-flag", { title: "Set from the dashboard; this shadows the value in the config file" }, "overridden"),
editBtn,
resetBtn,
);
const rowEl = el("div.kv", labelEl, valueEl, actions);
editBtn.addEventListener("click", () => startEdit(rowEl, label, opts, [labelEl, valueEl, actions]));
resetBtn?.addEventListener("click", () => resetOverride(rowEl, resetBtn, opts));
return rowEl;
}
// resetOverride deletes one runtime-overlay row via the reset seam, then
// re-renders so the row returns to its file value. A failure reports on
// the row's own note line; the previous version overwrote the "overridden"
// marker's text with the error, destroying the marker to show it.
function resetOverride(rowEl, btn, opts) {
const { key, onSaved } = opts;
btn.disabled = true;
api
.configReset(key)
.then(() => onSaved?.())
.catch((err) => {
btn.disabled = false;
note(rowEl, String(err.message || err));
});
}
// note puts a message on the row's secondary line, creating the line if
// the row does not already have one.
function note(rowEl, message) {
let target = rowEl.querySelector?.(".kv-note");
if (!target) {
target = el("span.kv-note.is-error");
rowEl.appendChild(target);
if (opts.editable === false) {
return (
<div className="kv">
<span className="kv-label" title={opts.hint}>{label}</span>
<span className={`kv-value mono ${text === "—" ? "is-empty" : ""}`} title={text}>{text}</span>
</div>
);
}
target.classList.add("is-error");
target.textContent = message;
}
function startEdit(rowEl, label, opts, restore) {
const { key, type, raw, options, onSaved } = opts;
// save lets a caller redirect where an edit is persisted -- the
// repositories table's per-repo fields PATCH /api/config/repos/{owner}/
// {name} instead of the generic dotted-key /api/config path, since a
// repository is one element of a slice, not a flat key (see
// api.configRepoUpdate, archie-core-b6ew.6). Defaults to the ordinary
// dotted-key update every other row already used.
const save = opts.save || ((value) => api.configUpdate({ [key]: value }));
const input = type === "bool"
? el(
"select.kv-input",
el("option", { value: "true", selected: raw === true }, "true"),
el("option", { value: "false", selected: raw === false }, "false"),
)
: type === "enum"
? el(
"select.kv-input",
...(options || []).map((o) => el("option", { value: o, selected: raw === o }, o)),
)
: el("input.kv-input", { type: "text", value: String(raw ?? "") });
const saveBtn = el("button.kv-save", { type: "button" }, "Save");
const cancel = el("button.kv-cancel", { type: "button" }, "Cancel");
const error = el("span.kv-note.is-error");
const overridden = opts.overridden?.includes(key);
mount(rowEl, el("span.kv-label", label), input, el("div.kv-actions", saveBtn, cancel), error);
input.focus?.();
input.select?.();
const startEdit = () => {
setEditValue(String(opts.raw ?? ""));
setError(null);
setIsEditing(true);
};
const done = () => mount(rowEl, ...restore);
cancel.addEventListener("click", done);
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault?.();
saveBtn.click();
const handleReset = async () => {
setResetting(true);
setError(null);
try {
await api.configReset(key);
opts.onSaved?.();
} catch (err) {
setError(String(err.message || err));
} finally {
setResetting(false);
}
if (e.key === "Escape") done();
});
};
saveBtn.addEventListener("click", async () => {
const parsed = parseEdit(type, input.value);
const handleSave = async () => {
const parsed = parseEdit(opts.type, editValue);
if (parsed.error) {
error.textContent = parsed.error;
setError(parsed.error);
return;
}
saveBtn.disabled = true;
setSaving(true);
setError(null);
try {
const save = opts.save || ((val) => api.configUpdate({ [key]: val }));
await save(parsed.value);
onSaved?.();
setIsEditing(false);
opts.onSaved?.();
} catch (err) {
// The server's reason (validation failure, denylisted key) is the
// part the operator can act on; show it instead of the status.
error.textContent = String(err.message || err);
saveBtn.disabled = false;
setError(String(err.message || err));
} finally {
setSaving(false);
}
});
};
if (isEditing) {
const inputRef = useRef(null);
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
const handleKeyDown = (e) => {
if (e.key === "Enter") {
e.preventDefault();
handleSave();
}
if (e.key === "Escape") setIsEditing(false);
};
let inputEl;
if (opts.type === "bool") {
inputEl = (
<select className="kv-input" value={editValue} onChange={e => setEditValue(e.target.value)} onKeyDown={handleKeyDown} ref={inputRef}>
<option value="true">true</option>
<option value="false">false</option>
</select>
);
} else if (opts.type === "enum") {
inputEl = (
<select className="kv-input" value={editValue} onChange={e => setEditValue(e.target.value)} onKeyDown={handleKeyDown} ref={inputRef}>
{(opts.options || []).map(o => <option key={o} value={o}>{o}</option>)}
</select>
);
} else {
inputEl = <input className="kv-input" type="text" value={editValue} onInput={e => setEditValue(e.target.value)} onKeyDown={handleKeyDown} ref={inputRef} />;
}
return (
<div className="kv">
<span className="kv-label" title={opts.hint}>{label}</span>
{inputEl}
<div className="kv-actions">
<button className="kv-save" type="button" onClick={handleSave} disabled={saving}>Save</button>
<button className="kv-cancel" type="button" onClick={() => setIsEditing(false)} disabled={saving}>Cancel</button>
</div>
{error && <span className="kv-note is-error">{error}</span>}
</div>
);
}
return (
<div className="kv">
<span className="kv-label" title={opts.hint}>{label}</span>
<span className={`kv-value mono ${text === "—" ? "is-empty" : ""}`} title={text}>{text}</span>
<div className="kv-actions">
{overridden && <span className="kv-flag" title="Set from the dashboard; this shadows the value in the config file">overridden</span>}
<button className="kv-btn" type="button" title={`Edit ${label}`} onClick={startEdit}>Edit</button>
{overridden && <button className="kv-btn" type="button" title="Discard the dashboard value and fall back to the config file" onClick={handleReset} disabled={resetting}>Reset</button>}
</div>
{error && <span className="kv-note is-error">{error}</span>}
</div>
);
}
// parseEdit converts the input text to the JSON type the config field
// expects. Durations and strings pass through (the server validates
// duration syntax); ints are parsed client-side so a typo fails before a
// round trip.
export function parseEdit(type, text) {
switch (type) {
case "int": {
+362 -322
View File
@@ -1,372 +1,228 @@
import { h } from "preact";
import { useState, useEffect } from "preact/hooks";
import "./settings.css";
import { api } from "../base/api.jsx";
import { el, empty, mount, pill } from "../base/dom.jsx";
import { statusKind, statusLabel } from "../base/task-meta.jsx";
import { row } from "./config-row.jsx";
import { updateStatusCard } from "./update-status.jsx";
import { Row } from "./config-row.jsx";
import { UpdateStatusCard } from "./update-status.jsx";
/**
* A view of the config archied is actually running with, grouped by
* domain and explained in plain language. Backed by GET /api/config,
* which is built from an explicit, hand-picked allowlist on the Go side
* (internal/webui/api_config.go handleConfig) -- secrets never reach
* this page, so nothing here needs to be hidden or redacted client-side.
*
* Scalar rows that are not denylisted are editable inline: Edit swaps
* the value for an input, Save PATCHes the dotted key to /api/config,
* which validates the materialised config before persisting to the
* runtime overlay and republishing. Structured values (repositories,
* models, providers -- arrays and maps) render read-only; denylisted
* keys (db_path, work_dir) render disabled with the server's reason.
*/
export function settingsPage() {
// .cfg-page caps and centres the whole view. Constraining the container
// rather than the individual lists keeps the cards, key/value lists and
// tables on one shared measure; see settings.css.
const root = el("div.cfg-page");
const body = el("div");
const versionSlot = el("div");
const lifecycleSlot = el("div");
render();
load();
loadVersionStatus();
loadLifecycle();
function render() {
mount(
root,
el(
"div.page-head",
el(
"div",
el("h1.page-title", "Configuration"),
el("p.page-sub", "What archied is actually running with right now."),
),
el("div.page-actions", el("button.btn", { onclick: () => { load(); loadVersionStatus(); loadLifecycle(); } }, "Refresh")),
),
versionSlot,
lifecycleSlot,
body,
);
}
async function load() {
try {
const cfg = await api.config();
renderBody(cfg, load);
} catch (err) {
mount(body, el("div.card", empty("Cannot reach archied", String(err.message || err))));
}
}
async function loadVersionStatus() {
try {
const data = await api.version();
mount(versionSlot, updateStatusCard(data?.components || []));
} catch (err) {
// 501 means updates just aren't configured for this deployment --
// that's the ordinary state for most installs, not a failure to
// report as loudly as an unreachable daemon.
if (err?.status === 501) {
mount(versionSlot);
return;
}
mount(versionSlot, el("div.card", empty("Update status unavailable", String(err.message || err))));
}
}
async function loadLifecycle() {
try {
const data = await api.taskMeta();
mount(lifecycleSlot, lifecycleCard(data));
} catch (err) {
// The lifecycle vocabulary is optional metadata; if archied does not
// answer, show a quiet placeholder rather than a loud failure.
mount(
lifecycleSlot,
section(
"Work lifecycle",
"The task statuses and operator actions archied ships.",
empty("Lifecycle unavailable", String(err.message || err)),
),
);
}
}
function renderBody(cfg, reload) {
if (!cfg || Object.keys(cfg).length === 0) {
mount(
body,
el(
"div.card",
empty(
"No configuration loaded",
"archied is running without a config file wired into the dashboard, so there is nothing to show.",
),
),
);
return;
}
const ctx = { locked: cfg.locked || {}, overridden: cfg.overridden || [], onSaved: reload };
const banners = [
cfg.reload?.overlay_unavailable &&
el("div.card.cfg-notice", el("p", `The runtime config overlay is not in effect: ${cfg.reload.overlay_unavailable}`)),
cfg.reload?.last_error &&
el("div.card.cfg-notice", el("p", `The last config reload failed; the running config is unchanged: ${cfg.reload.last_error}`)),
];
mount(
body,
...banners,
...schemaCards(cfg.schema || []),
repositoriesCard(cfg.repositories, reload),
modelsAndProvidersCard(cfg.models, cfg.providers),
provenanceCard(cfg.provenance),
);
// schemaCards renders one card per backend-defined section, generically,
// from cfg.schema (archie-core-b6ew) -- a scalar field's label, type,
// description and editability all come from the backend, not from a
// hardcoded row(...) call here. A section whose fields are all
// type=structured (repositories, models & providers) renders no card
// here; those keep the dedicated renderers above, called directly off
// the flat cfg fields (archie-core-b6ew.4 gives them their own editors).
function schemaCards(sections) {
return sections
.map((s) => {
const rows = s.fields
.filter((f) => f.type !== "structured")
.map((f) =>
row(f.label, f.value, {
key: f.key,
type: f.type,
options: f.options,
raw: f.value,
hint: f.description,
editable: f.editable,
...ctx,
}),
);
if (!rows.length) return null;
return section(s.label, s.description, el("div.kv-list", ...rows));
})
.filter(Boolean);
}
}
return root;
function Pill({ text, kind = "idle" }) {
return <span className={`pill pill-${kind}`}>{text}</span>;
}
function provenanceCard(origins) {
if (!origins?.length) return section("Configuration sources", "The files that supplied the running configuration.", empty("Source provenance is unavailable."));
return section(
"Configuration sources",
"Applied from top to bottom; later entries take precedence over earlier ones.",
el("div.kv-list", ...origins.map((origin) => row(`${origin.layer} ${origin.role}${origin.feature ? ` (${origin.feature})` : ""}`, origin.path))),
function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
function section(title, sub, ...children) {
return el(
"div.card.cfg-section",
el("div.card-head", el("div", el("h2.card-title", title), el("p.card-sub", sub))),
...children,
function Section({ title, sub, children }) {
return (
<div className="card cfg-section">
<div className="card-head">
<div>
<h2 className="card-title">{title}</h2>
<p className="card-sub">{sub}</p>
</div>
</div>
{children}
</div>
);
}
// Work lifecycle: the vocabulary archied ships as a server catalog. Both the
// statuses (label + pill severity) and the operator actions (label + button
// variant) are rendered from the /api/task-meta payload, so a status or action
// added on the backend appears here on the next load with no frontend change.
// statusLabel/statusKind are used as fallbacks for an entry that arrives
// without its own label/kind so the card degrades gracefully.
function lifecycleCard(data) {
const statuses = data?.statuses || [];
const actions = data?.actions || [];
const statusList = statuses.length
? el("div.kv-list", ...statuses.map((s) => statusLifecycleRow(s)))
: empty("No statuses reported", "The server did not return any lifecycle statuses.");
const actionList = actions.length
? el("div.kv-list", ...actions.map((a) => actionLifecycleRow(a)))
: empty("No actions reported", "The server did not return any operator actions.");
return section(
"Work lifecycle",
"The task statuses and operator actions archied ships. Add one on the backend and it appears here without a frontend change.",
el("h3.cfg-subhead", "Statuses"),
statusList,
el("h3.cfg-subhead", "Actions"),
actionList,
function ProvenanceCard({ origins }) {
if (!origins?.length) return (
<Section title="Configuration sources" sub="The files that supplied the running configuration.">
<Empty title="Source provenance is unavailable." />
</Section>
);
return (
<Section title="Configuration sources" sub="Applied from top to bottom; later entries take precedence over earlier ones.">
<div className="kv-list">
{origins.map((origin, i) => (
<Row key={i} label={`${origin.layer} ${origin.role}${origin.feature ? ` (${origin.feature})` : ""}`} value={origin.path} />
))}
</div>
</Section>
);
}
function statusLifecycleRow(s) {
const label = s.label ?? statusLabel(s.id);
const kind = s.kind ?? statusKind(s.id);
return el("div.kv", el("span.kv-label", s.id), el("span.kv-value", pill(label, kind)));
}
function actionLifecycleRow(a) {
const label = a.label ?? a.id;
const cls = roleButtonClass(a.kind);
const spec = cls ? `button.btn.btn-small.${cls}` : "button.btn.btn-small";
return el("div.kv", el("span.kv-label", a.id), el("span.kv-value", el(spec, { type: "button", disabled: true }, label)));
}
// The button variant token for an action kind, matching the tasks board's
// mapping: quiet/danger get their own tokens, everything else (primary, link)
// falls back to the default .btn styling. A new kind never needs a new case.
function roleButtonClass(kind) {
return kind === "quiet" ? "btn-quiet" : kind === "danger" ? "btn-danger" : "";
}
function repositoriesCard(repos, onSaved) {
if (!repos?.length) {
return section(
"Repositories",
"The repositories Archie polls for work.",
empty("No repositories configured", "Add a [[repos]] entry in config.toml so Archie has somewhere to work."),
function LifecycleCard({ data, error }) {
if (error) {
return (
<Section title="Work lifecycle" sub="The task statuses and operator actions archied ships.">
<Empty title="Lifecycle unavailable" detail={error} />
</Section>
);
}
return section(
"Repositories",
"Each repository Archie polls, and the quality gate a change must pass before it opens a pull request. " +
"Concurrent tasks, retries, and self-review are per-repository overrides -- PATCH /api/config/repos/{owner}/{name}, " +
"not the file config.toml directly.",
el(
"div.table-scroll",
el(
"table.table",
el(
"thead",
el(
"tr",
...["Repository", "Base branch", "Ecosystem", "Quality gate", "Protected paths", "Concurrent", "Max retries", "Self-review"].map((h) =>
el("th", h),
),
),
),
el(
"tbody",
...repos.map((r) =>
el(
"tr",
el("td.strong", `${r.owner}/${r.name}`),
el("td.mono", r.base),
el("td", r.ecosystem || "go"),
el("td.mono", gateSummary(r.gate)),
el("td.mono", r.protect?.length ? r.protect.join(", ") : "—"),
repoBoolCell(r, "allow_concurrent", onSaved),
repoIntCell(r, "max_retries", onSaved),
repoBoolCell(r, "review_enabled", onSaved),
),
),
),
),
),
const statuses = data?.statuses || [];
const actions = data?.actions || [];
return (
<Section title="Work lifecycle" sub="The task statuses and operator actions archied ships. Add one on the backend and it appears here without a frontend change.">
<h3 className="cfg-subhead">Statuses</h3>
{statuses.length ? (
<div className="kv-list">
{statuses.map(s => {
const label = s.label ?? statusLabel(s.id);
const kind = s.kind ?? statusKind(s.id);
return (
<div className="kv" key={s.id}>
<span className="kv-label">{s.id}</span>
<span className="kv-value"><Pill text={label} kind={kind} /></span>
</div>
);
})}
</div>
) : (
<Empty title="No statuses reported" detail="The server did not return any lifecycle statuses." />
)}
<h3 className="cfg-subhead">Actions</h3>
{actions.length ? (
<div className="kv-list">
{actions.map(a => {
const label = a.label ?? a.id;
const cls = roleButtonClass(a.kind);
return (
<div className="kv" key={a.id}>
<span className="kv-label">{a.id}</span>
<span className="kv-value">
<button className={`btn btn-small ${cls}`} type="button" disabled>{label}</button>
</span>
</div>
);
})}
</div>
) : (
<Empty title="No actions reported" detail="The server did not return any operator actions." />
)}
</Section>
);
}
// repoBoolCell renders an immediately-autosaving checkbox, PATCHing
// api.configRepoUpdate on change and reverting the toggle if the save
// fails (archie-core-b6ew.6). A table cell doesn't fit config-row.jsx's
// label/value/actions Edit-then-Save flow, and a checkbox is the more
// natural control for a boolean in a table anyway.
function repoBoolCell(r, field, onSaved) {
const cb = el("input.repo-field-checkbox", { type: "checkbox", checked: !!r[field] });
const note = el("span.kv-note.is-error");
cb.addEventListener("change", async () => {
const next = cb.checked;
cb.disabled = true;
function RepoBoolCell({ r, field, onSaved }) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [checked, setChecked] = useState(!!r[field]);
const handleChange = async (e) => {
const next = e.target.checked;
setChecked(next);
setLoading(true);
setError(null);
try {
await api.configRepoUpdate(r.owner, r.name, field, next);
onSaved?.();
} catch (err) {
cb.checked = !next;
note.textContent = String(err.message || err);
cb.disabled = false;
setChecked(!next);
setError(String(err.message || err));
} finally {
setLoading(false);
}
});
return el("td", cb, note);
};
return (
<td>
<input className="repo-field-checkbox" type="checkbox" checked={checked} onChange={handleChange} disabled={loading} />
{error && <span className="kv-note is-error">{error}</span>}
</td>
);
}
// repoIntCell renders a plain text input that saves on blur/Enter. Errors
// (a non-numeric entry, a rejected save) stay on the cell rather than
// reloading the page out from under the operator mid-edit.
function repoIntCell(r, field, onSaved) {
const input = el("input.kv-input", { type: "text", value: String(r[field] ?? 0) });
const note = el("span.kv-note.is-error");
function RepoIntCell({ r, field, onSaved }) {
const [val, setVal] = useState(String(r[field] ?? 0));
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const commit = async () => {
const n = parseInt(input.value, 10);
const n = parseInt(val, 10);
if (Number.isNaN(n)) {
note.textContent = "Enter a whole number";
setError("Enter a whole number");
return;
}
input.disabled = true;
setLoading(true);
setError(null);
try {
await api.configRepoUpdate(r.owner, r.name, field, n);
onSaved?.();
} catch (err) {
note.textContent = String(err.message || err);
input.disabled = false;
setError(String(err.message || err));
} finally {
setLoading(false);
}
};
input.addEventListener("keydown", (e) => {
const handleKeyDown = (e) => {
if (e.key === "Enter") {
e.preventDefault?.();
input.blur();
e.preventDefault();
e.target.blur();
}
});
input.addEventListener("blur", commit);
return el("td", input, note);
};
return (
<td>
<input
className="kv-input"
type="text"
value={val}
onChange={e => setVal(e.target.value)}
onBlur={commit}
onKeyDown={handleKeyDown}
disabled={loading}
/>
{error && <span className="kv-note is-error">{error}</span>}
</td>
);
}
function gateSummary(gate) {
if (!gate?.length) return "—";
return gate.map((cmd) => cmd.join(" ")).join(" → ");
}
function RepositoriesCard({ repos, onSaved }) {
if (!repos?.length) {
return (
<Section title="Repositories" sub="The repositories Archie polls for work.">
<Empty title="No repositories configured" detail="Add a [[repos]] entry in config.toml so Archie has somewhere to work." />
</Section>
);
}
function modelsAndProvidersCard(models, providers) {
const modelEntries = Object.entries(models || {});
const providerEntries = Object.entries(providers || {});
const gateSummary = (gate) => {
if (!gate?.length) return "—";
return gate.map((cmd) => cmd.join(" ")).join(" → ");
};
const modelRows = modelEntries.length
? el("div.kv-list", ...modelEntries.map(([role, ref]) => row(roleLabel(role), ref)))
: empty("No model roles configured", "Assign a model to at least one role (e.g. \"builder\") in [models].");
const providerRows = providerEntries.length
? el(
"div.table-scroll",
el(
"table.table",
el("thead", el("tr", ...["Provider", "Class", "Base URL", "API key env var", "Status"].map((h) => el("th", h)))),
el(
"tbody",
...providerEntries.map(([name, p]) =>
el(
"tr",
el("td.strong", name),
el("td", p.class),
el("td.mono", p.base_url || "default"),
el("td.mono", p.api_key_env || "—"),
el("td", p.configured ? pill("configured", "ok") : pill("missing credentials", "warn")),
),
),
),
),
)
: empty("No providers configured", "Add a [providers.<name>] entry so a model role above has something to run on.");
return section(
"Models & providers",
"Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.",
el("h3.cfg-subhead", "Model roles"),
modelRows,
el("h3.cfg-subhead", "Providers"),
providerRows,
return (
<Section title="Repositories" sub="Each repository Archie polls, and the quality gate a change must pass before it opens a pull request. Concurrent tasks, retries, and self-review are per-repository overrides -- PATCH /api/config/repos/{owner}/{name}, not the file config.toml directly.">
<div className="table-scroll">
<table className="table">
<thead>
<tr>
<th>Repository</th><th>Base branch</th><th>Ecosystem</th><th>Quality gate</th><th>Protected paths</th><th>Concurrent</th><th>Max retries</th><th>Self-review</th>
</tr>
</thead>
<tbody>
{repos.map((r, i) => (
<tr key={i}>
<td className="strong">{r.owner}/{r.name}</td>
<td className="mono">{r.base}</td>
<td>{r.ecosystem || "go"}</td>
<td className="mono">{gateSummary(r.gate)}</td>
<td className="mono">{r.protect?.length ? r.protect.join(", ") : "—"}</td>
<RepoBoolCell r={r} field="allow_concurrent" onSaved={onSaved} />
<RepoIntCell r={r} field="max_retries" onSaved={onSaved} />
<RepoBoolCell r={r} field="review_enabled" onSaved={onSaved} />
</tr>
))}
</tbody>
</table>
</div>
</Section>
);
}
@@ -375,3 +231,187 @@ function roleLabel(role) {
return role.charAt(0).toUpperCase() + role.slice(1).replace(/_/g, " ");
}
function ModelsAndProvidersCard({ models, providers }) {
const modelEntries = Object.entries(models || {});
const providerEntries = Object.entries(providers || {});
return (
<Section title="Models & providers" sub="Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.">
<h3 className="cfg-subhead">Model roles</h3>
{modelEntries.length ? (
<div className="kv-list">
{modelEntries.map(([role, ref]) => (
<Row key={role} label={roleLabel(role)} value={ref} />
))}
</div>
) : (
<Empty title="No model roles configured" detail='Assign a model to at least one role (e.g. "builder") in [models].' />
)}
<h3 className="cfg-subhead">Providers</h3>
{providerEntries.length ? (
<div className="table-scroll">
<table className="table">
<thead>
<tr><th>Provider</th><th>Class</th><th>Base URL</th><th>API key env var</th><th>Status</th></tr>
</thead>
<tbody>
{providerEntries.map(([name, p]) => (
<tr key={name}>
<td className="strong">{name}</td>
<td>{p.class}</td>
<td className="mono">{p.base_url || "default"}</td>
<td className="mono">{p.api_key_env || "—"}</td>
<td>
{p.configured ? <Pill text="configured" kind="ok" /> : <Pill text="missing credentials" kind="warn" />}
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<Empty title="No providers configured" detail="Add a [providers.<name>] entry so a model role above has something to run on." />
)}
</Section>
);
}
function SettingsApp() {
const [cfg, setCfg] = useState(null);
const [cfgError, setCfgError] = useState(null);
const [versionData, setVersionData] = useState(null);
const [versionError, setVersionError] = useState(null);
const [versionMissing, setVersionMissing] = useState(false);
const [lifecycleData, setLifecycleData] = useState(null);
const [lifecycleError, setLifecycleError] = useState(null);
const loadAll = () => {
loadCfg();
loadVersion();
loadLifecycle();
};
const loadCfg = async () => {
try {
const data = await api.config();
setCfg(data);
setCfgError(null);
} catch (err) {
setCfgError(String(err.message || err));
}
};
const loadVersion = async () => {
try {
const data = await api.version();
setVersionData(data?.components || []);
setVersionError(null);
setVersionMissing(false);
} catch (err) {
if (err?.status === 501) {
setVersionMissing(true);
} else {
setVersionError(String(err.message || err));
}
}
};
const loadLifecycle = async () => {
try {
const data = await api.taskMeta();
setLifecycleData(data);
setLifecycleError(null);
} catch (err) {
setLifecycleError(String(err.message || err));
}
};
useEffect(() => {
loadAll();
}, []);
return (
<div className="cfg-page">
<div className="page-head">
<div>
<h1 className="page-title">Configuration</h1>
<p className="page-sub">What archied is actually running with right now.</p>
</div>
<div className="page-actions">
<button className="btn" onClick={loadAll}>Refresh</button>
</div>
</div>
<div>
{!versionMissing && (
versionError ? (
<div className="card"><Empty title="Update status unavailable" detail={versionError} /></div>
) : versionData ? (
<UpdateStatusCard components={versionData} />
) : null
)}
</div>
<div>
<LifecycleCard data={lifecycleData} error={lifecycleError} />
</div>
<div>
{cfgError ? (
<div className="card"><Empty title="Cannot reach archied" detail={cfgError} /></div>
) : !cfg || Object.keys(cfg).length === 0 ? (
<div className="card"><Empty title="No configuration loaded" detail="archied is running without a config file wired into the dashboard, so there is nothing to show." /></div>
) : (
<>
{cfg.reload?.overlay_unavailable && (
<div className="card cfg-notice"><p>The runtime config overlay is not in effect: {cfg.reload.overlay_unavailable}</p></div>
)}
{cfg.reload?.last_error && (
<div className="card cfg-notice"><p>The last config reload failed; the running config is unchanged: {cfg.reload.last_error}</p></div>
)}
{(cfg.schema || []).map((s, i) => {
const rows = s.fields.filter(f => f.type !== "structured");
if (!rows.length) return null;
return (
<Section title={s.label} sub={s.description} key={i}>
<div className="kv-list">
{rows.map(f => (
<Row
key={f.key}
label={f.label}
value={f.value}
opts={{
key: f.key,
type: f.type,
options: f.options,
raw: f.value,
hint: f.description,
editable: f.editable,
locked: cfg.locked || {},
overridden: cfg.overridden || [],
onSaved: loadCfg
}}
/>
))}
</div>
</Section>
);
})}
<RepositoriesCard repos={cfg.repositories} onSaved={loadCfg} />
<ModelsAndProvidersCard models={cfg.models} providers={cfg.providers} />
<ProvenanceCard origins={cfg.provenance} />
</>
)}
</div>
</div>
);
}
export function settingsPage(query) {
return <SettingsApp query={query} />;
}
+67 -66
View File
@@ -1,73 +1,74 @@
import { el, empty, pill } from "../base/dom.jsx";
import { h } from "preact";
const STATUS_LABELS = {
ok: "OK",
update_available: "Update available",
drift: "Drift",
unknown: "Unknown",
};
function Pill({ text, kind = "idle" }) {
return <span className={`pill pill-${kind}`}>{text}</span>;
}
const STATUS_KINDS = {
ok: "ok",
update_available: "info",
drift: "danger",
unknown: "idle",
};
function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
/**
* Per-component deployment/update status (GET /api/version): how each
* component is installed, what's actually running, and whether that
* agrees with what the update-check command claims. The comparison basis
* -- the exact installed claim, running version and reference this status
* was computed from -- sits in the row's title attribute (a hover tooltip)
* rather than a separate expand control, since it's supplementary detail
* an operator wants on demand, not on every glance at the table.
*
* Split out from settings.js (which top-level imports settings.css) so it
* can be unit tested under plain node --test.
*/
export function updateStatusCard(components) {
if (!components.length) {
return section(
"How each component is deployed, and whether what's running matches what's installed.",
empty("No components reported", "The configured update-check command returned nothing."),
function Section({ sub, title, children }) {
return (
<div className="card cfg-section">
<div className="card-head">
<div>
<h2 className="card-title">{title || "Update status"}</h2>
<p className="card-sub">{sub}</p>
</div>
</div>
{children}
</div>
);
}
const STATUS_LABELS = { ok: "OK", update_available: "Update available", drift: "Drift", unknown: "Unknown" };
const STATUS_KINDS = { ok: "ok", update_available: "info", drift: "danger", unknown: "idle" };
export function UpdateStatusCard({ components }) {
if (!components || !components.length) {
return (
<Section sub="How each component is deployed, and whether what's running matches what's installed.">
<Empty title="No components reported" detail="The configured update-check command returned nothing." />
</Section>
);
}
return section(
"How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.",
el(
"div.table-scroll",
el(
"table.table",
el("thead", el("tr", ...["Component", "Install type", "Running", "Latest available", "Status"].map((h) => el("th", h)))),
el(
"tbody",
...components.map((c) => {
const basis = [
`Installed claim: ${c.installed_claim || "unknown"}`,
`Running: ${c.running_version || "not observed"}`,
c.reference ? `Reference: ${c.reference}` : null,
].filter(Boolean).join("\n");
return el(
"tr",
{ title: basis },
el("td.strong", c.label || c.id),
el("td.mono", c.install_type || "—"),
el("td.mono", c.running_version || "—"),
el("td.mono", c.latest_available || "—"),
el("td", pill(STATUS_LABELS[c.status] || c.status, STATUS_KINDS[c.status] || "idle")),
);
}),
),
),
),
);
}
function section(sub, ...children) {
return el(
"div.card.cfg-section",
el("div.card-head", el("div", el("h2.card-title", "Update status"), el("p.card-sub", sub))),
...children,
return (
<Section sub="How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.">
<div className="table-scroll">
<table className="table">
<thead>
<tr>
<th>Component</th><th>Install type</th><th>Running</th><th>Latest available</th><th>Status</th>
</tr>
</thead>
<tbody>
{components.map(c => {
const basis = [
`Installed claim: ${c.installed_claim || "unknown"}`,
`Running: ${c.running_version || "not observed"}`,
c.reference ? `Reference: ${c.reference}` : null,
].filter(Boolean).join("\n");
return (
<tr title={basis} key={c.id || c.label}>
<td className="strong">{c.label || c.id}</td>
<td className="mono">{c.install_type || "—"}</td>
<td className="mono">{c.running_version || "—"}</td>
<td className="mono">{c.latest_available || "—"}</td>
<td>
<Pill text={STATUS_LABELS[c.status] || c.status} kind={STATUS_KINDS[c.status] || "idle"} />
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</Section>
);
}