diff --git a/ui/src/channels/channels.jsx b/ui/src/channels/channels.jsx index 3398b4f96..3a596b400 100644 --- a/ui/src/channels/channels.jsx +++ b/ui/src/channels/channels.jsx @@ -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 {text}; +} - 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 ( +
+
{title}
+ {detail &&
{detail}
} +
+ ); } 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 ( +
+
+
+

Channels

+

The conversational front-ends Archie can be reached through.

+
+
+ +
+
+
+ {error ? ( + + ) : channels.length === 0 ? ( + + ) : ( + channels.map(channel => ( +
+
+

{channel.name}

+ +
+

{channel.description}

+

{channel.detail}

+ {channel.reload_supported ? ( + + ) : ( +

Reload requires a daemon restart for this adapter.

+ )} +
+ )) + )} +
+
+ ); +} + +export function channelsPage(query) { + return ; +} diff --git a/ui/src/logs/logs.jsx b/ui/src/logs/logs.jsx index cfb0df23f..9ca5e661a 100644 --- a/ui/src/logs/logs.jsx +++ b/ui/src/logs/logs.jsx @@ -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 {text}; +} + +function Empty({ title, detail }) { + return ( +
+
{title}
+ {detail &&
{detail}
} +
+ ); +} + +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 ( +
+ {shortTime(entry.time)} + {(entry.level || "info").toUpperCase()} + + {entry.message || entry.msg || ""} + {Object.entries(fields).map(([k, v]) => ( + + {k} + {String(fmtValue(v))} + + ))} + +
+ ); +} 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 ( +
+
+
+

Logs

+

What Archie has been doing, newest last.

+
+
+ + +
+
+ +
+
+
+ + + { + const v = e.target.value; + if (searchTimeout.current) clearTimeout(searchTimeout.current); + searchTimeout.current = setTimeout(() => { + setFilters(f => ({ ...f, q: v })); + }, 250); + }} + /> +
+
+ {meta} + +
+
+ +
+ {meta === "Cannot read logs" ? ( + + ) : !entriesToRender.length ? ( + + ) : ( + entriesToRender.map(entry => ) + )} +
+
+
+ ); +} + +export function logsPage(query) { + return ; } diff --git a/ui/src/memory/memory.jsx b/ui/src/memory/memory.jsx index 6f147c358..4a2e6ff63 100644 --- a/ui/src/memory/memory.jsx +++ b/ui/src/memory/memory.jsx @@ -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 {text}; } -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 ( +
+
{title}
+ {detail &&
{detail}
} +
); } -// 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 ( +
+
+
+

{p.name || "provider"}

+

{roleLabel(p.role)}

+
+ {p.available ? : } +
+ {!p.available && ( +

+ Configured but not usable right now — a required binary or connection may be missing. +

+ )} + {tools.length ? ( +
    + {tools.map((t, idx) => ( +
  • +
    {t.name}
    + {t.description &&
    {t.description}
    } +
  • + ))} +
+ ) : ( +

This provider exposes no tools, so the agent cannot use it.

+ )} +
+ ); +} + +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 ( +
+
+
+

Memory

+

What Archie can recall between conversations, and the tools it uses to do it.

+
+
+ +
+
+
+ {loading ? ( +
Loading…
+ ) : error ? ( +
+ ) : !enabled || !providers.length ? ( +
+ +
+ ) : ( +
+ {providers.map((p, idx) => ( + + ))} +
+ )} +
+
+ ); +} + +export function memoryPage(query) { + return ; +} diff --git a/ui/src/settings/config-row.jsx b/ui/src/settings/config-row.jsx index 137cf0b00..93d8926a5 100644 --- a/ui/src/settings/config-row.jsx +++ b/ui/src/settings/config-row.jsx @@ -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 ( +
+ {label} + {text} +
+ ); + } - 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 ( +
+ {label} + {text} + {lockedReason} +
+ ); } - // 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 ( +
+ {label} + {text} +
+ ); } - 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 = ( + + ); + } else if (opts.type === "enum") { + inputEl = ( + + ); + } else { + inputEl = setEditValue(e.target.value)} onKeyDown={handleKeyDown} ref={inputRef} />; + } + + return ( +
+ {label} + {inputEl} +
+ + +
+ {error && {error}} +
+ ); + } + + return ( +
+ {label} + {text} +
+ {overridden && overridden} + + {overridden && } +
+ {error && {error}} +
+ ); } -// 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": { diff --git a/ui/src/settings/settings.jsx b/ui/src/settings/settings.jsx index 71dc04123..bf4468ac5 100644 --- a/ui/src/settings/settings.jsx +++ b/ui/src/settings/settings.jsx @@ -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 {text}; } -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 ( +
+
{title}
+ {detail &&
{detail}
} +
); } -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 ( +
+
+
+

{title}

+

{sub}

+
+
+ {children} +
); } -// 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 ( +
+ +
+ ); + return ( +
+
+ {origins.map((origin, i) => ( + + ))} +
+
); } -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 ( +
+ +
); } - 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 ( +
+

Statuses

+ {statuses.length ? ( +
+ {statuses.map(s => { + const label = s.label ?? statusLabel(s.id); + const kind = s.kind ?? statusKind(s.id); + return ( +
+ {s.id} + +
+ ); + })} +
+ ) : ( + + )} + +

Actions

+ {actions.length ? ( +
+ {actions.map(a => { + const label = a.label ?? a.id; + const cls = roleButtonClass(a.kind); + return ( +
+ {a.id} + + + +
+ ); + })} +
+ ) : ( + + )} +
); } -// 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 ( + + + {error && {error}} + + ); } -// 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 ( + + setVal(e.target.value)} + onBlur={commit} + onKeyDown={handleKeyDown} + disabled={loading} + /> + {error && {error}} + + ); } -function gateSummary(gate) { - if (!gate?.length) return "—"; - return gate.map((cmd) => cmd.join(" ")).join(" → "); -} +function RepositoriesCard({ repos, onSaved }) { + if (!repos?.length) { + return ( +
+ +
+ ); + } -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.] 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 ( +
+
+ + + + + + + + {repos.map((r, i) => ( + + + + + + + + + + + ))} + +
RepositoryBase branchEcosystemQuality gateProtected pathsConcurrentMax retriesSelf-review
{r.owner}/{r.name}{r.base}{r.ecosystem || "go"}{gateSummary(r.gate)}{r.protect?.length ? r.protect.join(", ") : "—"}
+
+
); } @@ -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 ( +
+

Model roles

+ {modelEntries.length ? ( +
+ {modelEntries.map(([role, ref]) => ( + + ))} +
+ ) : ( + + )} + +

Providers

+ {providerEntries.length ? ( +
+ + + + + + {providerEntries.map(([name, p]) => ( + + + + + + + + ))} + +
ProviderClassBase URLAPI key env varStatus
{name}{p.class}{p.base_url || "default"}{p.api_key_env || "—"} + {p.configured ? : } +
+
+ ) : ( + + )} +
+ ); +} + +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 ( +
+
+
+

Configuration

+

What archied is actually running with right now.

+
+
+ +
+
+ +
+ {!versionMissing && ( + versionError ? ( +
+ ) : versionData ? ( + + ) : null + )} +
+ +
+ +
+ +
+ {cfgError ? ( +
+ ) : !cfg || Object.keys(cfg).length === 0 ? ( +
+ ) : ( + <> + {cfg.reload?.overlay_unavailable && ( +

The runtime config overlay is not in effect: {cfg.reload.overlay_unavailable}

+ )} + {cfg.reload?.last_error && ( +

The last config reload failed; the running config is unchanged: {cfg.reload.last_error}

+ )} + + {(cfg.schema || []).map((s, i) => { + const rows = s.fields.filter(f => f.type !== "structured"); + if (!rows.length) return null; + return ( +
+
+ {rows.map(f => ( + + ))} +
+
+ ); + })} + + + + + + )} +
+
+ ); +} + +export function settingsPage(query) { + return ; +} diff --git a/ui/src/settings/update-status.jsx b/ui/src/settings/update-status.jsx index 3a0d5632c..58c538601 100644 --- a/ui/src/settings/update-status.jsx +++ b/ui/src/settings/update-status.jsx @@ -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 {text}; +} -const STATUS_KINDS = { - ok: "ok", - update_available: "info", - drift: "danger", - unknown: "idle", -}; +function Empty({ title, detail }) { + return ( +
+
{title}
+ {detail &&
{detail}
} +
+ ); +} -/** - * 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 ( +
+
+
+

{title || "Update status"}

+

{sub}

+
+
+ {children} +
+ ); +} + +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 ( +
+ +
); } - 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 ( +
+
+ + + + + + + + {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 ( + + + + + + + + ); + })} + +
ComponentInstall typeRunningLatest availableStatus
{c.label || c.id}{c.install_type || "—"}{c.running_version || "—"}{c.latest_available || "—"} + +
+
+
); }