A local-first multi-agent app development platform, built on PenguinHarness
/**
* Plugin library page: the built-in plugin library (loaded by core from the @adelie/* packages), shown sectioned by category.
* A plugin ships skills and/or a hook package (scripts the harness runs at the loop's hook
* points, e.g. after every Task), and is installed on an Agent as a whole. Each list is a
* collapsible section whose head strip folds it (the theme's layout motion moves the fold). Cards
* within a group form a grid, generously sized: two per row from the sm breakpoint up, one per
* row on narrow screens. Each card = a rounded icon tile centered against the two text rows
* (its color comes from skillTileColor — a per-name palette hashed from the plugin name; DTO
* icon = the plugin's raw icon.svg (beside plugin.json), rendered inline once it passes
* sanitize, otherwise the puzzle piece) + a name (monospace) and short description on the
* right, one line each
* (single-line truncation, falling back to the full description when missing) + a line below
* both with what the plugin contains ("N skills", one "<event> hook" badge per hook point)
* and its metadata (version · usage count "used by N Agents"); group and card copy follow the
* UI language (localizedText / localizedShortText), and groups have no description. The page
* draws two collapsible sections, and a library plugin sits in the first one exactly when the
* Agent the page is working with holds it (splitPluginRows): a card the reader sees tagged
* "not installed" is never filed under "installed plugins". The tag
* line carries the market shelf's state for the Agent the page is working with —
* not installed / installed / updatable (marketState, off the server's own list of installs it
* says are behind) — and the action row leads with that shelf's one-click button: a labelled
* "Install to <agent>" when that Agent has nothing of the plugin, the update confirmation the
* Rotate button opens when its copy is behind, nothing when it is current. Icon
* buttons for actions (copy goes into aria-label and title) —
* - Rotate "update installs" (shown only when the server lists some Agent's installed copy
* behind the library — `AgentSummary.pluginUpdates`; the page never compares versions
* itself): opens a confirm dialog (lists each Agent's old → new version and warns the
* overwriting reinstall drops local edits), then reinstalls the current library copy on
* every outdated Agent (install-again-is-update semantics), with a single success toast; the
* manage-installs Modal marks outdated rows with an accent "Update" button doing the same per
* Agent (through the same confirm);
* - Paper plane "quick start" (plugins with at least one skill): enters /chat/new draft mode on
* the currently selected agent, pre-selects one of the plugin's skills the agent has
* installed, and pre-fills the invocation text per UI language ("use the X skill" in the
* active dictionary, overwriting any existing draft body); disabled unless that agent has
* one of the plugin's skills installed — quick start opens the draft there, so it can't
* pre-select a skill the current agent lacks;
* - Download "manage installs": a Modal listing every Agent in the current Project —
* not-installed shows "Install", installed shows "Installed" (hover switches to
* "Uninstall", click to uninstall); any member can operate it; optimistic update, a
* top-level toast on success for install/uninstall, rollback on failure.
* A refusal is not a toast: an install's — from this row's toggle or the card's one-click
* button — is drawn under that plugin's card, naming the Agent it could not reach
* (install-refusal.ts), while the three writes the card asks about first (update, uninstall,
* delete) keep their confirmation open with the server's words inside it — see the
* PluginCard's three confirmations. Installed means the whole plugin is: every one of its
* skills is in the Agent's installed skills and, when it ships a hook package, that package is
* in the Agent's installed hooks —
* which is why the page fetches both lists per Agent. Uninstall takes the plugin apart the
* same way: one DELETE per skill and one for the hook package.
*/
import { useCallback, useEffect, useState } from "react";
import { Link, useNavigate } from "react-router";
import type {
AgentSummary,
HookItem,
InstalledPluginsResponse,
PluginDirectoryResponse,
PluginGroupItem,
PluginIndexEntry,
PluginItem,
SkillMetadataItem,
} from "@adelie/server/api";
import {
AgentAvatar,
Badge,
Button,
CollapsibleSection,
ConfirmModal,
CopyButton,
DownloadIcon,
GlyphIcon,
ICONS,
ICON_SIZE,
Modal,
Notice,
PageFrame,
PageHeader,
SearchInput,
Skeleton,
SkeletonCard,
StatusIcon,
Text,
TodoNotice,
UpdateDot,
toastError,
toastSuccess,
} from "@adelie/ui";
import * as api from "../../api/endpoints";
import { ApiError } from "../../api/client";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { useDocumentTitle } from "../../lib/use-document-title";
import { useUpdateBadges } from "../../lib/use-update-badges";
import { dismissTodo } from "../../lib/todo-dismissals";
import {
bulkFailureText,
bulkOutcome,
firstFailure,
noticeCounts,
remainingTargets,
} from "../../lib/bulk-update";
import { useAuth } from "../../state/auth";
import { useLocale } from "../../state/locale";
import { agentDisplayName, useProject } from "../../state/project";
import { useSessions } from "../../state/sessions";
import { MachinePicker, type MachineChoice } from "../machines/machine-picker";
import { NAV_ICONS } from "../../lib/nav-icons";
import { DRAFT_SESSION_ID } from "../chat/chat-page";
import { draftKey, loadDraft, saveDraft } from "../chat/draft-cache";
import { prepareNewChatDraft } from "../chat/new-chat";
import { localizedShortText, localizedText } from "../chat/skill-use";
import { downloadArchive } from "../agents/archive-download";
import { refusalOf } from "../models/write-outcome";
import type { WriteOutcome } from "../models/write-outcome";
import { PluginDetailModal } from "./plugin-detail";
import { PluginImportActions } from "./plugin-import-dialog";
import { pluginExportRefused } from "./plugin-export-refusal";
import { pluginImportErrorText, pluginNameFromError } from "./plugin-import";
import { libraryAddRefused } from "./library-add-refusal";
import { installRefusalFor, installRefused } from "./install-refusal";
import type { InstallRefusal } from "./install-refusal";
import { SettingsDialog } from "../settings/settings-dialog";
import { formatRelativeDate } from "../../lib/format";
import { SkillTile } from "../skills/skill-icon-view";
import { toneInk, toneSurface } from "../../lib/tone";
/**
* What one Agent has installed, by name → the installed copy's version (`YYYY.MM.DD.N`, or ""
* when the files carry none): its skills and its hook packages, the two lists a plugin is
* spread over.
*/
export interface AgentInstalls {
skills: ReadonlyMap<string, string>;
hooks: ReadonlyMap<string, string>;
}
/** agentId → what is installed there; in-page install-state snapshot, rewritten in place by optimistic updates. */
export type InstalledMap = ReadonlyMap<string, AgentInstalls>;
/** The three fields of a plugin the install questions below read (the card passes the whole DTO; tests can pass just these). */
export type PluginParts = Pick<PluginItem, "name" | "skills" | "hooks">;
/** "Manage installs" button icon (download into tray, 24×24 line path). */
const INSTALL_ICON = "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3";
const NO_INSTALLS: AgentInstalls = { skills: new Map(), hooks: new Map() };
/** The two lists an install response carries, folded into one Agent's snapshot entry. */
function installsOf(
skills: readonly SkillMetadataItem[],
hooks: readonly HookItem[],
): AgentInstalls {
return {
skills: new Map(skills.map((s) => [s.name, s.version])),
hooks: new Map(hooks.map((h) => [h.name, h.version])),
};
}
/**
* Whether a plugin is installed on an Agent, meaning any part of it is: one of its skills is in
* the Agent's installed skills, or (when it ships a hook package) that package — named after
* the plugin — is in the Agent's installed hooks. A partial copy counts: an install of an older
* version that shipped fewer skills, or one a skill was removed from in the Skills tab, is what
* the server lists as behind and what an update (a whole reinstall) completes; "all parts"
* would call it not installed and hide the update.
*/
export function pluginInstalled(plugin: PluginParts, installs: AgentInstalls | undefined): boolean {
if (installs === undefined) return false;
return (
plugin.skills.some((skill) => installs.skills.has(skill.name)) ||
(plugin.hooks.length > 0 && installs.hooks.has(plugin.name))
);
}
/**
* The version of a plugin's installed copy on one Agent, read off its hook package where it has
* one and off its first installed skill otherwise (a plugin's parts ship at the plugin's
* version), or undefined when the plugin is not installed there. Only ever displayed — the
* "old → new" line of the update confirmation — never compared.
*/
export function installedPluginVersion(
plugin: PluginParts,
installs: AgentInstalls | undefined,
): string | undefined {
if (installs === undefined) return undefined;
if (plugin.hooks.length > 0) return installs.hooks.get(plugin.name);
for (const skill of plugin.skills) {
const version = installs.skills.get(skill.name);
if (version !== undefined) return version;
}
return undefined;
}
/**
* What the market shelf offers for one plugin on the Agent the page is working with: the three
* states a card carries — not installed, installed and current, installed but behind — as one
* value, so the state tag, the one-click button and its wording cannot describe different
* things.
*
* `outdated` comes from `AgentSummary.pluginUpdates` (the server's own comparison of an
* installed copy against the library), never from comparing versions here: a plugin is
* "updatable" when the server already says that Agent's copy is behind, and the button then
* runs the same reinstall the per-Agent "Update" runs.
*/
export type MarketState = "available" | "installed" | "updatable";
export function marketState(
plugin: PluginParts,
installs: AgentInstalls | undefined,
outdated: boolean,
): MarketState {
if (!pluginInstalled(plugin, installs)) return "available";
return outdated ? "updatable" : "installed";
}
/**
* Agents the server says are behind the library on plugin `name` (the update reminder's data
* source): read off `AgentSummary.pluginUpdates`, the same field the plugins gate counts, so
* the card, the notice and the nav dot cannot disagree — and so the web never compares
* `YYYY.MM.DD.N` strings itself. Not-installed Agents are never listed there.
*/
export function outdatedAgentIds(
agents: ReadonlyArray<Pick<AgentSummary, "agentId" | "pluginUpdates">>,
name: string,
): string[] {
return agents
.filter((agent) => agent.pluginUpdates.some((update) => update.name === name))
.map((agent) => agent.agentId);
}
/**
* What updating EVERY outdated plugin on this page would write, grouped the way it is sent.
*
* Read off `AgentSummary.pluginUpdates` — the same field the plugins gate counts — so the plan
* and the notice above the button cannot describe different work. One request per Agent rather
* than one per (Agent, plugin): the install endpoint already takes a list of names, and an Agent
* behind on four plugins is one overwrite either way.
*
* `plugins` is the distinct library plugins across the whole plan, sorted, which is what the
* confirmation lists and what the notice counts — the page shows the library once, so an update
* touching five Agents is still one plugin to the reader.
*/
export interface PluginUpdatePlan {
perAgent: { agentId: string; names: string[] }[];
plugins: string[];
}
export function pluginUpdatePlan(
agents: ReadonlyArray<Pick<AgentSummary, "agentId" | "pluginUpdates">>,
): PluginUpdatePlan {
const perAgent: { agentId: string; names: string[] }[] = [];
const plugins = new Set<string>();
for (const agent of agents) {
const names = agent.pluginUpdates.map((u) => u.name).sort();
if (names.length === 0) continue;
perAgent.push({ agentId: agent.agentId, names });
for (const name of names) plugins.add(name);
}
return { perAgent, plugins: [...plugins].sort() };
}
export function PluginsPage() {
useDocumentTitle(S.nav.plugins);
const navigate = useNavigate();
const { locale } = useLocale();
const { user } = useAuth();
const userId = user?.userId ?? null;
const { currentProject, agents, currentAgent, setCurrentAgentId, reloadAgents } = useProject();
const projectId = currentProject?.projectId ?? null;
/** The plugins trail's raised badge, or undefined — the notice under the title acts on it or clears it. */
const todo = useUpdateBadges().todos.plugins;
/** The bulk update's confirmation is open (null = closed); it holds the plan it will run. */
const [pendingBulk, setPendingBulk] = useState<PluginUpdatePlan | null>(null);
const [bulkRunning, setBulkRunning] = useState(false);
/** The batch's answer when it did not all land: drawn inside the confirmation that asked for it. */
const [bulkRefusal, setBulkRefusal] = useState<string | null>(null);
const [groups, setGroups] = useState<PluginGroupItem[] | null>(null);
const [error, setError] = useState<string | null>(null);
/** GET /api/plugins/directory: the directory line's data (null until it answers, or when the read failed). */
const [directory, setDirectory] = useState<PluginDirectoryResponse | null>(null);
const [directoryError, setDirectoryError] = useState<string | null>(null);
const [installed, setInstalled] = useState<InstalledMap>(new Map());
/** What this Project asks for of the module plugins, and which of those the process runs. */
const [deployment, setDeployment] = useState<InstalledPluginsResponse | null>(null);
/** The registry: every module plugin this deployment could ask for. */
const [index, setIndex] = useState<PluginIndexEntry[] | null>(null);
/** The specifier whose install or removal is running: the list is written one verb at a time. */
const [pendingSpecifier, setPendingSpecifier] = useState<string | null>(null);
const isAdmin = user?.isAdmin === true;
const [settingsOpen, setSettingsOpen] = useState(false);
/** Free text over name, specifier and description. */
const [query, setQuery] = useState("");
/** The filter column's choices: a row shows when it carries one selected category and every selected tag. */
const [pickedCategories, setPickedCategories] = useState<ReadonlySet<string>>(new Set());
const [pickedKinds, setPickedKinds] = useState<ReadonlySet<PluginKind>>(new Set());
const [pickedStates, setPickedStates] = useState<ReadonlySet<PluginState>>(new Set());
/** The installed list starts folded — it is the long one; a search or a filter opens both. */
const [installedOpen, setInstalledOpen] = useState(false);
const [availableOpen, setAvailableOpen] = useState(true);
// The Project's list, re-read whenever the Project changes; a read that fails leaves the
// module rows without their state rather than failing the page.
const reloadDeployment = useCallback(() => {
if (projectId === null) return;
api.getInstalledPlugins(projectId).then(setDeployment, () => setDeployment(null));
}, [projectId]);
useEffect(reloadDeployment, [reloadDeployment]);
const { machineIds, machineLabels } = useSessions();
/** The machine the page shows and edits: null for all machines, or a machine's own id. */
const [viewMachine, setViewMachine] = useState<string | null>(null);
useEffect(() => setViewMachine(null), [projectId]);
const selfId = deployment?.machineId;
/** What the viewed machine answered itself — or why it could not — when it is not this server. */
const [remote, setRemote] = useState<
| { machineId: string; res: InstalledPluginsResponse }
| { machineId: string; error: string }
| null
>(null);
// Read again after every change of the list: the machine is handed its part in the
// background, so a row reads "not on that machine yet" until it has answered with it.
useEffect(() => {
setRemote(null);
if (projectId === null || viewMachine === null || viewMachine === selfId) return;
let cancelled = false;
api.getInstalledPlugins(projectId, viewMachine).then(
(res) => !cancelled && setRemote({ machineId: viewMachine, res }),
(e: unknown) => !cancelled && setRemote({ machineId: viewMachine, error: apiErrorText(e) }),
);
return () => {
cancelled = true;
};
}, [projectId, viewMachine, selfId, deployment]);
const nameOf = (machineId: string) =>
machineId === selfId ? S.plugins.thisServer : (machineLabels.get(machineId) ?? machineId);
const view: PluginView = {
machineId: viewMachine,
remote: remote !== null && "res" in remote ? remote.res : null,
nameOf,
};
/** Whether the machine in view is this server itself, or every machine including it. */
const viewIncludesHere = viewMachine === null || viewMachine === selfId;
// The picker offers the machines this Project reaches and any a table names; a deployment
// with neither has one machine, and no picker.
const otherMachines = [
...new Set([...machineIds, ...(deployment?.plugins ?? []).flatMap((p) => p.machines ?? [])]),
].filter((id) => id !== selfId);
const machineChoices: MachineChoice[] = [
{ value: ALL_MACHINES_CHOICE, label: S.plugins.allMachines },
...(selfId === undefined ? [] : [selfId, ...otherMachines]).map((id) => ({
value: id,
label: nameOf(id),
})),
];
// The registry, fetched once on page entry.
useEffect(() => {
let cancelled = false;
api.getPluginIndex().then(
(res) => {
if (!cancelled) setIndex(res.plugins);
},
() => {
if (!cancelled) setIndex([]);
},
);
return () => {
cancelled = true;
};
}, []);
/**
* A module plugin change waiting for its confirmation (null = none). Applying one
* re-assembles the App, which stops the agent runs in flight in EVERY Project — the same
* cost a hot push has — so it is said before it is done.
*/
const [pendingApply, setPendingApply] = useState<{ specifier: string; install: boolean } | null>(
null,
);
/**
* The server's words for the last module plugin change it refused, drawn inside the
* confirmation that asked for it. It has to outlive a toast: when the write is refused the
* plugin is still exactly as it was, so retrying is the next thing the user does — and the
* button that retries it is in this card.
*/
const [applyRefusal, setApplyRefusal] = useState<string | null>(null);
/**
* Fetching a published plugin into the library, by specifier (null = none): the row's own busy
* state, and — when the name is already taken — the overwrite confirmation that the import
* dialog raises for the same 409.
*/
const [publishing, setPublishing] = useState<string | null>(null);
const [overwriteImport, setOverwriteImport] = useState<{
specifier: string;
name: string;
} | null>(null);
/**
* The sentence for the last install onto an Agent this page did not get, and the plugin it was
* for: it is drawn under that plugin's card (install-refusal.ts). It lives here rather than in
* the card because an install moves the card into the other section before the answer arrives,
* so the instance that sent the request no longer exists by the time a refusal comes back.
*/
const [installRefusal, setInstallRefusal] = useState<{
plugin: string;
text: string;
} | null>(null);
/**
* The server's words for the last "add to the library" it refused, and the row they belong to.
* It has to outlive a toast: the write changed nothing, so that row is still on the shelf with
* the same button, and the sentence belongs in it (library-add-refusal.ts).
*/
const [libraryRefusal, setLibraryRefusal] = useState<{
specifier: string;
reason: string;
} | null>(null);
/**
* Open the confirmation for one module plugin change, without the previous refusal: that
* sentence belonged to the attempt before (one attempt, one reason).
*/
const askApply = (specifier: string, install: boolean) => {
setPendingApply({ specifier, install });
setApplyRefusal(null);
};
/**
* Asks this Project for a module plugin (or drops it); the server lists it and re-assembles
* the App, so the row's state afterwards is what the running process has — including a
* load that failed, which is reported as such rather than toasted as installed.
*
* The confirmation closes on the answer, not on the request: a refusal leaves the plugin
* where it was, so the card stays open with the server's words in it and the same button
* retries. Closing it in a `finally` used to take the reason away with it — the toast that
* carried it dismisses itself after six seconds and sits above the card, not in it.
*/
const runDeploymentInstall = async (specifier: string, install: boolean) => {
if (pendingSpecifier !== null || projectId === null) return;
setPendingSpecifier(specifier);
try {
const next = install
? await api.installPlugin(projectId, specifier, viewMachine)
: await api.uninstallPlugin(projectId, specifier, viewMachine);
setDeployment(next);
setPendingApply(null);
const row = next.plugins.find((p) => p.specifier === specifier);
if (install && row?.error !== undefined) {
toastError(S.plugins.deploymentFailedToast(specifier, row.error));
} else {
toastSuccess(install ? S.plugins.deploymentInstalledToast(specifier) : S.common.saved);
}
} catch (e) {
setApplyRefusal(apiErrorText(e));
} finally {
setPendingSpecifier(null);
}
};
/**
* The directory line alone — what a delete moves. The listing is updated in place there, so
* re-fetching it too would only flash a skeleton over a card the user just removed.
*/
const reloadDirectory = useCallback(async () => {
try {
setDirectory(await api.getPluginDirectory());
setDirectoryError(null);
} catch (e) {
setDirectoryError(apiErrorText(e));
}
}, []);
/**
* The page's two reads in one call — the library listing and the directory line. Every import
* wants both (it adds a card AND moves the count behind it), and neither half may take the
* other down with it: a read that fails still leaves the other half on screen, and only the
* listing has a page-level error state (it is the page's content; the directory's own line
* carries its failure).
*/
const reloadLibrary = useCallback(async () => {
await Promise.all([
api.getPluginLibrary().then(
(res) => {
setGroups(res.groups);
setError(null);
},
(e: unknown) => setError(apiErrorText(e)),
),
reloadDirectory(),
]);
}, [reloadDirectory]);
// Library list and directory line: readable once logged in, read once on page entry and again
// after every import (reloadLibrary above). Both writes are whole-state replacements, so an
// answer that arrives after the page unmounted is discarded rather than guarded against.
useEffect(() => {
void reloadLibrary();
}, [reloadLibrary]);
// Installed skills and hook packages for every Agent in the current Project (fetched in
// parallel, same convention as the sessions context): a single Agent's failure is silently
// treated as "nothing installed" and doesn't break the whole page.
const agentIdsKey = agents.map((a) => a.agentId).join(",");
useEffect(() => {
// Clear the snapshot before fetching: agentId (e.g. default_agent) is
// reused across Projects, and leftover state from the previous project
// would otherwise overwrite the new data when merged below, leaving the
// page permanently showing the old project's install state.
setInstalled(new Map());
if (!projectId || agentIdsKey === "") return;
let cancelled = false;
const ids = agentIdsKey.split(",");
void Promise.all(
ids.map(async (agentId) => {
try {
const [skills, hooks] = await Promise.all([
api.getAgentSkills(projectId, agentId),
api.getAgentHooks(projectId, agentId),
]);
return [agentId, installsOf(skills.skills, hooks.hooks)] as const;
} catch {
return [agentId, NO_INSTALLS] as const;
}
}),
).then((entries) => {
// Merge instead of replacing the whole table: an Agent the user has
// already interacted with during the fetch keeps its interaction result
// (an optimistic state or an install/uninstall response is newer than
// this mount-time snapshot), so a late-arriving initial snapshot never
// regresses the UI.
if (!cancelled)
setInstalled((prev) => {
const next = new Map<string, AgentInstalls>(entries);
for (const [agentId, m] of prev) next.set(agentId, m);
return next;
});
});
return () => {
cancelled = true;
};
}, [projectId, agentIdsKey]);
/** Rewrite one Agent's snapshot entry in place (shared by optimistic updates, install responses and failure rollback). */
const setAgentInstalls = (agentId: string, installs: AgentInstalls) =>
setInstalled((prev) => new Map(prev).set(agentId, installs));
/**
* One Agent's snapshot entry with a plugin marked present (at the library's version) or
* absent — its skills and, when it ships one, its hook package, all at once.
*/
const withPlugin = (installs: AgentInstalls, plugin: PluginItem, on: boolean): AgentInstalls => {
const skills = new Map(installs.skills);
const hooks = new Map(installs.hooks);
for (const skill of plugin.skills) {
if (on) skills.set(skill.name, plugin.version);
else skills.delete(skill.name);
}
if (plugin.hooks.length > 0) {
if (on) hooks.set(plugin.name, plugin.version);
else hooks.delete(plugin.name);
}
return { skills, hooks };
};
/**
* Install / uninstall on one Agent (any member can do this): optimistic update, a
* confirmation toast on success, rollback on failure. Install is one request for
* the whole plugin; uninstall takes it apart — one DELETE per skill and one for the hook
* package — since the server offers no plugin-level delete, and a plugin's parts are what an
* Agent actually holds. The Agent list is re-read afterwards either way: the card's counts
* and its `pluginUpdates` moved, and both are read off that list.
*
* The answer is a {@link WriteOutcome} rather than a toast: uninstall is asked about first, so
* a refusal belongs in the card that asked (its retry button is there). An install is not asked
* about, so its refusal is kept here instead — the page outlives the cards — and drawn under
* the card of that plugin (install-refusal.ts); nothing is toasted either way.
*
* Only an install moves the snapshot before the answer. An uninstall waits for it: removing the
* current Agent's copy on the way out flips the card to "not installed" and carries it into the
* other section, which unmounts the very confirmation that asked — and with it a refusal's
* reason. The row reads "Installed" until the answer arrives, which is also what a refused one
* leaves it at.
*
* The optimistic move is also why the install's refusal cannot live in the card: it files the
* card into the other section on the way out and back on a refusal, so the instance that sent
* the request is unmounted either way. The sentence names the Agent for the same reason the
* Modal needs it to: the card's own button installs to the Agent the page is working with, while
* a refused row may have been aimed at another one.
*/
const toggleInstall = async (
agentId: string,
plugin: PluginItem,
on: boolean,
): Promise<WriteOutcome> => {
// Unreachable through the page (it renders nothing without a Project, and every caller is
// behind that gate). The generic sentence is what a write that never left would report.
if (!projectId) return { ok: false, reason: S.common.unknownError };
const prev = installed.get(agentId) ?? NO_INSTALLS;
if (on) {
// One attempt, one reason: the sentence of the attempt before belonged to it.
setInstallRefusal(null);
setAgentInstalls(agentId, withPlugin(prev, plugin, on));
}
const target = agents.find((a) => a.agentId === agentId);
const agentName = target ? agentDisplayName(target) : agentId;
try {
if (on) {
const res = await api.installAgentPlugins(projectId, agentId, [plugin.name]);
setAgentInstalls(agentId, installsOf(res.skills, res.hooks));
toastSuccess(
`${S.plugins.installedToast(plugin.name, agentName)}${S.agent.takesEffectSuffix}`,
);
} else {
// A 404 on a part means "was already not installed": the target state is already
// reached for that part, so it does not fail the uninstall (otherwise the row would be
// stuck at "Installed" whenever this page's snapshot is stale).
const gone = (e: unknown) => {
if (e instanceof ApiError && e.status === 404) return;
throw e;
};
await Promise.all([
...plugin.skills.map((skill) =>
api.removeAgentSkill(projectId, agentId, skill.name).catch(gone),
),
...(plugin.hooks.length > 0
? [api.uninstallAgentHook(projectId, agentId, plugin.name).catch(gone)]
: []),
]);
setAgentInstalls(agentId, withPlugin(prev, plugin, false));
toastSuccess(
`${S.plugins.uninstalledToast(plugin.name, agentName)}${S.agent.takesEffectSuffix}`,
);
}
} catch (e) {
setAgentInstalls(agentId, prev);
const reason = apiErrorText(e);
// An install has no confirmation to keep the reason in and no card instance that survives
// its own optimistic move: the page holds it, keyed by plugin, for the card that comes back.
if (on) {
setInstallRefusal({
plugin: plugin.name,
text: installRefused(plugin.name, agentName, reason),
});
}
return { ok: false, reason };
}
void reloadAgents();
return { ok: true };
};
/**
* Update reminder action: reinstall the current library copy on every outdated Agent
* (install-again-is-update semantics). One success toast for the whole batch; on partial
* failure the Agents that took it keep their calibrated state, and the first error comes back
* to the card that asked for the update — the ones that stayed behind are still marked behind
* on the cards and in the notice, and retrying sends the same set again.
*/
const updateOutdated = async (name: string, agentIds: string[]): Promise<WriteOutcome> => {
// Unreachable through the page (the card only draws an update with an Agent behind it).
if (!projectId || agentIds.length === 0) return { ok: true };
const results = await Promise.allSettled(
agentIds.map(async (agentId) => {
const res = await api.installAgentPlugins(projectId, agentId, [name]);
setAgentInstalls(agentId, installsOf(res.skills, res.hooks));
}),
);
// The outdated marks and the nav badge are both read off `AgentSummary.pluginUpdates`,
// which this page's install map does not feed: without reloading the Agent list the dot
// would survive the very update it led the user to. Runs after a partial failure too —
// some Agent moved.
void reloadAgents();
const failed = results.find((r): r is PromiseRejectedResult => r.status === "rejected");
if (failed) return { ok: false, reason: apiErrorText(failed.reason) };
toastSuccess(S.plugins.updatedToast(name, agentIds.length));
return { ok: true };
};
/**
* The notice's bulk action: reinstall the library copy of every outdated plugin, on every
* Agent behind on it — the per-card update, over the whole page. The per-card and per-Agent
* controls are untouched and remain the way to update just one.
*
* `Promise.allSettled` over one request per Agent, the shape the per-plugin update already
* uses, and the same reload afterwards: the gate reads `AgentSummary.pluginUpdates`, which
* this page's install map does not feed, so without it the dot would survive the very update
* it led the user to. What is new is that a partial failure NAMES the Agents that did not take
* it — on a control whose whole point is "all of them at once", a first-error toast leaves the
* user unable to tell which half they are looking at.
*
* Only a batch that landed everywhere dismisses the confirmation. Anything less keeps it open,
* with that same sentence drawn inside it (`bulkFailureText`) instead of in a toast that would
* leave after six seconds, and with `pendingBulk` scoped down to the Agents that are still
* behind (`remainingTargets`) so the retry button asks about exactly what the sentence named.
*/
const runBulkUpdate = async (plan: PluginUpdatePlan) => {
if (!projectId || plan.perAgent.length === 0) return;
setBulkRunning(true);
const labels = plan.perAgent.map(({ agentId }) => {
const agent = agents.find((a) => a.agentId === agentId);
return agent ? agentDisplayName(agent) : agentId;
});
const results = await Promise.allSettled(
plan.perAgent.map(async ({ agentId, names }) => {
const res = await api.installAgentPlugins(projectId, agentId, names);
setAgentInstalls(agentId, installsOf(res.skills, res.hooks));
}),
);
const outcome = bulkOutcome(labels, results);
if (outcome.allOk) toastSuccess(S.todo.bulkDone(outcome.ok));
else {
const rest = remainingTargets(plan.perAgent, results);
setBulkRefusal(
bulkFailureText(
outcome,
apiErrorText(firstFailure(results)),
S.todo.bulkPartial,
S.todo.listSeparator,
),
);
setPendingBulk({ perAgent: rest.targets, plugins: rest.names });
}
// Runs after a partial failure too — some Agent moved, and the gate has to see it. Guarded,
// because `reloadAgents` rejects on a failed list read and the busy flag disables every
// control here, the dialog's Cancel included: a reload that failed after the writes landed
// would otherwise leave the page frozen with nothing saying why.
try {
await reloadAgents();
} catch (e) {
toastError(apiErrorText(e));
} finally {
setBulkRunning(false);
// Nothing but a clean batch closes the question: a refusal leaves it (and its retry
// button) where the user still is. The reload failing afterwards closes it too — every
// write landed, and the page says so in a toast; the stale dot is the reload's problem.
if (outcome.allOk) setPendingBulk(null);
}
};
/**
* Quick start: pre-selects one of the plugin's skills in the draft cache (the `skills`
* field, used by ChatInput as its initial selection on mount), pre-fills the invocation text
* per UI language (overwriting any existing draft body — quick start's intent is
* unambiguous, and leftover draft text would only be noise here), and opens the draft on the
* currently selected Agent — the route state carries its agentId explicitly. handoffAgentId
* must be cleared: a leftover handoff target would forward the whole skill invocation to a
* different Agent. The button is gated on the current Agent having the skill (see
* PluginCard.quickStartSkill), so agentId is present here.
*/
const quickInvoke = (skillName: string) => {
const agentId = currentAgent?.agentId;
if (!agentId) return;
if (userId && projectId) {
// Typed-but-unsent draft text becomes a parked draft conversation instead of being
// clobbered by the canned invocation body, and the Workspace and approval mode start on
// the Project's new-chat defaults (new-chat.ts).
prepareNewChatDraft(userId, projectId);
const key = draftKey(userId, projectId);
saveDraft(key, {
...loadDraft(key),
agentId,
text: S.skills.quickInvokeText(skillName),
skills: [skillName],
handoffAgentId: undefined,
});
}
setCurrentAgentId(agentId);
navigate(`/chat/${DRAFT_SESSION_ID}`, { state: { agentId } });
};
/**
* "Export" on a user plugin's card: the shared archive download (archive-download.ts, the same
* one the Skills and Hooks tabs export with). Open to any member — GET
* /api/plugins/:plugin/archive is a plain read of a directory everyone can already browse —
* and the way to keep a copy of a plugin an admin may delete off the machine.
*
* The refusal comes back as a {@link WriteOutcome} rather than a toast: the card that asked is
* still on screen with the button that retries it, and a toast dismisses itself after six
* seconds over the list (7.19's rule; plugin-export-refusal.ts draws the sentence).
*/
const exportPlugin = async (name: string): Promise<WriteOutcome> => {
try {
await downloadArchive(api.pluginArchiveUrl(name), name);
return { ok: true };
} catch (e) {
return { ok: false, reason: pluginExportRefused(name, e) };
}
};
/**
* Delete one user plugin (admin-only server-side). The directory line is re-read afterwards,
* since the on-disk directory is what it reports.
*
* The card leaves the listing only once the directory is gone — no longer optimistically on the
* way out: it is the card that asked for the delete, and taking it off the page as the request
* left unmounts that confirmation, so a refusal had nothing left to put its reason in. The
* confirm button reads busy meanwhile, which is what the wait looks like.
*
* The refusal comes back as a {@link WriteOutcome} instead of a toast for the same reason: the
* card that asked still has the button that retries it.
*/
const removePlugin = async (plugin: PluginItem): Promise<WriteOutcome> => {
try {
await api.deletePlugin(plugin.name);
} catch (e) {
return { ok: false, reason: pluginImportErrorText(e) };
}
setGroups(
(current) =>
current
?.map((group) => ({
...group,
plugins: group.plugins.filter((p) => p.name !== plugin.name),
}))
// A category the deleted plugin was the only member of goes with it: the grouping is
// the server's, and an empty section would stand under the title until the next load.
.filter((group) => group.plugins.length > 0) ?? current,
);
toastSuccess(S.plugins.deletedToast(plugin.name));
await reloadDirectory();
return { ok: true };
};
/**
* "Add to the library" on a published plugin's row: exactly the import the header's dialog
* performs — POST /api/plugins/download, which the server reads as an npm package name — so a
* plugin that is on the shelf because it was published needs no typed address. An admin's
* action, like every other write into the plugin directory, and the row keeps the refresh:
* once it lands, the library listing carries the new card and this row is gone.
*
* A 409 (the name is taken) opens the same overwrite question the dialog asks for its own
* imports rather than a toast: it is a question, and the answer resends the request with
* `overwrite`.
*
* Any other refusal is drawn IN this row (library-add-refusal.ts): the fetch wrote nothing, so
* the row is still here with the same button, and a notification would take the reason away
* after six seconds while the retry stayed on screen. One attempt, one reason: starting the
* next one clears it.
*/
const addPublishedToLibrary = async (specifier: string, overwrite = false) => {
setPublishing(specifier);
setLibraryRefusal(null);
try {
const res = await api.importPluginFromUrl({
url: specifier,
...(overwrite ? { overwrite: true } : {}),
});
setOverwriteImport(null);
toastSuccess(S.plugins.importDoneToast(res.plugin.name));
await reloadLibrary();
} catch (e) {
if (e instanceof ApiError && e.status === 409 && e.code === "plugin_exists") {
setOverwriteImport({
specifier,
name: pluginNameFromError(e, specifier.split("/").pop() ?? specifier),
});
} else {
setOverwriteImport(null);
setLibraryRefusal({ specifier, reason: libraryAddRefused(e) });
}
} finally {
setPublishing(null);
}
};
// The library's rows, divided by what the Agent the page is working with holds (the value
// each card's tag shows), then the module rows the Project does not list yet. The two lists
// below are exactly these: nothing else decides which section a row lands in.
const libraryRows = installedPluginRows(groups ?? [], locale, deployment, index ?? [], view);
const offeredRows = availablePluginRows(deployment, index ?? [], view);
// What the project published and this deployment does not carry: rows that only exist on the
// shelf. They go through the same division so a published plugin is filed with what is offered.
const publishedRows = publishedPluginRows(
index ?? [],
(view.remote ?? deployment)?.shipped ?? [],
(groups ?? []).flatMap((group) => group.plugins.map((plugin) => plugin.name)),
);
const divided = splitPluginRows(
[...libraryRows, ...publishedRows],
agents,
installed,
currentAgent?.agentId ?? null,
);
const allInstalled = divided.installed;
const allAvailable = [...divided.available, ...offeredRows];
const facets = pluginFacets([...allInstalled, ...allAvailable]);
const picked = { categories: pickedCategories, kinds: pickedKinds, states: pickedStates };
const filtering =
query.trim() !== "" ||
pickedCategories.size > 0 ||
pickedKinds.size > 0 ||
pickedStates.size > 0;
const keep = (row: PluginRow) => rowMatches(row, query, picked);
const installedRows = allInstalled.filter(keep);
const availableRows = allAvailable.filter(keep);
const toggle = <T,>(set: ReadonlySet<T>, value: T): Set<T> => {
const next = new Set(set);
if (next.has(value)) next.delete(value);
else next.add(value);
return next;
};
/**
* The card a library row draws in EITHER section: it carries its own shelf state, so the one
* in the available list says "not installed" and offers that Agent's install button by
* itself. Written once because the two sections must not drift apart in what a row can do.
*/
const libraryCard = (row: Extract<PluginRow, { kind: "library" }>) => (
<PluginCard
key={`library:${row.plugin.name}`}
plugin={row.plugin}
category={row.category}
installed={installed}
marketSpecifier={marketEntryFor(row.plugin, index ?? [])?.name ?? null}
canDelete={isAdmin}
installRefusal={installRefusalFor(installRefusal, row.plugin.name)}
onQuickInvoke={quickInvoke}
onToggleInstall={toggleInstall}
onUpdateOutdated={updateOutdated}
onExport={exportPlugin}
onDelete={removePlugin}
/>
);
/**
* The row a module or published plugin draws, whichever list it is filed under. A module row's
* verbs depend on that list — installed offers Remove, available offers Install — while a
* published one only ever offers the first step, because it is nowhere until it is fetched.
*/
const shelfRow = (
row: Extract<PluginRow, { kind: "module" | "published" }>,
install: boolean,
) => {
if (row.kind === "published") {
return (
<ModuleRow
key={`published:${row.specifier}`}
specifier={row.specifier}
entry={row.entry}
state="none"
shipped={false}
installLabel={S.plugins.addToLibrary}
refusal={libraryRefusal?.specifier === row.specifier ? libraryRefusal.reason : undefined}
busy={publishing === row.specifier}
blocked={publishing !== null && publishing !== row.specifier}
onInstall={isAdmin ? () => void addPublishedToLibrary(row.specifier) : null}
onRemove={null}
/>
);
}
return (
<ModuleRow
key={`module:${row.specifier}`}
specifier={row.specifier}
entry={row.entry}
state={row.state}
error={row.error}
shipped={row.shipped}
onlyOn={row.onlyOn}
removeBlocked={row.removeBlocked}
busy={pendingSpecifier === row.specifier}
blocked={pendingSpecifier !== null && pendingSpecifier !== row.specifier}
onInstall={install && isAdmin ? () => askApply(row.specifier, true) : null}
onRemove={install || !isAdmin ? null : () => askApply(row.specifier, false)}
/>
);
};
// The scrollbar gutter stays reserved: a filter that shortens the page below the viewport
// would otherwise take the scrollbar with it and shift everything sideways at the click.
return (
<PageFrame className="[scrollbar-gutter:stable]">
{/* The options loaded plugins declare live on the Settings dialog's Plugins page, an
admin's page; the header's gear opens the dialog there rather than sending anyone
through the user menu to find it. */}
<PageHeader
title={S.plugins.pageTitle}
info={S.plugins.pageDesc}
actions={
isAdmin ? (
<>
{/* Importing into the plugin directory, in the title row beside the gear: a
server-level resource, so both actions are the admin's and the routes answer
403 without the right. Rendered only for an admin — a button that always
refuses is worse than no button — and disabled while either runs, since one
import at a time is what the overwrite confirmation's slot can carry. */}
<PluginImportActions onImported={reloadLibrary} />
{/* Which machine's plugins the rows show, and which table an install or a
removal edits: the shared one, or that machine's own. */}
{otherMachines.length > 0 && (
<MachinePicker
aria-label={S.plugins.viewMachine}
choices={machineChoices}
value={viewMachine ?? ALL_MACHINES_CHOICE}
onChange={(v) => setViewMachine(v === ALL_MACHINES_CHOICE ? null : v)}
/>
)}
<Button
size="sm"
className="h-8 w-8 shrink-0 justify-center p-0"
aria-label={S.plugins.openSettings}
title={S.plugins.openSettings}
onClick={() => setSettingsOpen(true)}
>
<GlyphIcon d={ICONS.gear} size={ICON_SIZE.iconButton} />
</Button>
</>
) : undefined
}
>
{/* Where an import lands and what a delete removes from: the server's own plugin
directory, named under the title rather than left for the reader to find in a
settings page. A read, so every member sees it. */}
<PluginDirectoryLine directory={directory} failed={directoryError !== null} />
{/* Last stop on the plugins trail: what the sidebar's dot was pointing at, the control
that takes all of it in one press, and the way to clear it for someone who has looked
and decided to stay on the installed copies. A plugin is never NEW here — one nobody
has installed is not waiting for anyone — so the line states the upgradable count
alone rather than padding it with a zero. The per-card update buttons below remain
the way to take just one. */}
{todo && (
<TodoNotice
text={S.todo.changesUpgradable(noticeCounts(todo).updated)}
actionLabel={S.todo.updateNow}
busy={bulkRunning}
onAction={() => {
setPendingBulk(pluginUpdatePlan(agents));
// Opening the batch afresh: a reason from the last attempt belongs to that attempt.
setBulkRefusal(null);
}}
dismissLabel={S.todo.dismiss}
onDismiss={() => dismissTodo(projectId, "plugins", todo.signature)}
/>
)}
{remote !== null && "error" in remote && remote.machineId === viewMachine && (
<Notice tone="attention" className="mt-4">
{S.plugins.machineUnreadable(nameOf(remote.machineId), remote.error)}
</Notice>
)}
{deployment !== null && viewIncludesHere && deployment.restartPending && (
<Notice tone="attention" className="mt-4">
{S.plugins.restartPending}
</Notice>
)}
</PageHeader>
<SettingsDialog
open={settingsOpen}
onClose={() => setSettingsOpen(false)}
section="plugins"
/>
{/* The header block ends in its own bottom margin, so the content's top margin tops it
up to the page's usual gap under the header. */}
{error ? (
<div className="mt-2 flex items-center gap-3">
<p className={`text-sm ${toneInk.danger}`}>{error}</p>
<Button size="sm" onClick={() => window.location.reload()}>
{S.common.retry}
</Button>
</div>
) : groups === null ? (
<div className="mt-2 grid grid-cols-1 gap-2">
{Array.from({ length: 4 }, (_, i) => (
<SkeletonCard key={i} className="p-4">
<Skeleton className="h-4 w-32" />
<Skeleton className="mt-2 h-4 w-3/4" />
<Skeleton className="mt-3 h-6 w-36" />
</SkeletonCard>
))}
</div>
) : (
<div className="mt-2 md:grid md:grid-cols-[minmax(0,1fr)_12rem] md:gap-4">
<div className="min-w-0 space-y-3">
<SearchInput
size="sm"
value={query}
placeholder={S.plugins.searchPlaceholder}
aria-label={S.plugins.searchPlaceholder}
onChange={setQuery}
/>
{/* ONE list, one plugin per row, every kind in the same card: what this Project is
running first — the library's plugins the working Agent holds, and the module
plugins this Project asks for — then what could be: the library plugins no
Agent copy stands behind yet (installable to the working Agent) and the module
plugins the registry offers. A plugin's category is a tag on its row, not a
group around it. */}
<PluginList
title={S.plugins.installedSection(installedRows.length)}
open={installedOpen || filtering}
onToggle={() => setInstalledOpen((v) => !v)}
>
{installedRows.map((row) =>
row.kind === "library" ? libraryCard(row) : shelfRow(row, false),
)}
</PluginList>
{availableRows.length > 0 && (
<PluginList
title={S.plugins.availableSection(availableRows.length)}
open={availableOpen || filtering}
onToggle={() => setAvailableOpen((v) => !v)}
>
{availableRows.map((row) =>
row.kind === "library" ? libraryCard(row) : shelfRow(row, true),
)}
</PluginList>
)}
{filtering && installedRows.length === 0 && availableRows.length === 0 && (
<p className="px-1 text-sm text-gray-400 dark:text-gray-500">{S.plugins.noMatch}</p>
)}
</div>
{/* The filter column: the categories on the page, then two attributes with a
handful of values each (what a plugin carries, what it is here). Free-form
keywords are not a facet — they feed the search box. A pick narrows both lists,
and the lists unfold while anything is picked or typed. */}
<PluginFilters
facets={facets}
picked={picked}
onCategory={(c) => setPickedCategories((prev) => toggle(prev, c))}
onKind={(k) => setPickedKinds((prev) => toggle(prev, k))}
onState={(st) => setPickedStates((prev) => toggle(prev, st))}
onClear={() => {
setPickedCategories(new Set());
setPickedKinds(new Set());
setPickedStates(new Set());
setQuery("");
}}
/>
</div>
)}
{/* A module plugin change: what it costs is said before it runs. */}
{pendingApply !== null && (
<ConfirmModal
open
title={
pendingApply.install
? S.plugins.applyConfirmInstall(pendingApply.specifier)
: S.plugins.applyConfirmRemove(pendingApply.specifier)
}
tone="primary"
confirmLabel={pendingApply.install ? S.plugins.install : S.plugins.uninstall}
cancelLabel={S.common.cancel}
busy={pendingSpecifier !== null}
onClose={() => setPendingApply(null)}
onConfirm={() => void runDeploymentInstall(pendingApply.specifier, pendingApply.install)}
refusal={applyRefusal === null ? undefined : S.common.refused(applyRefusal)}
>
<p>{S.plugins.applyConfirmBody}</p>
</ConfirmModal>
)}
{/* Bulk update confirmation. Same warning as the per-plugin confirm — an update is an
overwriting reinstall — and the same primary (overwrite) tone, with the list naming
every plugin the batch would rewrite. Confirm-first is the point of the button: it
overwrites many installs in one press, and a single one already asks. A batch that did
not land everywhere keeps this card and reports inside it: the retry is the same button,
and the list has already been scoped to the Agents still behind. */}
{pendingBulk !== null && (
<ConfirmModal
open
title={S.todo.pluginsConfirmTitle(pendingBulk.plugins.length)}
tone="primary"
confirmLabel={S.skills.updateAction}
cancelLabel={S.common.cancel}
busy={bulkRunning}
onClose={() => {
setPendingBulk(null);
setBulkRefusal(null);
}}
onConfirm={() => void runBulkUpdate(pendingBulk)}
refusal={bulkRefusal === null ? undefined : bulkRefusal}
>
<div className="space-y-3">
<p className="text-sm text-gray-600 dark:text-gray-300">{S.todo.pluginsConfirmBody}</p>
<p className="text-xs text-gray-500 dark:text-gray-400">{S.todo.willTouch}</p>
<ul className="max-h-60 divide-y divide-gray-100 overflow-y-auto rounded-md border border-gray-200 dark:divide-gray-800 dark:border-gray-800">
{pendingBulk.plugins.map((name) => (
<li key={name} className="px-3 py-1.5 font-mono text-xs">
{name}
</li>
))}
</ul>
</div>
</ConfirmModal>
)}
{/* Fetching a published plugin into the library, when its name is already taken: the row's
own confirm, and the same question the header's import dialog asks — one name, one
plugin, and the answer re-sends the request with overwrite, which is what replaces the
existing copy's files. */}
{overwriteImport !== null && (
<ConfirmModal
open
title={S.plugins.importOverwriteTitle}
tone="primary"
confirmLabel={S.plugins.importOverwriteAction}
cancelLabel={S.common.cancel}
busy={publishing !== null}
onClose={() => setOverwriteImport(null)}
onConfirm={() => void addPublishedToLibrary(overwriteImport.specifier, true)}
>
<p className="text-sm text-gray-600 dark:text-gray-300">
{S.plugins.importOverwriteBody(overwriteImport.name)}
</p>
</ConfirmModal>
)}
</PageFrame>
);
}
/** One row of the page: a library plugin (skills / hooks, installed per Agent), a module plugin (listed per Project), or a published one (on the shelf, not here yet). */
type PluginRow =
| {
kind: "library";
plugin: PluginItem;
category: string;
/**
* What the shelf says for the Agent the page is working with — the value the card's own
* state tag shows. Set by {@link splitPluginRows} when the page divides the lists, and read
* by `rowFacets`, so the state filter counts a row under the state the reader sees on it.
*/
market?: MarketState;
}
| ModulePluginRow
| PublishedPluginRow;
/**
* A plugin the project has published but this deployment does not carry: an entry on the shelf
* whose package is neither part of this build nor in the library. The row exists so the plugin is
* visible where plugins are browsed, and its verb is the first step of installing it — fetch it
* into the library (the npm import an operator would otherwise have to type), after which it
* behaves like any other plugin.
*/
interface PublishedPluginRow {
kind: "published";
specifier: string;
entry: PluginIndexEntry;
}
interface ModulePluginRow {
kind: "module";
specifier: string;
entry: PluginIndexEntry | undefined;
state: ModuleState;
/** Why the process could not load it, when `state` is `failed`. */
error?: string;
shipped: boolean;
/** The machines it is listed for, by name, when the shared table does not list it. */
onlyOn?: string[];
/** Why Remove is unavailable in this view, when it is. */
removeBlocked?: string;
}
/**
* What a listed module plugin is on the machine in view: running; waiting for a runtime that
* can re-assemble (`pending`); FAILED — the process tried and could not load it, for the
* reason the server sends, which no restart would change; `elsewhere` — the all-machines view
* of a plugin listed only for other machines, which this server neither installs nor loads;
* or `unsynced` — listed for a machine that has not reported running it.
*/
type ModuleState = "none" | "pending" | "active" | "failed" | "elsewhere" | "unsynced";
/**
* Which machine the page shows: `machineId` null for all machines (the shared table), or a
* machine's own id. `remote` is that machine's own answer when it is not this server — what
* it actually runs — and null when it is this server or could not be read.
*/
export interface PluginView {
machineId: string | null;
remote: InstalledPluginsResponse | null;
/** A machine's display name, by its own id. */
nameOf: (machineId: string) => string;
}
/** The picker's value for all machines: a machine id is never this short. */
const ALL_MACHINES_CHOICE = "*";
const ALL_MACHINES: PluginView = { machineId: null, remote: null, nameOf: (id) => id };
/** Whether a listed plugin belongs in the view: shared, or listed for the machine in view. */
function inView(listed: InstalledPluginsResponse["plugins"][number], view: PluginView): boolean {
return (
view.machineId === null ||
listed.everywhere !== false ||
(listed.machines ?? []).includes(view.machineId)
);
}
/** A listed plugin's state as the machine in view has it. */
function stateIn(
listed: InstalledPluginsResponse["plugins"][number],
view: PluginView,
selfId: string | undefined,
): { state: ModuleState; error?: string } {
const local = (row: InstalledPluginsResponse["plugins"][number]) =>
row.active
? { state: "active" as const }
: row.error !== undefined
? { state: "failed" as const, error: row.error }
: { state: "pending" as const };
if (view.machineId === null)
return listed.here === false ? { state: "elsewhere" } : local(listed);
if (view.machineId === selfId) return local(listed);
const there = view.remote?.plugins.find((p) => p.specifier === listed.specifier);
return there === undefined ? { state: "unsynced" } : local(there);
}
/**
* What is installed, in one list: the library's plugins — they ship with the build, so
* every Agent may use them, and the category their group gave them rides along as a tag —
* followed by the module plugins this Project asks for, each with its registry entry
* (description, version, categories) when the registry has one.
*/
export function installedPluginRows(
groups: readonly PluginGroupItem[],
locale: Parameters<typeof localizedText>[0],
deployment: InstalledPluginsResponse | null,
index: readonly PluginIndexEntry[],
view: PluginView = ALL_MACHINES,
): PluginRow[] {
const rows: PluginRow[] = [];
for (const group of groups) {
const category = localizedText(locale, group.title, group.titleZh);
for (const plugin of group.plugins) rows.push({ kind: "library", plugin, category });
}
for (const listed of deployment?.plugins ?? []) {
if (!inView(listed, view)) continue;
const shared = listed.everywhere !== false;
const ownTable = view.machineId !== null && (listed.machines ?? []).includes(view.machineId);
rows.push({
kind: "module",
specifier: listed.specifier,
entry: index.find((e) => e.name === listed.specifier),
...stateIn(listed, view, deployment?.machineId),
shipped:
listed.builtin || (view.remote ?? deployment)?.shipped.includes(listed.specifier) === true,
...(shared ? {} : { onlyOn: (listed.machines ?? []).map(view.nameOf) }),
// A machine's view edits that machine's own table; a shared entry is not in it.
...(view.machineId !== null && shared && !ownTable
? { removeBlocked: S.plugins.sharedCannotRemove }
: {}),
});
}
return rows;
}
/**
* The library's rows divided the way the two section heads claim, for the Agent the page is
* working with: a plugin that Agent holds goes with the installed ones, one it does not goes
* with what can be installed there. The decision is `marketState` — the very value the card's
* state tag draws — so a card the reader sees tagged "not installed" can never be filed under
* "installed plugins". (Before this, every library plugin was listed as installed whether or
* not anything had it, and a card inside that list said "not installed": the two disagreed
* about the same plugin on the same screen.)
*
* Module rows are the Project's own list rather than per-Agent state, and stay where they are:
* the installed section, where the Project's plugin table has always been shown.
*
* With no Agent selected there is nothing to compare against — and the cards draw no state tag
* either — so the library rows keep their place rather than being called missing from an Agent
* nobody named.
*/
export function splitPluginRows(
rows: readonly PluginRow[],
agents: ReadonlyArray<Pick<AgentSummary, "agentId" | "pluginUpdates">>,
installs: InstalledMap,
currentAgentId: string | null,
): { installed: PluginRow[]; available: PluginRow[] } {
const installed: PluginRow[] = [];
const available: PluginRow[] = [];
for (const row of rows) {
// A published plugin is nowhere yet — not on an Agent, not even in the library — so it
// belongs with what could be installed whatever Agent the page is working with.
if (row.kind === "published") {
available.push(row);
continue;
}
if (row.kind === "module" || currentAgentId === null) {
installed.push(row);
continue;
}
const outdated = outdatedAgentIds(agents, row.plugin.name).includes(currentAgentId);
const market = marketState(row.plugin, installs.get(currentAgentId), outdated);
if (market === "available") available.push({ ...row, market });
else installed.push({ ...row, market });
}
return { installed, available };
}
/**
* What could be asked for: what the build ships and this Project does not list yet. The
* registry is consulted for the entry (description, version, categories) and the build's own
* list for the row: the shelf carries an entry per plugin package the build ships — the
* library's skills/hooks packages among them, which install to an AGENT and are never a
* Project's to ask for — and the server refuses the ones it does not ship, so offering those
* here would be a row whose Install answers `plugin_not_shipped`.
*/
export function availablePluginRows(
deployment: InstalledPluginsResponse | null,
index: readonly PluginIndexEntry[],
view: PluginView = ALL_MACHINES,
): ModulePluginRow[] {
// What the machine in view does not run yet: in the all-machines view, anything the shared
// table lacks — a plugin listed for some machines is still offered for all of them.
const listed = new Set(
(deployment?.plugins ?? [])
.filter((p) => (view.machineId === null ? p.everywhere !== false : inView(p, view)))
.map((p) => p.specifier),
);
// What the machine in view ships, when it answered; this server's otherwise.
const shippedList = (view.remote ?? deployment)?.shipped ?? [];
const seen = new Set<string>();
const rows: ModulePluginRow[] = [];
for (const entry of index) {
if (listed.has(entry.name) || seen.has(entry.name)) continue;
// Marked seen before the build's list is consulted: an entry this deployment does not ship
// has no row at all, rather than the entry-less one the loop below would add for its name.
seen.add(entry.name);
if (!shippedList.includes(entry.name)) continue;
rows.push({
kind: "module",
specifier: entry.name,
entry,
state: "none",
shipped: true,
});
}
for (const name of shippedList) {
if (listed.has(name) || seen.has(name)) continue;
seen.add(name);
rows.push({ kind: "module", specifier: name, entry: undefined, state: "none", shipped: true });
}
return rows;
}
/**
* The plugins the project has published that this deployment does not carry yet: shelf entries
* whose package is neither part of this build nor in the library. What is left is the published
* side of the market — a plugin that reached npm without a release — and each becomes a row whose
* verb fetches it into the library.
*
* An entry the build ships is left to `availablePluginRows` (a module row for a Project to ask
* for), and one the library already holds is left to the card that library row draws: those are
* the same plugin seen from where it can actually be installed, and a second row for it would
* claim a state the other row contradicts.
*/
export function publishedPluginRows(
index: readonly PluginIndexEntry[],
shipped: readonly string[],
library: readonly string[],
): PublishedPluginRow[] {
const known = new Set([...shipped, ...library.map((name) => name.split("/").pop() ?? name)]);
const rows: PublishedPluginRow[] = [];
for (const entry of index) {
if (known.has(entry.name) || known.has(entry.name.split("/").pop() ?? entry.name)) continue;
rows.push({ kind: "published", specifier: entry.name, entry });
}
return rows;
}
/**
* The market entry that describes a library plugin, when the registry has one. The two lists
* name the same package differently: the library by the directory its package was read from
* (`csu-mail`), the market by the specifier a Project's list would take
* (`@adelie/csu-mail`) — and a plugin package's version is its own `plugin.json`'s in both,
* so a scoped entry of that name carrying the card's version is this plugin's package. A user
* plugin has none: it is no package of the build's, and nothing on the shelf describes it.
*/
export function marketEntryFor(
plugin: Pick<PluginItem, "name" | "version">,
index: readonly PluginIndexEntry[],
): PluginIndexEntry | undefined {
return (
index.find((entry) => entry.name === plugin.name) ??
index.find(
(entry) => entry.name.endsWith(`/${plugin.name}`) && entry.version === plugin.version,
)
);
}
/**
* A titled list of rows: a collapsible section whose head strip toggles the fold, as on the
* model page, with one column of cards under it.
*/
function PluginList({
title,
open,
onToggle,
children,
}: {
title: string;
open: boolean;
onToggle: () => void;
children: React.ReactNode;
}) {
return (
<CollapsibleSection title={title} open={open} onOpenChange={onToggle}>
<div
className={`grid grid-cols-1 gap-2 p-2 transition-opacity duration-200 ${open ? "opacity-100" : "opacity-0"}`}
>
{children}
</div>
</CollapsibleSection>
);
}
/** What a plugin carries: the payload kinds a row is filtered by. */
export type PluginKind = "skills" | "hooks" | "modules";
/** What a plugin is for this deployment. */
export type PluginState = "installed" | "available" | "running" | "restart" | "failed";
export const PLUGIN_KINDS: readonly PluginKind[] = ["skills", "hooks", "modules"];
export const PLUGIN_STATES: readonly PluginState[] = [
"installed",
"available",
"running",
"restart",
"failed",
];
/**
* A library row's value on the state filter, off the shelf state the card's tag shows
* (`row.market`, set by splitPluginRows): the filter has no "updatable" option — an outdated
* copy IS installed — and a row the page never classified (no Agent selected, so no tag is
* drawn) reads as installed, which is how this list has always been filed.
*/
function libraryState(row: { market?: MarketState }): PluginState {
return row.market === "available" ? "available" : "installed";
}
/** The category a row belongs to, what it carries and what it is here — the three facets the filter column offers. */
export function rowFacets(row: PluginRow): {
categories: string[];
kinds: PluginKind[];
states: PluginState[];
} {
if (row.kind === "library") {
const kinds: PluginKind[] = [];
if (row.plugin.skills.length > 0) kinds.push("skills");
if (row.plugin.hooks.length > 0) kinds.push("hooks");
// The state the card's tag shows, not a blanket "installed": a library plugin the working
// Agent does not hold is offered, whichever section the page currently files it under.
return { categories: [row.category], kinds, states: [libraryState(row)] };
}
// A published plugin is not here, so nothing on this machine says what it carries: its kinds
// stay empty rather than being guessed from a search result. It is offered, which is one state.
if (row.kind === "published") {
return { categories: row.entry.categories ?? [], kinds: [], states: ["available"] };
}
const states: PluginState[] =
row.state === "active"
? ["installed", "running"]
: row.state === "pending"
? ["installed", "restart"]
: row.state === "failed"
? ["installed", "failed"]
: row.state === "none"
? ["available"]
: ["installed"];
return { categories: row.entry?.categories ?? [], kinds: ["modules"], states };
}
export interface PluginFacets {
/** Every category on the page, each once, in first-seen order, with how many rows carry it. */
categories: { value: string; count: number }[];
kinds: { value: PluginKind; count: number }[];
states: { value: PluginState; count: number }[];
}
export interface PickedFacets {
categories: ReadonlySet<string>;
kinds: ReadonlySet<PluginKind>;
states: ReadonlySet<PluginState>;
}
export function pluginFacets(rows: readonly PluginRow[]): PluginFacets {
const categories = new Map<string, number>();
const kinds = new Map<PluginKind, number>(PLUGIN_KINDS.map((k) => [k, 0]));
const states = new Map<PluginState, number>(PLUGIN_STATES.map((st) => [st, 0]));
for (const row of rows) {
const f = rowFacets(row);
for (const c of f.categories) categories.set(c, (categories.get(c) ?? 0) + 1);
for (const k of f.kinds) kinds.set(k, (kinds.get(k) ?? 0) + 1);
for (const st of f.states) states.set(st, (states.get(st) ?? 0) + 1);
}
const list = <T,>(m: Map<T, number>) =>
[...m].filter(([, count]) => count > 0).map(([value, count]) => ({ value, count }));
return { categories: list(categories), kinds: list(kinds), states: list(states) };
}
/**
* Whether a row survives the search box and the filter column: text anywhere in its name,
* description or keywords; within a facet any picked value matches, across facets all must.
*/
export function rowMatches(row: PluginRow, query: string, picked: PickedFacets): boolean {
const f = rowFacets(row);
if (picked.categories.size > 0 && !f.categories.some((c) => picked.categories.has(c)))
return false;
if (picked.kinds.size > 0 && !f.kinds.some((k) => picked.kinds.has(k))) return false;
if (picked.states.size > 0 && !f.states.some((st) => picked.states.has(st))) return false;
const q = query.trim().toLowerCase();
if (q === "") return true;
const text =
row.kind === "library"
? `${row.plugin.name} ${row.plugin.description} ${row.plugin.descriptionZh ?? ""} ${row.plugin.shortDescription ?? ""} ${row.plugin.shortDescriptionZh ?? ""}`
: `${row.specifier} ${row.entry?.description ?? ""} ${(row.entry?.keywords ?? []).join(" ")}`;
return text.toLowerCase().includes(q);
}
/**
* The filter column: three groups, each a vertical list of options with its count — the
* marketplace sidebar shape. A picked option is filled and carries a check; the heading
* offers Clear while anything is picked.
*/
function PluginFilters({
facets,
picked,
onCategory,
onKind,
onState,
onClear,
}: {
facets: PluginFacets;
picked: PickedFacets;
onCategory: (category: string) => void;
onKind: (kind: PluginKind) => void;
onState: (state: PluginState) => void;
onClear: () => void;
}) {
const option = (key: string, label: string, count: number, on: boolean, onClick: () => void) => (
<button
key={key}
type="button"
aria-pressed={on}
onClick={onClick}
className={`flex w-full items-center gap-2 rounded-md px-2 py-1 text-left text-sm transition-colors duration-150 ${
on
? "bg-gray-200/70 font-medium text-gray-900 dark:bg-gray-700/70 dark:text-gray-100"
: "text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800/70"
}`}
>
<span
className={`flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-sm border ${
on
? "border-gray-800 bg-gray-800 text-white dark:border-gray-100 dark:bg-gray-100 dark:text-gray-900"
: "border-gray-300 dark:border-gray-600"
}`}
>
{on && <GlyphIcon d="M20 6 9 17l-5-5" size={10} />}
</span>
<span className="min-w-0 flex-1 truncate">{label}</span>
<span className="shrink-0 font-mono text-xs tabular-nums text-gray-400 dark:text-gray-500">
{count}
</span>
</button>
);
const group = (title: string, children: React.ReactNode) => (
<div>
<Text variant="eyebrow" as="div" className="mb-1 px-2">
{title}
</Text>
<div className="space-y-1">{children}</div>
</div>
);
const active = picked.categories.size > 0 || picked.kinds.size > 0 || picked.states.size > 0;
return (
<aside className="mt-3 space-y-4 md:mt-0 md:sticky md:top-0 md:self-start">
{/* Always in the flow, hidden until a pick is made: appearing and vanishing would shift
every option below by a line at the moment of the click. */}
<button
type="button"
onClick={onClear}
tabIndex={active ? 0 : -1}
aria-hidden={!active}
className={`px-2 text-xs text-gray-400 underline-offset-2 hover:underline dark:text-gray-500 ${active ? "" : "invisible"}`}
>
{S.plugins.filterClear}
</button>
{group(
S.plugins.filterCategories,
facets.categories.map(({ value, count }) =>
option(value, value, count, picked.categories.has(value), () => onCategory(value)),
),
)}
{group(
S.plugins.filterKind,
facets.kinds.map(({ value, count }) =>
option(value, S.plugins.kindLabel[value], count, picked.kinds.has(value), () =>
onKind(value),
),
),
)}
{group(
S.plugins.filterState,
facets.states.map(({ value, count }) =>
option(value, S.plugins.stateLabel[value], count, picked.states.has(value), () =>
onState(value),
),
),
)}
</aside>
);
}
/** One tag on a row's tag line: a category, "built in", a license, a keyword. */
function Tag({
children,
mono,
title,
}: {
children: React.ReactNode;
mono?: boolean;
title?: string;
}) {
return (
<span
data-tooltip={title}
className={`rounded-full bg-gray-100 px-2 py-0.5 dark:bg-gray-800 ${mono ? "font-mono text-gray-500 dark:text-gray-400" : "font-medium text-gray-600 dark:text-gray-300"}`}
>
{children}
</span>
);
}
/**
* The user plugin directory line under the title: the absolute path in monospace with the
* shared copy button, and how many user plugins are inside it — the answer to where an import
* landed, which is also the directory a delete removes from.
*
* Deliberately quiet (one line of small gray text) and worded rather than counted at zero:
* "0 user plugins" reads like a fault where the directory is simply still empty. Nothing is
* rendered until the read answers, so the list below never jumps for a line that is not there
* yet; a failed read states itself in the same line instead of hiding, since silence under the
* title would leave the count missing for no visible reason.
*/
function PluginDirectoryLine({
directory,
failed,
}: {
directory: PluginDirectoryResponse | null;
/** The read failed: say so in words (there is no path to show then). */
failed: boolean;
}) {
if (directory === null && !failed) return null;
return (
<div className="mt-2 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-xs text-gray-400 dark:text-gray-500">
<span className="shrink-0">{S.plugins.dirLabel}</span>
{directory === null ? (
<span>{S.plugins.dirUnavailable}</span>
) : (
<>
{/* The path is the one value here worth taking away, so it is selectable, truncating
with the full path in the tooltip, and carries the app's copy button beside it. */}
<span className="min-w-0 truncate font-mono" data-tooltip={directory.path}>
{directory.path}
</span>
<CopyButton text={directory.path} label={S.plugins.dirPathCopy} size="sm" />
<span className="shrink-0">
{directory.plugins.length === 0
? S.plugins.dirEmpty
: S.plugins.dirCount(directory.plugins.length)}
</span>
</>
)}
</div>
);
}
/** A single plugin card: metadata display (contents badges + a semantic metadata line) + update reminder + quick start + "manage installs" Modal. */
function PluginCard({
plugin,
category,
installed,
marketSpecifier,
canDelete,
installRefusal,
onQuickInvoke,
onToggleInstall,
onUpdateOutdated,
onExport,
onDelete,
}: {
plugin: PluginItem;
/** The library's category, shown as the row's first tag (the page has no groups). */
category: string;
installed: InstalledMap;
/** The specifier of the market entry describing this plugin, or null when the registry has none. */
marketSpecifier: string | null;
/** Whether this account may delete, which is the account's admin right and not a Project role (see the page header). */
canDelete: boolean;
/**
* Why the last install of this plugin onto an Agent did not land, naming that Agent
* (install-refusal.ts). The page keeps it rather than this card: an install moves the snapshot
* optimistically, so the card is filed into the other section and remounts on the way — and a
* sentence held here would go with the instance that sent it. Undefined when there is none.
*/
installRefusal?: string;
onQuickInvoke: (skillName: string) => void;
onToggleInstall: (agentId: string, plugin: PluginItem, on: boolean) => Promise<WriteOutcome>;
onUpdateOutdated: (name: string, agentIds: string[]) => Promise<WriteOutcome>;
onExport: (name: string) => Promise<WriteOutcome>;
onDelete: (plugin: PluginItem) => Promise<WriteOutcome>;
}) {
const { locale } = useLocale();
const { agents, currentAgent } = useProject();
const [installOpen, setInstallOpen] = useState(false);
// Agents pending an update confirmation (null = none): an update is an overwriting reinstall, so it needs a confirm + a per-agent version list before it runs.
const [pendingUpdate, setPendingUpdate] = useState<string[] | null>(null);
const [updating, setUpdating] = useState(false);
// Agent pending an uninstall confirmation (null = none): uninstalling deletes the installed files, local edits included.
const [pendingUninstall, setPendingUninstall] = useState<string | null>(null);
const [uninstalling, setUninstalling] = useState(false);
// Whether this card's delete confirmation is open: deleting a user plugin removes its directory from disk, so it confirms first, like the uninstall above.
const [deleteOpen, setDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
/**
* The server's words for the last write each of this card's three confirmations asked for and
* did not get. They are drawn inside the confirmation that asked (its `refusal` slot): the
* plugin, the update or the delete changed nothing, so retrying is the next thing the person
* does, and the button that retries it is in that card. A toast says the same thing, but it
* dismisses itself after six seconds and sits over the card rather than in it.
*/
const [updateRefusal, setUpdateRefusal] = useState<string | null>(null);
const [uninstallRefusal, setUninstallRefusal] = useState<string | null>(null);
const [deleteRefusal, setDeleteRefusal] = useState<string | null>(null);
/**
* The reason an "Export plugin" that did not land left under the row
* (plugin-export-refusal.ts). Held here rather than on the page (unlike the install refusal
* above): an export moves nothing, so the card instance that asked is still the one on screen.
*/
const [exportRefusal, setExportRefusal] = useState<string | null>(null);
/** A user plugin, i.e. one from the server's plugin directory: the only kind the library can delete, and the only kind that carries a "user" mark. */
const isUser = plugin.source === "user";
/** Open a confirmation, without the previous refusal: that sentence belonged to the attempt before (one attempt, one reason). */
const askUpdate = (agentIds: string[]) => {
setPendingUpdate(agentIds);
setUpdateRefusal(null);
};
const askUninstall = (agentId: string) => {
setPendingUninstall(agentId);
setUninstallRefusal(null);
};
const askDelete = () => {
setDeleteOpen(true);
setDeleteRefusal(null);
};
/**
* The three confirmations close on the answer, not on the request: a refused write changes
* nothing on either side (the same files are still installed, the same plugin is still on
* disk), so the card stays open with the server's words in it and the same button retries.
* Closing it as the request left used to carry that reason into a toast that dismisses itself
* after six seconds and sits above the card.
*/
const confirmUpdate = async () => {
if (!pendingUpdate) return;
setUpdating(true);
const outcome = await onUpdateOutdated(plugin.name, pendingUpdate);
setUpdating(false);
if (outcome.ok) setPendingUpdate(null);
else setUpdateRefusal(outcome.reason);
};
const confirmUninstall = async () => {
if (pendingUninstall === null) return;
setUninstalling(true);
const outcome = await onToggleInstall(pendingUninstall, plugin, false);
setUninstalling(false);
if (outcome.ok) setPendingUninstall(null);
else setUninstallRefusal(outcome.reason);
};
const confirmDelete = async () => {
setDeleting(true);
const outcome = await onDelete(plugin);
setDeleting(false);
if (outcome.ok) setDeleteOpen(false);
else setDeleteRefusal(outcome.reason);
};
/**
* "Export plugin": one attempt, one reason — starting attempt clears the sentence the one
* before it left (so it is not read as this attempt's), and only a refusal leaves one behind.
* A written one clears it: the zip is on disk and the line no longer has anything to say.
*/
const exportThis = async () => {
setExportRefusal(null);
setExportRefusal(refusalOf(await onExport(plugin.name)));
};
/** Display name of the Agent pending uninstall (falls back to the raw id below). */
const uninstallAgent =
pendingUninstall !== null ? agents.find((a) => a.agentId === pendingUninstall) : undefined;
const uninstallAgentName = uninstallAgent ? agentDisplayName(uninstallAgent) : undefined;
let installedCount = 0;
for (const m of installed.values()) if (pluginInstalled(plugin, m)) installedCount += 1;
// The server's list of Agents behind on this plugin, minus any this page has since uninstalled
// it from (the list is re-read after every install action, but the snapshot moves first).
const outdated = outdatedAgentIds(agents, plugin.name).filter((agentId) =>
pluginInstalled(plugin, installed.get(agentId)),
);
// Quick start opens a draft on the currently selected Agent and pre-selects one of this
// plugin's skills there, so it's only offered once that Agent has one installed — otherwise
// it would pre-select a skill the Agent lacks. A plugin with no skill has nothing to start.
const currentInstalls = currentAgent === null ? undefined : installed.get(currentAgent.agentId);
const quickStartSkill =
currentInstalls === undefined
? undefined
: plugin.skills.find((skill) => currentInstalls.skills.has(skill.name));
// The shelf's state on the Agent the page is working with (undefined when none is selected):
// the card says what a click would do there — install the plugin, or bring a copy the server
// lists as behind up to the library's version — and quick start becomes usable once the
// optimistic install has moved that Agent's snapshot.
const marketAgent = currentAgent;
const market =
marketAgent === null
? undefined
: marketState(
plugin,
installed.get(marketAgent.agentId),
outdated.includes(marketAgent.agentId),
);
/** The display name of that Agent, for the copies that have to say which one they act on. */
const marketAgentName = marketAgent === null ? undefined : agentDisplayName(marketAgent);
// The card's detail Modal (the model library's card pattern): what the plugin ships,
// with a per-skill SKILL.md reader.
const [detailOpen, setDetailOpen] = useState(false);
// Short description takes priority, falling back to the full description
// when missing (per UI language); title carries the full description for hover reading.
const description = localizedShortText(locale, plugin);
const fullDescription = localizedText(locale, plugin.description, plugin.descriptionZh);
// Metadata line: version (`YYYY.MM.DD.N`, omitted when the manifest carries none, displayed
// with a `v` in front) · how long ago that version's date is · usage count — plain readable
// phrases, no badges.
const versionMatch = /^(\d{4})\.(\d{2})\.(\d{2})\./.exec(plugin.version);
const versionDate = versionMatch ? versionMatch.slice(1, 4).join("-") : null;
const meta = [
plugin.version ? `v${plugin.version}` : null,
versionDate ? formatRelativeDate(versionDate, locale) : null,
S.plugins.usedByAgents(installedCount),
]
.filter((v): v is string => v !== null)
.join(" · ");
return (
<div className="rounded-md p-4 transition-colors hover:bg-gray-100/70 dark:hover:bg-gray-800/60">
<div className="flex items-center gap-3">
<button
type="button"
onClick={() => setDetailOpen(true)}
className="min-w-0 flex-1 text-left"
>
{/* Header: the plugin icon centered across the two text rows (rounded tile in the plugin's
own palette color — see SkillTile; deliberately a bit smaller than the two rows),
with the name and short description on one line each to the right. */}
<div className="flex items-center gap-3">
<SkillTile
icon={plugin.icon}
name={plugin.name}
fallback={ICONS.puzzle}
size={36}
glyph={20}
/>
<div className="min-w-0 flex-1">
<span
className="block truncate font-mono text-[length:var(--ui-text-code-size)] font-semibold"
data-tooltip={plugin.name}
data-tooltip-content="code"
>
{plugin.name}
</span>
{/* Short description truncates to one line (full description goes into title for hover reading). */}
<p
className="mt-0.5 truncate text-xs leading-5 text-gray-500 dark:text-gray-400"
data-tooltip={fullDescription}
data-tooltip-content="text"
>
{description}
</p>
</div>
</div>
{/* Metadata line under the header (e.g. `v2026.08.29.1 · updated 3 days ago · used by
2 agents`); what the plugin contains lives in the detail Modal this card opens. */}
<p
className="mt-2.5 truncate text-xs text-gray-400 dark:text-gray-500"
data-tooltip={meta}
data-tooltip-content="text"
>
{meta}
</p>
{/* Tag line: the category, where the plugin came from (the build, or the server's plugin
directory — the two kinds carry different actions, so this is what says which a card
is), and what it carries. */}
<div className="mt-2 flex flex-wrap items-center gap-1.5 text-xs">
<Tag>{category}</Tag>
{isUser ? (
<Tag title={S.plugins.userBadgeHint}>{S.plugins.userBadge}</Tag>
) : (
<Tag title={S.plugins.libraryBuiltinHint}>{S.plugins.builtin}</Tag>
)}
{plugin.skills.length > 0 && (
<Tag mono>{S.skills.skillCount(plugin.skills.length)}</Tag>
)}
{plugin.hooks.length > 0 && <Tag mono>{S.hooks.hookCount(plugin.hooks.length)}</Tag>}
{/* The shelf's state, relative to the Agent the page is working with: the same value
the one-click button acts on, named so the reader knows which Agent it is about. */}
{market !== undefined && (
<Tag title={S.plugins.marketStateHint(marketAgentName ?? "")}>
{S.plugins.marketState[market]}
</Tag>
)}
</div>
</button>
{detailOpen && (
<PluginDetailModal
plugin={plugin}
meta={meta}
marketSpecifier={marketSpecifier}
onClose={() => setDetailOpen(false)}
/>
)}
{/* Actions: equal-square light icon buttons in a single row, vertically centered at the
card's right edge (copy goes into aria-label and title). */}
<div className="flex shrink-0 items-center justify-center gap-1.5">
{/* The shelf's one-click action, on the Agent the page is working with: install when that
Agent holds nothing of this plugin, or the update an outdated copy gets elsewhere on
the card (that one confirms first, because it overwrites installed files). The card's
primary action, so it carries a label rather than a glyph; with no Agent selected
there is nothing to install to and the shelf's state is not shown either. */}
{market === "available" && marketAgent !== null && (
<Button
size="sm"
className="h-8 shrink-0"
aria-label={`${S.plugins.marketInstall(marketAgentName ?? "")} ${plugin.name}`}
title={S.plugins.marketInstall(marketAgentName ?? "")}
onClick={() => void onToggleInstall(marketAgent.agentId, plugin, true)}
>
{S.plugins.install}
</Button>
)}
{market === "updatable" && marketAgent !== null && (
<Button
size="sm"
variant="secondary"
className="h-8 shrink-0"
aria-label={`${S.plugins.marketUpdate(marketAgentName ?? "")} ${plugin.name}`}
title={S.plugins.marketUpdate(marketAgentName ?? "")}
onClick={() => askUpdate([marketAgent.agentId])}
>
{S.skills.updateAction}
</Button>
)}
{/* Light (secondary): an update nudge, not the card's primary action. The last stop on
the plugins trail, so it carries the dot itself — straddling the top-right corner of
the button's border, the anchoring rule update-dot.tsx states for a button. The mark
is decorative; what is waiting is already in this button's own title and accessible
name, which is why no sr-only sentence is added beside it. */}
{outdated.length > 0 && (
<Button
size="sm"
variant="secondary"
className="relative h-8 w-8 shrink-0 justify-center p-0"
aria-label={`${S.plugins.updateOutdated(outdated.length)} ${plugin.name}`}
title={S.plugins.updateOutdated(outdated.length)}
onClick={() => askUpdate(outdated)}
>
<GlyphIcon d={ICONS.rotateCw} size={ICON_SIZE.iconButton} />
<UpdateDot
size="inline"
position="right-0.5 top-0.5 -translate-y-1/2 translate-x-1/2"
/>
</Button>
)}
{plugin.skills.length > 0 && (
<Button
size="sm"
className="h-8 w-8 shrink-0 justify-center p-0"
aria-label={`${S.skills.quickInvoke} ${plugin.name}`}
title={quickStartSkill ? S.skills.quickInvoke : S.plugins.quickInvokeNeedsInstall}
disabled={quickStartSkill === undefined}
onClick={() => {
if (quickStartSkill) onQuickInvoke(quickStartSkill.name);
}}
>
<GlyphIcon d={ICONS.paperPlane} size={ICON_SIZE.iconButton} />
</Button>
)}
<Button
size="sm"
className="h-8 w-8 shrink-0 justify-center p-0"
aria-label={`${S.skills.manageInstall} ${plugin.name}`}
title={S.skills.manageInstall}
onClick={() => setInstallOpen(true)}
>
<GlyphIcon d={INSTALL_ICON} size={ICON_SIZE.iconButton} />
</Button>
{/* Export, for a user plugin only (a built-in is in the build, so there is nothing to take
a copy of): the archive download the Skills and Hooks rows export with, open to every
member — the route is a read. */}
{isUser && (
<Button
size="sm"
variant="secondary"
className="h-8 w-8 shrink-0 justify-center p-0"
aria-label={`${S.plugins.exportPlugin} ${plugin.name}`}
title={S.plugins.exportPlugin}
onClick={() => void exportThis()}
>
<DownloadIcon size={ICON_SIZE.iconButton} />
</Button>
)}
{/* Delete, for a user plugin and an admin: the one action that removes files from the
machine, so it takes the danger variant and confirms first. */}
{isUser && canDelete && (
<Button
size="sm"
variant="danger"
className="h-8 w-8 shrink-0 justify-center p-0"
aria-label={`${S.plugins.deletePluginAction} ${plugin.name}`}
title={S.plugins.deletePluginAction}
onClick={askDelete}
>
<GlyphIcon d={ICONS.trash} size={ICON_SIZE.iconButton} />
</Button>
)}
</div>
</div>
{/* An install this card offered that did not land: the card is back with the button that
retries it, so the reason sits under the row rather than in a notification that
dismisses itself (install-refusal.ts). */}
{installRefusal !== undefined && (
<p
role="alert"
data-testid="install-refusal"
data-tooltip={installRefusal}
data-tooltip-content="text"
className={`mt-1 line-clamp-2 break-words text-xs ${toneInk.danger}`}
>
{installRefusal}
</p>
)}
{/* An export this card offered that did not land: the card is still here with the button
that retries it, so the reason sits under the row rather than in a notification that
dismisses itself (plugin-export-refusal.ts). */}
{exportRefusal !== null && (
<p
role="alert"
data-testid="export-refusal"
data-tooltip={exportRefusal}
data-tooltip-content="text"
className={`mt-1 line-clamp-2 break-words text-xs ${toneInk.danger}`}
>
{exportRefusal}
</p>
)}
{installOpen && (
<Modal
open
title={S.skills.manageInstallTitle(plugin.name)}
onClose={() => setInstallOpen(false)}
>
<div className="space-y-1">
{agents.length === 0 && (
<p className="py-1.5 text-xs text-gray-400">{S.common.loading}</p>
)}
{agents.map((a) => (
<InstallRow
key={a.agentId}
agentId={a.agentId}
name={agentDisplayName(a)}
installed={pluginInstalled(plugin, installed.get(a.agentId))}
outdated={outdated.includes(a.agentId)}
onToggle={(on) => {
// Install runs directly; uninstall deletes the installed files, so it confirms first.
if (on) void onToggleInstall(a.agentId, plugin, true);
else askUninstall(a.agentId);
}}
onUpdate={() => askUpdate([a.agentId])}
/>
))}
</div>
</Modal>
)}
{pendingUpdate && (
<ConfirmModal
open
title={S.plugins.updateConfirmTitle(plugin.name)}
tone="primary"
confirmLabel={S.skills.updateAction}
cancelLabel={S.common.cancel}
busy={updating}
onClose={() => setPendingUpdate(null)}
onConfirm={() => void confirmUpdate()}
refusal={updateRefusal === null ? undefined : S.common.refused(updateRefusal)}
>
<div className="space-y-3">
<p className="text-sm text-gray-600 dark:text-gray-300">
{S.plugins.updateConfirmWarning(plugin.name)}
</p>
{/* Per-agent old → new version, so it's clear exactly which installs get overwritten. */}
<ul className="max-h-60 divide-y divide-gray-100 overflow-y-auto rounded-md border border-gray-200 dark:divide-gray-800 dark:border-gray-800">
{pendingUpdate.map((agentId) => {
const oldVersion = installedPluginVersion(plugin, installed.get(agentId));
const target = agents.find((a) => a.agentId === agentId);
return (
<li
key={agentId}
className="flex items-center justify-between gap-3 px-3 py-1.5 text-xs"
>
<span className="min-w-0 truncate">
{target ? agentDisplayName(target) : agentId}
</span>
<span className="shrink-0 font-mono text-gray-500 dark:text-gray-400">
{oldVersion || "?"} → {plugin.version}
</span>
</li>
);
})}
</ul>
</div>
</ConfirmModal>
)}
{pendingUninstall !== null && (
<ConfirmModal
open
title={S.plugins.uninstallConfirmTitle(plugin.name)}
confirmLabel={S.skills.uninstall}
cancelLabel={S.common.cancel}
busy={uninstalling}
onClose={() => setPendingUninstall(null)}
onConfirm={() => void confirmUninstall()}
refusal={uninstallRefusal === null ? undefined : S.common.refused(uninstallRefusal)}
>
<p className="text-sm text-gray-600 dark:text-gray-300">
{S.plugins.uninstallConfirmBody(plugin.name, uninstallAgentName ?? pendingUninstall)}
</p>
</ConfirmModal>
)}
{/* Delete confirmation: unlike an uninstall, this takes the plugin's directory — and with
it every skill and hook it ships — off the machine, so it asks first and says so. */}
{deleteOpen && (
<ConfirmModal
open
title={S.plugins.deleteConfirmTitle(plugin.name)}
confirmLabel={S.plugins.deletePluginAction}
cancelLabel={S.common.cancel}
busy={deleting}
onClose={() => setDeleteOpen(false)}
onConfirm={() => void confirmDelete()}
refusal={deleteRefusal === null ? undefined : S.common.refused(deleteRefusal)}
>
<p className="text-sm text-gray-600 dark:text-gray-300">
{S.plugins.deleteConfirmBody(plugin.name)}
</p>
</ConfirmModal>
)}
</div>
);
}
/**
* One Agent row in the "manage installs" Modal: not-installed shows
* "Install"; installed shows "Installed", switching to "Uninstall" on hover
* (same button, click to uninstall); an installed copy the server lists as behind the
* library additionally shows an accent "Update" button (reinstall = update). Install
* and uninstall go through optimistic updates (toggleInstall), rolling back on
* failure.
*/
function InstallRow({
agentId,
name,
installed,
outdated,
onToggle,
onUpdate,
}: {
agentId: string;
name: string;
installed: boolean;
outdated: boolean;
onToggle: (on: boolean) => void;
onUpdate: () => void;
}) {
return (
<div className="flex items-center gap-2 rounded-md px-1.5 py-1.5 transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/60">
<AgentAvatar id={agentId} name={name} size={22} className="shrink-0 rounded" />
<span
className="min-w-0 flex-1 truncate text-sm"
data-tooltip={agentId}
data-tooltip-content="text"
>
{name}
</span>
{installed && outdated && (
<Button
size="sm"
variant="secondary"
className="shrink-0"
aria-label={`${S.skills.updateAction} ${agentId}`}
onClick={onUpdate}
>
{S.skills.updateAction}
</Button>
)}
{installed ? (
// group: on hover the button's copy switches "Installed" → "Uninstall" (the same button carries the uninstall action).
<Button
size="sm"
variant="ghost"
className="group shrink-0"
aria-label={`${S.skills.uninstall} ${agentId}`}
onClick={() => onToggle(false)}
>
<span className="group-hover:hidden">{S.skills.installed}</span>
<span className="hidden text-red-600 group-hover:inline dark:text-red-400">
{S.skills.uninstall}
</span>
</Button>
) : (
<Button
size="sm"
className="shrink-0"
aria-label={`${S.skills.install} ${agentId}`}
onClick={() => onToggle(true)}
>
{S.skills.install}
</Button>
)}
</div>
);
}
/**
* A module plugin as a row in the library card's shape: the icon tile, the specifier and
* version, the description, a metadata line saying what the deployment's own state is (not
* installed → nothing yet; installed but not loaded → the restart it waits for; running → the
* modules it holds), then the tag line — its categories, "built in" when this build ships
* it, the license, the keywords. The trailing cluster is the verb: Install on an available
* row, Remove on an installed one. The row is a link to the registry page when the registry
* knows the package; the cluster sits BESIDE that link — a button inside an anchor is invalid
* markup, and the click would have two meanings.
*/
function ModuleRow({
specifier,
entry,
state,
error,
shipped,
onlyOn,
removeBlocked,
refusal,
busy,
blocked,
installLabel,
onInstall,
onRemove,
}: {
specifier: string;
entry: PluginIndexEntry | undefined;
state: ModuleState;
/** Why it failed to load, when it did. */
error?: string;
/** The build carries this one: installing it copies nothing over the network. */
shipped: boolean;
/** The machines it is listed for, by name, when not every machine runs it. */
onlyOn?: string[];
/** Why Remove is unavailable in this view, when it is. */
removeBlocked?: string;
/**
* Why the last write this row offers was refused. It is drawn in the row because a refusal
* changes nothing: the row and its button are what the reader retries from, and a sentence
* that dismisses itself would be gone before the second attempt.
*/
refusal?: string;
/** This row's own install or removal is running. */
busy: boolean;
/** Another row's is: one at a time, so the rest are held rather than queued. */
blocked: boolean;
/**
* What the install verb says, when it is not the Project's own install. A published row
* fetches the package into the library rather than listing it for the Project, so its verb
* names that first step instead.
*/
installLabel?: string;
onInstall: (() => void) | null;
onRemove: (() => void) | null;
}) {
const { locale } = useLocale();
const installText = installLabel ?? S.plugins.install;
const stateText =
state === "active"
? S.plugins.stateActive
: state === "pending"
? S.plugins.installedRestart
: state === "failed"
? S.plugins.stateFailed
: state === "unsynced"
? S.plugins.notSynced
: state === "elsewhere"
? S.plugins.notHere
: S.plugins.notInstalled;
// Metadata line, the library card's shape: version · updated · what it is here.
const updated =
entry?.updatedAt === undefined
? null
: formatRelativeDate(new Date(entry.updatedAt * 1000).toISOString().slice(0, 10), locale);
const meta = [entry === undefined ? null : `v${entry.version}`, updated]
.filter((v): v is string => v !== null)
.join(" · ");
const body = (
<>
<div className="flex items-center gap-3">
<SkillTile name={specifier} fallback={ICONS.puzzle} size={36} glyph={20} />
<div className="min-w-0 flex-1">
<div className="flex items-baseline gap-2">
<span
className="min-w-0 truncate font-mono text-[length:var(--ui-text-code-size)] font-semibold"
data-tooltip={`${S.pluginRegistry.specifierHint}: ${specifier}`}
data-tooltip-content="code"
>
{specifier}
</span>
</div>
<p
className="mt-0.5 truncate text-xs leading-5 text-gray-500 dark:text-gray-400"
data-tooltip={entry?.description}
data-tooltip-content="text"
>
{entry?.description ?? S.plugins.shippedNoEntry}
</p>
</div>
</div>
<p
className="mt-2.5 truncate text-xs text-gray-400 dark:text-gray-500"
data-tooltip={`${meta}${meta === "" ? "" : " · "}${stateText}`}
data-tooltip-content="text"
>
{meta !== "" && <span>{meta} · </span>}
<span
className={
state === "active"
? toneInk.success
: state === "pending" || state === "unsynced"
? toneInk.attention
: state === "failed"
? toneInk.danger
: undefined
}
>
{stateText}
</span>
</p>
{state === "failed" && error !== undefined && (
<p
className={`mt-1 truncate text-xs ${toneInk.danger}`}
data-tooltip={error}
data-tooltip-content="text"
>
{error}
</p>
)}
<div className="mt-2 flex flex-wrap items-center gap-1.5 text-xs">
{(entry?.categories ?? []).map((category) => (
<Tag key={category}>{category}</Tag>
))}
{onlyOn !== undefined && <Tag>{S.plugins.onlyOn(onlyOn.join(", "))}</Tag>}
{shipped && <Tag title={S.plugins.builtinHint}>{S.plugins.builtin}</Tag>}
{(entry?.keywords ?? []).map((keyword) => (
<Tag key={keyword} mono>
{keyword}
</Tag>
))}
</div>
</>
);
return (
<div className="rounded-md transition-colors hover:bg-gray-100/70 dark:hover:bg-gray-800/60">
<div className="flex items-center gap-3 p-4">
{entry !== undefined ? (
<Link to={`/plugins/registry/${specifier}`} className="min-w-0 flex-1">
{body}
</Link>
) : (
<div className="min-w-0 flex-1">{body}</div>
)}
{/* The verb, in the library card's shape: one square light icon button, its copy in
aria-label and title. While it runs, a spinner stands in for the glyph. */}
<div className="flex shrink-0 items-center justify-center gap-1.5">
{state === "none"
? onInstall !== null && (
<Button
size="sm"
className="h-8 w-8 shrink-0 justify-center p-0"
aria-label={`${busy ? S.plugins.installing : installText} ${specifier}`}
aria-busy={busy}
title={busy ? S.plugins.installing : installText}
disabled={busy || blocked}
onClick={onInstall}
>
{busy ? (
<StatusIcon state="running" />
) : (
<GlyphIcon d={INSTALL_ICON} size={ICON_SIZE.iconButton} />
)}
</Button>
)
: onRemove !== null && (
<Button
size="sm"
className="h-8 w-8 shrink-0 justify-center p-0"
aria-label={`${S.plugins.uninstall} ${specifier}`}
aria-busy={busy}
title={removeBlocked ?? S.plugins.uninstall}
disabled={busy || blocked || removeBlocked !== undefined}
onClick={onRemove}
>
{busy ? (
<StatusIcon state="running" />
) : (
<GlyphIcon d={ICONS.trash} size={ICON_SIZE.iconButton} />
)}
</Button>
)}
</div>
</div>
{/* A write this row offered that did not land: the row still stands, its button is the
retry, so the reason sits under the row rather than in a notification that dismisses
itself. Outside the link on purpose — the row's body is a link to the registry page, and
clicking a reason should not take the reader somewhere else. */}
{refusal !== undefined && (
<p
role="alert"
data-testid="row-refusal"
data-tooltip={refusal}
data-tooltip-content="text"
className={`-mt-1 px-4 pb-3 line-clamp-2 break-words text-xs ${toneInk.danger}`}
>
{refusal}
</p>
)}
</div>
);
}