A local-first multi-agent app development platform, built on PenguinHarness
/**
* Plugin options (admin only, server-global): one card per settings entry — a group a module
* contributes (the sandbox) or a loaded plugin's declared configuration — drawn from its
* schema: a string, a secret, a boolean, a number, a choice, a list of lines or a table (a
* row per preset, say; plugin-config-table.tsx) per field, so the page knows nothing about any
* particular entry. Fields a group marks `advanced` sit in a fold under the others, collapsed
* by default (advanced-fold.tsx). A group with a `switch` draws that field alone while it is
* off, and one that reports a `backend` it lacks offers to install it when the switch is turned
* on (sandbox-backend-prompt.tsx). An entry naming a
* `parent` is drawn inside that card (a sandbox backend's own options inside the sandbox's) and
* saved with it; notices the entry reports sit under its title. Each card saves on its own;
* nothing is written until its Save, which sends each changed entry of the card in one PUT. A secret field always starts empty and shows
* the stored value's mask under it: blank keeps what is stored, typing replaces it, and the
* clear checkbox drops it. The server validates against the same schema and answers a
* rejected field by name, which renders under that field; a save it refuses for any other
* reason (the group went away, the session expired, the machine is unreachable) keeps the
* reason on the card, above its Save — the drafts are untouched, so that button is the retry
* (plugin-config-save.ts).
*
* Each server keeps its own values, so the page edits one machine at a time: a picker at the
* top switches between this server and the machines the Project holds a connection to, and
* every read, save and action goes to the picked machine through this server's tunnel.
* Nothing is copied between machines.
*
* Values hydrate when the section mounts and the saved response is adopted as the new
* baseline, the proxy page's rule; the plugin picks the change up through its watch, so
* nothing here says "restart". Either read failing — that first one, or the one an install makes
* afterwards to bring the cards' live parts up to date — keeps its reason on the page rather than
* in a toast that would be gone before the person looked (plugin-config-read.ts).
*/
import { useEffect, useRef, useState } from "react";
import type { PluginConfigEntry, PluginConfigField } from "@adelie/server/api";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { toneInk } from "../../lib/tone";
import { useLocale } from "../../state/locale";
import { localizedText } from "../chat/skill-use";
import { apiErrorText } from "../../lib/api-error";
import { useSessions } from "../../state/sessions";
import { useProject } from "../../state/project";
import {
THIS_SERVER_KEY,
backendToOffer,
dismissBackendPrompt,
installInOrder,
} from "../../lib/sandbox-backend-prompt";
import { dispatchPluginConfigSaved } from "../../lib/plugin-config-event";
import { MachinePicker } from "../machines/machine-picker";
import { AdvancedFold } from "./advanced-fold";
import {
baselineOf,
draftOf,
drawnFields,
sameValue,
switchedOff,
valueOf,
} from "./plugin-config-draft";
import type { Draft } from "./plugin-config-draft";
import { ConfigField } from "./plugin-config-field";
import { ConfigHeading } from "./plugin-config-heading";
import { withLiveParts } from "./plugin-config-live";
import { pluginConfigStale, pluginConfigUnreadable } from "./plugin-config-read";
import { pluginSaveRefusal } from "./plugin-config-save";
import { backendInstallRefusal } from "./sandbox-backend-refusal";
import type { BackendInstallFailure, BackendInstallStop } from "./sandbox-backend-refusal";
import { SandboxBackendPrompt } from "./sandbox-backend-prompt";
import {
Button,
ConfirmModal,
NoticeStrip,
SettingsSection,
toastInfo,
toastSuccess,
} from "@adelie/ui";
/**
* Brings one card into view once the list has loaded — an opening that names a card (the
* composer's permission menu names `sandbox`) lands on it rather than on the top of the page.
* Once per opening: scrolling away afterwards is the person's choice.
*/
function FocusCard({ focus, ready }: { focus: string | undefined; ready: boolean }) {
const anchor = useRef<HTMLSpanElement>(null);
const done = useRef(false);
useEffect(() => {
if (focus === undefined || !ready || done.current) return;
const card = anchor.current?.parentElement?.querySelector(
`[data-plugin-config="${CSS.escape(focus)}"]`,
);
if (card) {
card.scrollIntoView({ block: "start" });
done.current = true;
}
}, [focus, ready]);
return <span ref={anchor} hidden />;
}
export function PluginsSection({ focus }: { focus?: string } = {}) {
const { locale } = useLocale();
const localized = (en: string | undefined, zhText: string | undefined) =>
en === undefined ? undefined : localizedText(locale, en, zhText);
const [entries, setEntries] = useState<PluginConfigEntry[] | null>(null);
const [drafts, setDrafts] = useState<Record<string, Draft>>({});
/** Secret fields whose stored value the next Save drops, keyed `<plugin>\0<field>`. */
const [clearing, setClearing] = useState<Set<string>>(new Set());
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
/**
* Why a card's save was refused for a reason that names no field — the group went away under
* the page, the session expired, the server errored, the machine is unreachable — keyed by the
* card's name. Drawn just above the Save button that is its retry, rather than as a toast: the
* drafts are exactly as they were, so a card that looks untouched is the worse answer.
*/
const [saveRefusals, setSaveRefusals] = useState<Record<string, string>>({});
const [busy, setBusy] = useState<string | null>(null);
/**
* A group action awaiting confirmation, with its own title. A plugin cannot mark an action
* as dangerous, so every one asks before it runs on the machine.
*/
const [pendingAction, setPendingAction] = useState<{
entry: PluginConfigEntry;
id: string;
title: string;
} | null>(null);
/**
* The words for an action the machine refused, drawn inside the confirmation that asked for
* it. Kept here rather than in a toast: nothing ran, so retrying is the next thing the person
* does — and the button that retries it is in this card, while a toast dismisses itself after
* six seconds and sits above it.
*/
const [actionRefusal, setActionRefusal] = useState<string | null>(null);
const { machineIds, machineLabels } = useSessions();
/** The machine whose settings the page shows and saves: null for this server. */
const [machine, setMachine] = useState<string | null>(null);
/**
* Why the settings on screen could not be read, null when the read landed. Two reads can fail:
* the one on mount leaves the page empty under this sentence (nothing to draw), and the one
* after an install leaves the cards as the machine answered before it (`pluginConfigStale`).
* Either way it is about this server or the picked machine (`nameOf`), it is drawn where the
* cards are, and it stays until another machine is picked, a read lands, or the page is opened
* again.
*/
const [readError, setReadError] = useState<string | null>(null);
const nameOf = (id: string) => machineLabels.get(id) ?? id;
const projectId = useProject().currentProject?.projectId ?? null;
/** The backend packages the install prompt offers, while it is open. */
const [offered, setOffered] = useState<string[] | null>(null);
const [installing, setInstalling] = useState(false);
/**
* Why a run of those installs left packages behind, and which ones — drawn inside the prompt
* that asked, under the button that retries them (sandbox-backend-refusal.ts). Null when the
* last run installed everything, or before the first one.
*/
const [installRefusal, setInstallRefusal] = useState<string | null>(null);
const adopt = (list: PluginConfigEntry[]) => {
setEntries(list);
setDrafts(Object.fromEntries(list.map((e) => [e.name, draftOf(e)])));
setClearing(new Set());
};
/** One plugin's saved entry becomes its new baseline; every other form keeps its draft. */
const adoptOne = (saved: PluginConfigEntry) => {
setEntries((prev) => (prev ?? []).map((e) => (e.name === saved.name ? saved : e)));
setDrafts((prev) => ({ ...prev, [saved.name]: draftOf(saved) }));
setClearing((prev) => new Set([...prev].filter((k) => !k.startsWith(`${saved.name}\0`))));
};
const clearErrorsOf = (plugin: string) =>
setFieldErrors((prev) =>
Object.fromEntries(Object.entries(prev).filter(([k]) => !k.startsWith(`${plugin}\0`))),
);
useEffect(() => {
let cancelled = false;
setEntries(null);
setReadError(null);
setFieldErrors({});
// A sentence about a save describes the values another machine (or another mount) held.
setSaveRefusals({});
void api.adminGetPluginConfig(machine).then(
(config) => {
if (!cancelled) adopt(config.plugins);
},
(e: unknown) => {
if (cancelled) return;
// A read that failed leaves no settings to draw: an empty page that says why, rather
// than this server's settings under a machine's name. The reason stays on screen —
// the page is blank in this state, so a toast would be the only account of it there
// ever was, and it is gone six seconds later.
adopt([]);
setReadError(
pluginConfigUnreadable(machine === null ? null : nameOf(machine), apiErrorText(e)),
);
},
);
return () => {
cancelled = true;
};
}, [machine]);
/**
* While any group reports work in progress (an install it started), its notices and actions
* are read again every few seconds — only those: a draft being typed elsewhere on the page is
* not replaced, and a group that finished gets its new notices and buttons the same way.
*/
const inProgress = (entries ?? []).some((e) =>
(e.notices ?? []).some((n) => n.tone === "progress"),
);
useEffect(() => {
if (!inProgress) return;
let cancelled = false;
// The machine whose settings are on screen: an install started over there reports its
// progress over there.
const timer = setTimeout(() => {
void api.adminGetPluginConfig(machine).then(
(config) => {
if (cancelled) return;
setEntries((prev) =>
(prev ?? []).map((e) => {
const next = config.plugins.find((p) => p.name === e.name);
if (next === undefined) return e;
const { notices: _n, actions: _a, ...rest } = e;
return {
...rest,
...(next.notices !== undefined ? { notices: next.notices } : {}),
...(next.actions !== undefined ? { actions: next.actions } : {}),
};
}),
);
},
() => {
// A failed read leaves the card as it was; the next change of `entries` does not
// come, so try again on the same schedule.
if (!cancelled) setEntries((prev) => (prev === null ? prev : [...prev]));
},
);
}, 2000);
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [entries, inProgress, machine]);
/**
* The update one entry's draft makes, or `null` when it changes nothing; `false` when a
* number box does not parse (its error is set, and nothing in the card is sent).
*/
const updateOf = (entry: PluginConfigEntry): Record<string, unknown> | null | false => {
const draft = drafts[entry.name] ?? {};
const values: Record<string, unknown> = {};
let changed = false;
for (const [name, field] of Object.entries(entry.configuration.properties)) {
if (field.type === "secret") {
const typed = typeof draft[name] === "string" ? (draft[name] as string).trim() : "";
if (typed !== "") {
values[name] = typed;
changed = true;
} else if (clearing.has(`${entry.name}\0${name}`)) {
values[name] = null;
changed = true;
}
continue;
}
const v = valueOf(field, draft[name]);
if (typeof v === "number" && !Number.isFinite(v)) {
setFieldErrors((prev) => ({
...prev,
[`${entry.name}\0${name}`]: S.settings.pluginFieldNotNumber,
}));
return false;
}
// Only what changed: sending an untouched field would store its default as a value,
// pinning it against a later change of the default.
if (sameValue(v, baselineOf(field, entry.values[name]))) continue;
values[name] = v;
changed = true;
}
return changed ? values : null;
};
/** Saves a card: its entry and the entries drawn inside it, each changed one in its own PUT. */
const save = async (card: PluginConfigEntry, members: PluginConfigEntry[]) => {
if (busy !== null) return;
const updates: Array<[PluginConfigEntry, Record<string, unknown>]> = [];
for (const entry of members) {
const update = updateOf(entry);
if (update === false) return;
if (update !== null) updates.push([entry, update]);
}
if (updates.length === 0) {
toastInfo(S.common.noChangesToSave);
return;
}
setBusy(card.name);
// Another attempt: the sentence about the last one is stale from this moment on.
setSaveRefusals((prev) => {
const next = { ...prev };
delete next[card.name];
return next;
});
for (const [entry] of updates) clearErrorsOf(entry.name);
try {
for (const [entry, values] of updates) {
try {
const res = await api.adminPutPluginConfig({ name: entry.name, values }, machine);
const saved = res.plugins.find((e) => e.name === entry.name);
if (saved !== undefined) adoptOne(saved);
else adopt(res.plugins);
} catch (e) {
// A rejected field is named in the message as `"field" …`, and renders under that
// field; anything else is about the card that asked, and stays there (7.71).
const refusal = pluginSaveRefusal(e);
if (refusal.field !== null) {
setFieldErrors({ [`${entry.name}\0${refusal.field}`]: refusal.text });
} else {
setSaveRefusals((prev) => ({ ...prev, [card.name]: refusal.text }));
}
return;
}
}
toastSuccess(S.common.saved);
// Pages showing what the card configures (the composer's permission menu) read it again.
for (const [entry] of updates) {
dispatchPluginConfigSaved({ group: entry.name, card: card.name });
}
} finally {
setBusy(null);
}
};
/**
* A group action's button: asks first, with the action's own title (see pendingAction) and
* without the previous refusal — that sentence belonged to the attempt before.
*/
const askAction = (entry: PluginConfigEntry, id: string) => {
const action = entry.actions?.find((a) => a.id === id);
setPendingAction({
entry,
id,
title: (action && localized(action.title, action.titleZh)) ?? action?.title ?? id,
});
setActionRefusal(null);
};
/**
* Runs a group's action: what the deployment must DO once on the machine (the Windows
* sandbox's local accounts). The result's own words are what the person sees — the module
* knows what happened, this page does not — and the groups it answers with replace ours,
* because a setup that worked changes what the card says about itself.
*
* The confirmation closes on the answer, not on the request: an action that did not run —
* a refused request, or a group answering `ok: false` ("another task is running") — leaves
* the machine as it was, so the card stays open with those words in it and the same button
* retries. Closing it as the request left used to take the reason away with it.
*/
const runAction = async (entry: PluginConfigEntry, action: string) => {
setBusy(`${entry.name}\0${action}`);
try {
const res = await api.adminRunPluginConfigAction({ name: entry.name, action }, machine);
adopt(res.plugins);
const message = localized(res.message, res.messageZh) ?? res.message;
if (res.ok) {
setPendingAction(null);
toastSuccess(message);
} else setActionRefusal(message);
} catch (e) {
setActionRefusal(apiErrorText(e));
} finally {
setBusy(null);
}
};
/**
* The switch was turned on: if the machine reports no sandbox backend for its OS, ask whether
* to install its default ones. The switch stays on in the draft whatever the answer.
*/
const offerBackend = (entry: PluginConfigEntry) => {
const pkgs = backendToOffer(entry, machine ?? THIS_SERVER_KEY);
if (pkgs === null) return;
// A fresh question: the sentence under it belonged to the attempt before.
setInstallRefusal(null);
setOffered(pkgs);
};
const closePrompt = (dontAskAgain: boolean) => {
if (dontAskAgain) dismissBackendPrompt(machine ?? THIS_SERVER_KEY);
setOffered(null);
setInstallRefusal(null);
};
/**
* Installs the offered backends the way the Plugins page does, one after another: into this
* Project's table for the machine on screen only — this server's own machine id when the card
* shows this server, so no other machine is asked to run it.
*
* The prompt closes on a run that installed everything, not on the request: a package the
* server listed but the process could not load, or a request that never answered, leaves the
* machine without the backend the card asked for — so the dialog stays open with that reason
* under its question, offering only the packages still missing, and its own Install button is
* the retry (a toast was the only account of a refusal before, gone six seconds later, over a
* card still reading "no backend for this OS"). Either way the card's live parts are read again,
* so what did install shows.
*/
const installOffered = async (dontAskAgain: boolean) => {
if (offered === null || installing) return;
if (projectId === null) {
// The dialog that asked keeps its own precondition too: its button is where the next try is.
setInstallRefusal(S.settings.sandboxBackendPrompt.noProject);
return;
}
const pkgs = offered;
const installed: string[] = [];
const failures: BackendInstallFailure[] = [];
let stopped: BackendInstallStop | null = null;
setInstallRefusal(null);
setInstalling(true);
let target = machine;
await installInOrder(
pkgs,
async (pkg) => {
const to = (target ??= (await api.getInstalledPlugins(projectId)).machineId);
const res = await api.installPlugin(projectId, pkg, to);
return res.plugins.find((p) => p.specifier === pkg)?.error;
},
{
installed: (pkg) => {
installed.push(pkg);
toastSuccess(S.plugins.deploymentInstalledToast(pkg));
},
failed: (pkg, error) => failures.push({ pkg, error }),
threw: (e) => {
stopped = { error: e };
},
},
);
try {
const config = await api.adminGetPluginConfig(machine);
setEntries((prev) => withLiveParts(prev ?? [], config.plugins));
// The cards say what the machine answered: nothing is stale any more.
setReadError(null);
} catch (e) {
// The packages that did install are already in the Project's table, but the cards' notices,
// actions and backend report are what the machine said before the install — a card that
// still reads "no backend for this OS" is the worst answer, and a six-second toast over it
// was all that said why (7.72). Say it where the cards are; opening the page again is the
// retry.
setReadError(pluginConfigStale(machine === null ? null : nameOf(machine), apiErrorText(e)));
} finally {
setInstalling(false);
}
const remaining = pkgs.filter((p) => !installed.includes(p));
if (remaining.length === 0) {
closePrompt(dontAskAgain);
return;
}
// Only what is still missing: the retry must not install again what already landed, because
// every install reloads the server's plugins and stops agent runs in progress.
setOffered(remaining);
setInstallRefusal(backendInstallRefusal(failures, stopped, remaining));
};
// Only when there is another machine to pick: a single server has nothing to switch to.
const picker =
machineIds.length > 0 ? (
<div className="flex justify-end">
<MachinePicker
aria-label={S.settings.pluginConfigMachine}
choices={[
{ value: THIS_SERVER_KEY, label: S.plugins.thisServer },
...machineIds.map((id) => ({ value: id, label: nameOf(id) })),
]}
value={machine ?? THIS_SERVER_KEY}
onChange={(v) => {
if (busy === null) setMachine(v === THIS_SERVER_KEY ? null : v);
}}
/>
</div>
) : null;
if (entries === null) return <SettingsSection>{picker}</SettingsSection>;
const patch = (plugin: string, name: string, value: unknown) => {
setDrafts((prev) => ({ ...prev, [plugin]: { ...(prev[plugin] ?? {}), [name]: value } }));
setFieldErrors((prev) => {
const next = { ...prev };
delete next[`${plugin}\0${name}`];
return next;
});
};
const control = (entry: PluginConfigEntry, name: string, field: PluginConfigField) => {
const key = `${entry.name}\0${name}`;
const choiceField = field.rowChoice?.field;
return (
<ConfigField
key={name}
entry={entry}
name={name}
field={field}
value={drafts[entry.name]?.[name]}
error={fieldErrors[key]}
// A refused cell is named `<field>.<row>.<column>`; the table lists them under itself.
tableErrors={Object.entries(fieldErrors)
.filter(([k]) => k === key || k.startsWith(`${key}.`))
.map(([, text]) => text)}
{...(choiceField !== undefined
? {
choice: drafts[entry.name]?.[choiceField],
onChoice: (row: string) => patch(entry.name, choiceField, row),
}
: {})}
clearing={clearing.has(key)}
onChange={(value) => {
patch(entry.name, name, value);
// Typing a new secret is not also clearing it.
if (field.type === "secret") setClearingKey(key, false);
if (value === true && name === entry.configuration.switch) {
offerBackend(entry);
}
}}
onClearingChange={(on) => setClearingKey(key, on)}
disabled={busy !== null}
locale={locale}
/>
);
};
const setClearingKey = (key: string, on: boolean) =>
setClearing((prev) => {
const next = new Set(prev);
if (on) next.add(key);
else next.delete(key);
return next;
});
/** An entry's fields in declaration order: the basic ones, then the Advanced fold, if any. */
const fields = (entry: PluginConfigEntry) => {
const all = drawnFields(entry, drafts[entry.name]);
const advanced = all.filter(([, field]) => field.advanced === true);
return (
<>
{all.filter(([, field]) => field.advanced !== true).map(([n, f]) => control(entry, n, f))}
{advanced.length > 0 && (
<AdvancedFold>{advanced.map(([n, f]) => control(entry, n, f))}</AdvancedFold>
)}
</>
);
};
// A card per entry with no parent on the page; an entry whose parent is not listed stands
// on its own rather than disappearing.
const names = new Set(entries.map((e) => e.name));
const cards = entries.filter((e) => e.parent === undefined || !names.has(e.parent));
return (
<SettingsSection>
{picker}
{readError !== null && (
<NoticeStrip
tone="attention"
as="p"
// Under a failed first read the page is empty, and under a failed read after an install
// the cards keep what the machine said before it: either way this line is the account
// of the state, so it is read out rather than glanced at.
role="alert"
className="rounded-md px-3 py-2 text-xs"
>
{readError}
</NoticeStrip>
)}
<FocusCard focus={focus} ready={entries.length > 0} />
{cards.map((card) => {
const children = entries.filter((e) => e.parent === card.name);
const saveRefusal = saveRefusals[card.name] ?? null;
return (
<section
key={card.name}
data-plugin-config={card.name}
className="space-y-3 rounded-md border border-gray-200 p-4 dark:border-gray-800"
>
<ConfigHeading
entry={card}
draft={drafts[card.name]}
nested={false}
disabled={busy !== null}
onAction={(action) => askAction(card, action)}
locale={locale}
/>
{fields(card)}
{(switchedOff(card, drafts[card.name]) ? [] : children).map((child) => (
<div
key={child.name}
className="space-y-3 border-t border-gray-100 pt-3 dark:border-gray-800/60"
>
<ConfigHeading
entry={child}
draft={drafts[child.name]}
nested
disabled={busy !== null}
onAction={(action) => askAction(child, action)}
locale={locale}
/>
{fields(child)}
</div>
))}
{/* The save's own failure, above the button that is its retry — the fields are
exactly as they were, so nothing else on this card would say it. Clamped to two
lines with the whole of it on hover, because a server's words run long. */}
{saveRefusal !== null && (
<p
role="alert"
data-tooltip={S.common.refused(saveRefusal)}
data-tooltip-content="text"
className={`line-clamp-2 break-words text-xs ${toneInk.danger}`}
>
{S.common.refused(saveRefusal)}
</p>
)}
<div className="flex justify-end">
<Button
size="sm"
variant="primary"
disabled={busy !== null}
onClick={() => void save(card, [card, ...children])}
>
{busy === card.name ? S.common.saving : S.common.save}
</Button>
</div>
</section>
);
})}
<ConfirmModal
open={pendingAction !== null}
title={S.settings.pluginActionTitle}
tone="primary"
onClose={() => setPendingAction(null)}
onConfirm={() => {
if (pendingAction !== null) void runAction(pendingAction.entry, pendingAction.id);
}}
// The card stays open while the action runs, so its own buttons must not send it twice.
busy={busy !== null}
confirmLabel={S.settings.pluginActionRun}
cancelLabel={S.common.cancel}
refusal={actionRefusal === null ? undefined : S.common.refused(actionRefusal)}
>
<p className="text-sm text-gray-600 dark:text-gray-300">
{pendingAction !== null
? S.settings.pluginActionConfirm(
pendingAction.title,
machine === null ? null : nameOf(machine),
)
: ""}
</p>
</ConfirmModal>
<SandboxBackendPrompt
pkgs={offered}
machineName={machine === null ? S.plugins.thisServer : nameOf(machine)}
busy={installing}
refusal={installRefusal}
onInstall={(dontAskAgain) => void installOffered(dontAskAgain)}
onLater={(dontAskAgain) => {
if (!installing) closePrompt(dontAskAgain);
}}
/>
</SettingsSection>
);
}