Redesign Agents & models as a roster of cards with a side drawer and an Add agent chooser

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-08 18:08:33 -08:00
1 parent 5136269ca7
commit 0fdb99f723
9 files changed
+1035 -351

No files matched your search

+132 -9
View File
@@ -1,11 +1,14 @@
// Plan2Code Web Console - the agents view's mount, state and server calls.
//
// One mount serves the User Preferences Agents & models tab and the
// agent-less setup page, drawn as a master-detail split: the list on the
// left (agents-summary.js), the picked agent's form or state in the right
// pane (agents-form.js / agents-summary.js), the row-list editor shared by
// every list field (agents-list-editor.js) and the pure helpers underneath
// (agents-data.js). Picking a row is the navigation; there is no back page.
// agent-less setup page. Preferences draws a roster of agent cards
// (agents-summary.js) with the picked agent's form in a side drawer
// (agents-form.js) and an Add agent chooser where the starter templates are an
// opt-in; the setup page keeps a master-detail split, its list on the left and
// the picked entry's state (or the same form) in the right pane. The row-list
// editor shared by every list field is agents-list-editor.js and the pure
// helpers underneath are agents-data.js. Picking a card or row is the
// navigation; there is no back page.
// Nothing saves as it changes: a form edits a draft, and its Save sends the
// saved list with only that draft swapped in, so a half-typed command line
// never reaches agents.json or models.json.
@@ -24,8 +27,9 @@ import {
isDirty,
nameOf,
cleanAgent,
templateDraft,
} from "./agents/agents-data.js";
import { renderSummary, drawSummaryPane, drawBadge } from "./agents/agents-summary.js";
import { renderSummary, drawSummaryPane, drawBadge, drawChooser, markTemplateState } from "./agents/agents-summary.js";
import { drawForm, renderDirty } from "./agents/agents-form.js";
/**
@@ -113,6 +117,13 @@ export function mountAgentsView(container, opts = {}) {
// warnings while Save anyway is on offer.
formError: null,
formReplace: null,
// The drawer's tab ("models" or "launch"), the template a new agent was
// started from (its name, for the form's head), and whether the Add agent
// chooser is up; templateState remembers each template command's check.
tab: "models",
draftFrom: null,
chooserOpen: false,
templateState: new Map(),
// Delete agent waiting for its second click; the folds' open state, kept
// across redraws.
confirming: false,
@@ -125,6 +136,10 @@ export function mountAgentsView(container, opts = {}) {
confirmUnsaved,
pick,
pickSetup,
openChooser,
closeChooser,
startNew,
closeDrawer,
save: (key, options) => saveForm(key, options),
discard: () => discardOpen(),
deleteAgent,
@@ -157,6 +172,24 @@ export function mountAgentsView(container, opts = {}) {
else drawSummaryPane(ctx);
}
// Preferences only: the drawer shows while a form is open, and the roster
// behind it is out of reach (it also sits behind a scrim).
function syncDrawer() {
const drawer = $("drawer");
if (!drawer) return;
drawer.hidden = !ctx.openKey;
const behind = Boolean(ctx.openKey || ctx.chooserOpen);
$("table").inert = behind;
if ($("add")) $("add").inert = behind;
}
function syncChooser() {
const box = $("chooser");
if (!box) return;
box.hidden = !ctx.chooserOpen;
syncDrawer();
}
function edited() {
if (ctx.openKey) {
// A model added or removed changes what the strengths fold may pick.
@@ -173,6 +206,7 @@ export function mountAgentsView(container, opts = {}) {
ctx.drafts.delete(ctx.openKey);
ctx.strengthDrafts.delete(ctx.openKey);
ctx.openKey = null;
ctx.draftFrom = null;
return true;
}
@@ -199,14 +233,18 @@ export function mountAgentsView(container, opts = {}) {
ctx.formReplace = null;
ctx.confirming = false;
ctx.strengthsOpen = false;
ctx.tab = key === "agent:new" ? "launch" : "models";
ctx.argsOpen = key === "agent:new";
// A built-in's only section is its models: folded it would show nothing.
ctx.modelsOpen = key.startsWith("cli:");
if (mode === "setup") ctx.setupSel = key.startsWith("agent:") && key !== "agent:new" ? "setup:" + agentId(key) : null;
if (!ctx.drafts.has(key)) ctx.drafts.set(key, structuredClone(key === "agent:new" ? newAgent() : savedEntry(ctx.saved, key)));
renderSummary(ctx);
syncDrawer();
drawForm(ctx);
$("form").querySelector("input")?.focus();
// A form of fields starts in its first one; the models list would scroll to its add row, so it starts on its tab.
const first = ctx.tab === "launch" ? $("form").querySelector(".prefs-agents-fields input") : null;
(first || $("form").querySelector('.agent-tab[aria-selected="true"]'))?.focus();
}
// The form goes back to the empty or picked pane; focus goes to the row
@@ -219,16 +257,77 @@ export function mountAgentsView(container, opts = {}) {
ctx.strengthDrafts.delete(ctx.openKey);
}
ctx.openKey = null;
ctx.draftFrom = null;
ctx.formError = null;
ctx.formReplace = null;
ctx.confirming = false;
renderSummary(ctx);
drawPane();
syncDrawer();
const rowKey = left && mode === "setup" && left.startsWith("agent:") ? "setup:" + agentId(left) : left;
const row = rowKey && $("table").querySelector(`[data-key="${CSS.escape(rowKey)}"]`);
(row || $("add")).focus();
}
const agentCardFor = (key) => $("table").querySelector(`[data-key="${CSS.escape(key)}"]`);
// The drawer's way out (Close, its scrim, Esc): a dirty draft asks first.
async function closeDrawer() {
const left = ctx.openKey;
if (!left) return;
if (!(await leaveForm())) return focusOpen();
ctx.formError = null;
ctx.formReplace = null;
ctx.confirming = false;
renderSummary(ctx);
drawPane();
syncDrawer();
(agentCardFor(left) || $("add"))?.focus();
}
// Add agent: the chooser, with the templates as an opt-in. Picking a tile is
// what starts the draft (and asks about an unsaved one first).
function openChooser() {
ctx.chooserOpen = true;
drawChooser(ctx);
syncChooser();
$("chooser").querySelector(".chooser-tile:not(:disabled)")?.focus();
for (const t of ctx.saved.templates) checkTemplate(t.command);
}
function closeChooser() {
ctx.chooserOpen = false;
syncChooser();
$("add")?.focus();
}
// Whether a template's command is on this computer, asked once per load.
async function checkTemplate(command) {
let state = ctx.templateState.get(command) || "unknown";
if (state === "unknown") {
try {
const res = await fetch("/agents/test", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ command }),
});
if (res.ok) state = (await res.json()).found ? "ok" : "missing";
} catch {}
ctx.templateState.set(command, state);
}
if (ctx.chooserOpen) markTemplateState(ctx, command, state);
}
async function startNew(template) {
if (!(await leaveForm())) return;
ctx.chooserOpen = false;
syncChooser();
ctx.drafts.set("agent:new", structuredClone(template ? templateDraft(template) : newAgent()));
openForm("agent:new");
ctx.draftFrom = template ? template.name : null;
drawForm(ctx);
}
/* ------------------------------------------------------------- badges */
// Whether each row's command is on PATH, all at once. /agents/test only
@@ -308,6 +407,7 @@ export function mountAgentsView(container, opts = {}) {
ctx.strengthDrafts.delete(ctx.openKey);
ctx.openKey = key;
ctx.drafts.set(key, structuredClone(savedEntry(ctx.saved, key)));
ctx.draftFrom = null;
ctx.formError = null;
ctx.formReplace = null;
renderSummary(ctx);
@@ -357,6 +457,7 @@ export function mountAgentsView(container, opts = {}) {
const isNew = key === "agent:new";
if (isNew && (!String(draft.name || "").trim() || !String(draft.command || "").trim())) {
ctx.formError = { field: String(draft.name || "").trim() ? "command" : "name", error: "Give it a name and a command first." };
ctx.tab = "launch";
drawForm(ctx);
return false;
}
@@ -373,6 +474,7 @@ export function mountAgentsView(container, opts = {}) {
}
if (!res.ok) {
ctx.formError = { field: body.index === at ? body.field : null, error: body.error || "Could not save." };
if (ctx.formError.field) ctx.tab = ctx.formError.field === "models" ? "models" : "launch";
ctx.formReplace = null;
drawForm(ctx);
return false;
@@ -471,7 +573,7 @@ export function mountAgentsView(container, opts = {}) {
// Back into the form after Keep editing or a failed Save: the marked field, else the first.
function focusOpen() {
const form = $("form");
(form.querySelector("input.invalid") || form.querySelector("input"))?.focus();
(form.querySelector("input.invalid") || form.querySelector('.agent-tab[aria-selected="true"]'))?.focus();
}
// Each time the dialog opens: the list, from the server. The setup mount
@@ -480,6 +582,9 @@ export function mountAgentsView(container, opts = {}) {
async function load() {
const seq = ++loadSeq;
ctx.openKey = null;
ctx.draftFrom = null;
ctx.chooserOpen = false;
ctx.templateState.clear();
ctx.drafts.clear();
ctx.strengthDrafts.clear();
ctx.found.clear();
@@ -530,10 +635,28 @@ export function mountAgentsView(container, opts = {}) {
setAgentsStatus(problems.join(" "), problems.length > 0);
renderSummary(ctx);
drawPane();
syncChooser();
}
function wire() {
$("add")?.addEventListener("click", () => pick("agent:new"));
$("add")?.addEventListener("click", () => (mode === "setup" ? pick("agent:new") : openChooser()));
$("scrim")?.addEventListener("click", () => closeDrawer());
// Esc backs out of the topmost layer first: the chooser, then the drawer
// (a dirty draft asks), before the dialog's own Esc closes Preferences.
if (mode === "prefs") {
container.addEventListener("keydown", (e) => {
if (e.key !== "Escape" || e.defaultPrevented) return;
if (ctx.chooserOpen) {
e.preventDefault();
e.stopPropagation();
closeChooser();
} else if (ctx.openKey) {
e.preventDefault();
e.stopPropagation();
closeDrawer();
}
});
}
}
return { load, wire, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen };
@@ -1,17 +1,19 @@
// Plan2Code Web Console - the agents view's per-agent form, the detail pane.
// Plan2Code Web Console - the agents view's per-agent form, the drawer's content.
//
// What the right pane draws while a draft is being edited: the built-in's
// models fold or an added agent's fields (identity inline, Models and
// Command-line arguments folded), the foot (Save, Discard, the Unsaved
// badge, Save anyway after a 409, Delete with its inline confirm), error
// marking, and the focus save/restore that keeps a redraw from stealing
// where the person was. It only draws and listens: state and fetches live
// in the mount, reached through `ctx`.
// What the drawer (or, on the setup page, the split's right pane) draws while a
// draft is being edited: the head (name, command, a close button), two tabs,
// Models & strengths and Launch, the foot (Save, Discard, the Unsaved badge,
// Save anyway after a 409, Delete with its inline confirm), error marking, and
// the focus save/restore that keeps a redraw from stealing where the person
// was. A built-in's Launch tab only reads (Plan2Code owns its command); an
// added agent's holds the fields. It only draws and listens: state and fetches
// live in the mount, reached through `ctx`.
import { el } from "../../render.js";
import { listEditor } from "./agents-list-editor.js";
import { BUILT_IN, HAS_EFFORT, cliOf, savedEntry, isDirty } from "./agents-data.js";
import { strengthsFold } from "./agents-strengths.js";
import { strengthsPanel } from "./agents-strengths.js";
import { drawBadge } from "./agents-summary.js";
function agentField(label, field, child) {
const wrap = el("div", "agent-field");
@@ -63,50 +65,152 @@ function fold(ctx, which, title, cls, kids) {
return d;
}
// A built-in's whole form is its models, so the one fold holds the note, the
// locked shipped list and the editor for the person's own additions.
function builtInFields(ctx, cli, draft) {
const shipped = el("div", "models-list prefs-agents-shipped");
shipped.setAttribute("aria-label", "Comes with Plan2Code");
for (const m of ctx.saved.shipped[cli]) {
const row = el("div", "models-row locked");
row.append(el("span", null, m.id), el("span", null, m.label || ""));
shipped.appendChild(row);
/* ------------------------------------------------------------ models tab */
// One model: its name and id, the pill set (when the strengths loaded), and a
// Remove for the ones the person added.
function modelRow(ctx, m, panel, onRemove) {
const row = el("div", onRemove ? "models-row" : "models-row locked");
const name = el("span", "model-name");
const named = m.label && m.label !== m.id;
name.append(named ? m.label : m.id);
if (named) name.append(el("code", null, m.id));
row.appendChild(name);
row.appendChild(panel ? panel.pills(m.id, m.label || m.id) : el("span"));
if (onRemove) {
const remove = el("button", "btn small ghost", "Remove");
remove.type = "button";
remove.setAttribute("aria-label", "Remove " + (m.label || m.id));
remove.addEventListener("click", onRemove);
row.appendChild(remove);
} else {
row.appendChild(el("span"));
}
const note = el("div", "models-note");
note.innerHTML =
"<ul>" +
"<li>Restart <code>plan2code</code> to see a change in its model menu.</li>" +
"<li>At any time, run <code>plan2code --model &lt;id&gt;</code>, or pick your model inside your agent before running a skill.</li>" +
"<li>Updating Plan2Code refreshes the built-in list. Models you added stay, unless the built-in list now includes them.</li>" +
"<li>Devin models are limited to Low, Medium and High effort.</li>" +
"</ul>";
const comes = el("div", "agent-field");
comes.append(el("span", null, "Comes with Plan2Code"));
if (ctx.saved.shipped[cli].length) comes.append(shipped);
else comes.append(el("p", "help prefs-agents-none", `No models ship for ${BUILT_IN[cli]} yet; add your own below.`));
const yours = agentField(
"Models you added",
"models",
listEditor({ list: draft, kind: "models", field: "models", optionalName: false, addLabel: "Add a model", onChange: ctx.edited })
);
const models = () => [...ctx.saved.shipped[cli], ...draft];
return [
fold(ctx, "modelsOpen", "Models", "agent-fold", [note, comes, yours]),
...(ctx.modelsLoaded ? [strengthsFold(ctx, cli, draft, { models, hasEffort: HAS_EFFORT.includes(cli) })] : []),
];
return row;
}
function addedFields(ctx, draft) {
// The add-a-model row: an id, a name for the menu, and the button that moves
// them into the draft, so the draft never holds a half-typed model.
function addModelRow(ctx, list, { nameRequired, taken }) {
const wrap = el("div", "agent-row model model-add");
const id = el("input");
id.placeholder = "Model id, for {model}";
id.setAttribute("aria-label", "Model id");
id.dataset.field = "models";
const label = el("input");
label.placeholder = nameRequired ? "Name shown in the menu" : "Name shown in the menu (optional)";
label.setAttribute("aria-label", "Name shown in the menu");
label.dataset.field = "models";
const add = el("button", "btn small", "Add a model");
add.type = "button";
const submit = () => {
const value = id.value.trim();
const text = label.value.trim();
id.classList.toggle("invalid", !value || taken(value));
if (!value || taken(value)) {
id.focus();
return;
}
list.push(nameRequired ? { id: value, label: text || value } : text ? { id: value, label: text } : { id: value });
ctx.edited();
ctx.drawForm();
ctx.$("form").querySelector(".model-add input")?.focus();
};
add.addEventListener("click", submit);
for (const input of [id, label]) {
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
submit();
}
});
}
wrap.append(id, label, add);
return wrap;
}
function modelsTab(ctx, key, draft) {
const isCli = key.startsWith("cli:");
const cli = isCli ? cliOf(key) : null;
const mine = isCli ? draft : draft.models;
const shipped = isCli ? ctx.saved.shipped[cli] : [];
const all = () => [...shipped, ...mine.filter((m) => m.id)];
const owner = isCli ? cli : key === "agent:new" ? "" : savedEntry(ctx.saved, key).id;
const panel = ctx.modelsLoaded ? strengthsPanel(ctx, owner, draft, { models: all, hasEffort: isCli && HAS_EFFORT.includes(cli) }) : null;
const kids = [];
if (panel) {
const lead = agentField("In the loop", "strengths", panel.box);
lead.classList.add("prefs-agents-strengths-field");
kids.push(lead);
kids.push(el("p", "help models-tip", "Tap Thrifty, Balanced or Best on a model below to make it that strength's pick."));
}
if (isCli) {
const comes = el("div", "agent-field");
comes.append(el("span", null, "Comes with Plan2Code"));
if (shipped.length) {
const list = el("div", "models-list prefs-agents-shipped");
list.setAttribute("aria-label", "Comes with Plan2Code");
for (const m of shipped) list.appendChild(modelRow(ctx, m, panel, null));
comes.append(list);
} else {
comes.append(el("p", "help prefs-agents-none", `No models ship for ${BUILT_IN[cli]} yet; add your own below.`));
}
kids.push(comes);
}
const yours = agentField(isCli ? "Models you added" : "Models", "models", el("div", "models-list prefs-agents-mine"));
const rows = yours.querySelector(".models-list");
mine.forEach((m, i) =>
rows.appendChild(
modelRow(ctx, m, panel, () => {
mine.splice(i, 1);
ctx.edited();
ctx.drawForm();
})
)
);
const taken = (id) => all().some((m) => m.id === id);
yours.appendChild(addModelRow(ctx, mine, { nameRequired: isCli, taken }));
kids.push(yours);
if (isCli) {
const note = el("div", "models-note");
note.innerHTML =
"<ul>" +
"<li>Restart <code>plan2code</code> to see a change in its model menu.</li>" +
"<li>At any time, run <code>plan2code --model &lt;id&gt;</code>, or pick your model inside your agent before running a skill.</li>" +
"<li>Updating Plan2Code refreshes the built-in list. Models you added stay, unless the built-in list now includes them.</li>" +
"<li>Devin models are limited to Low, Medium and High effort.</li>" +
"</ul>";
kids.push(fold(ctx, "modelsOpen", "About this list", "agent-fold", [note]));
}
return kids;
}
/* ------------------------------------------------------------ launch tab */
// A built-in's Launch tab only reads: Plan2Code ships and updates its command.
function builtInLaunch(ctx, key) {
const cli = cliOf(key);
const entry = ctx.saved.builtins.find((b) => b.id === cli);
const note = el("div", "note");
note.append(el("b", null, "Managed by Plan2Code. "), `The command and arguments for ${BUILT_IN[cli]} ship with the app and update with it. Only its models are yours to change.`);
const list = el("dl", "kv");
const state = el("span", "prefs-badge");
const known = ctx.found.get(key);
drawBadge(state, known ? known.state : "unknown");
const command = el("dd");
command.append(el("code", null, (entry && entry.command) || cli), " ", state);
list.append(el("dt", null, "Command"), command);
if (entry && entry.prompt) {
const prompt = el("dd");
prompt.appendChild(el("code", null, entry.prompt));
list.append(el("dt", null, "Start prompt"), prompt);
}
return [note, list];
}
function addedLaunch(ctx, draft) {
const command = agentField("Command", "command", agentInput(ctx, draft, "command", "Command", "Program to run, such as myagent", true));
command.append(agentTest(ctx, draft));
const models = fold(ctx, "modelsOpen", "Models", "agent-fold", [
agentField(
"Models",
"models",
listEditor({ list: draft.models, kind: "models", field: "models", addLabel: "Add a model", onChange: ctx.edited })
),
]);
const args = fold(ctx, "argsOpen", "Command-line arguments", "agent-fold prefs-agents-args", [
agentField("Arguments", "args", listEditor({ list: draft.args, field: "args", placeholder: "--message={prompt}", addLabel: "Add an argument", aria: "Arguments", onChange: ctx.edited })),
agentField("Bypass arguments", "bypassArgs", listEditor({ list: draft.bypassArgs, field: "bypassArgs", placeholder: "--yes-always", addLabel: "Add an argument", aria: "Bypass arguments", onChange: ctx.edited })),
@@ -116,14 +220,12 @@ function addedFields(ctx, draft) {
agentField("Name", "name", agentInput(ctx, draft, "name", "Name", "Name shown in the menu", true)),
command,
agentField("Start prompt", "prompt", agentInput(ctx, draft, "prompt", "Start prompt", "/plan2code (blank starts with nothing typed)", false)),
models,
...(ctx.modelsLoaded
? [strengthsFold(ctx, ctx.openKey === "agent:new" ? "" : savedEntry(ctx.saved, ctx.openKey).id, draft, { models: () => draft.models, hasEffort: false })]
: []),
args,
];
}
/* ------------------------------------------------------------------ foot */
// Save, Discard and the Unsaved badge (shown only while the draft differs),
// the Saved mark's spot, Save anyway after a 409, and Delete agent with its
// confirm on the form itself (never the browser's confirm()).
@@ -180,7 +282,7 @@ export function renderDirty(ctx, key) {
// Which field or button has focus, so a redraw (an id assigned, an error
// marked) puts the person back where they were: { nth, start, end }. What
// they typed is already in the draft the redraw reads.
const FORM_FOCUSABLE = "input, button, summary";
const FORM_FOCUSABLE = "input, button, summary, select";
function formFocus(form) {
const active = document.activeElement;
@@ -203,29 +305,68 @@ function restoreFormFocus(form, at) {
}
}
const TABS = [
["models", "Models & strengths"],
["launch", "Launch"],
];
export function drawForm(ctx) {
const pane = ctx.$("form");
const key = ctx.openKey;
const draft = ctx.drafts.get(key);
const focus = formFocus(pane);
pane.replaceChildren();
const isCli = key.startsWith("cli:");
const head = el("div", "form-head");
const title = el("h3", "prefs-agents-title");
title.tabIndex = -1;
if (key.startsWith("cli:")) title.append(el("span", null, BUILT_IN[cliOf(key)]), el("code", null, cliOf(key)));
else title.append(el("span", null, key === "agent:new" ? "New agent" : savedEntry(ctx.saved, key).name));
if (isCli) title.append(el("span", null, BUILT_IN[cliOf(key)]), el("code", null, cliOf(key)));
else {
title.append(el("span", null, key === "agent:new" ? "New agent" : savedEntry(ctx.saved, key).name));
if (key === "agent:new" && ctx.draftFrom) title.append(el("span", "tag", `From the ${ctx.draftFrom} template`));
}
head.appendChild(title);
if (ctx.$("drawer")) {
const close = el("button", "btn small ghost drawer-close", "Close");
close.type = "button";
close.setAttribute("aria-label", "Close");
close.addEventListener("click", () => ctx.closeDrawer());
head.appendChild(close);
}
pane.appendChild(head);
const tabs = el("div", "agent-tabs");
tabs.setAttribute("role", "tablist");
const order = key === "agent:new" ? [...TABS].reverse() : TABS;
for (const [id, label] of order) {
const tab = el("button", "agent-tab", label);
tab.type = "button";
tab.setAttribute("role", "tab");
tab.dataset.tab = id;
tab.setAttribute("aria-selected", String(ctx.tab === id));
tab.addEventListener("click", () => {
if (ctx.tab === id) return;
ctx.tab = id;
ctx.drawForm();
});
tabs.appendChild(tab);
}
pane.appendChild(tabs);
const body = el("div", "agent-body");
const fields = el("div", "prefs-agents-fields");
fields.append(...(key.startsWith("cli:") ? builtInFields(ctx, cliOf(key), draft) : addedFields(ctx, draft)));
pane.appendChild(fields);
fields.setAttribute("role", "tabpanel");
if (ctx.tab === "models") fields.append(...modelsTab(ctx, key, draft));
else fields.append(...(isCli ? builtInLaunch(ctx, key) : addedLaunch(ctx, draft)));
body.appendChild(fields);
if (ctx.formError) {
for (const input of pane.querySelectorAll("input")) {
for (const input of body.querySelectorAll("input")) {
if (input.dataset.field === ctx.formError.field) input.classList.add("invalid");
}
pane.appendChild(el("p", "agent-error", ctx.formError.error));
body.appendChild(el("p", "agent-error", ctx.formError.error));
}
if (ctx.formReplace && ctx.formReplace.length) pane.appendChild(el("p", "agent-error", ctx.formReplace.join(" ")));
if (ctx.formReplace && ctx.formReplace.length) body.appendChild(el("p", "agent-error", ctx.formReplace.join(" ")));
pane.appendChild(body);
pane.appendChild(formFoot(ctx, key));
renderDirty(ctx, key);
restoreFormFocus(pane, focus);
@@ -1,17 +1,21 @@
// Plan2Code Web Console - the "Strengths in the loop" fold of an agent's form.
// Plan2Code Web Console - the "In the loop" panel of an agent's form.
//
// Maps the loop's three words (Thrifty, Balanced, Best) to one of the agent's
// own models, and to an effort where the agent takes one. Choices are
// select-only from the agent's Models list. An untouched row follows what
// ships; only a row the person changed is kept in the form's strength draft
// (ctx.strengthDrafts, by form key), which the form's Save sends. The rule that
// reads a row is resolveStrengths, the same module the server uses.
// own models, and to an effort where the agent takes one. The panel is two
// halves that stay in step: a summary box (one row per word: the model it
// resolves to, an effort select, and Reset or "default") and a pill set each
// model row carries, where tapping a word on a model makes it that word's pick.
// An untouched row follows what ships; only a row the person changed is kept in
// the form's strength draft (ctx.strengthDrafts, by form key), which the form's
// Save sends. The rule that reads a row is resolveStrengths, the same module the
// server uses.
import { el } from "../../render.js";
import { STRENGTH_ORDER, resolveStrengths } from "../../strengths.js";
import { canonical, strengthOwner } from "./agents-data.js";
const WORDS = { thrifty: "Thrifty", balanced: "Balanced", best: "Best" };
export const WORDS = { thrifty: "Thrifty", balanced: "Balanced", best: "Best" };
const HINTS = { thrifty: "Quick, cheap steps", balanced: "The everyday pick", best: "The hardest steps" };
const EFFORTS = ["low", "medium", "high"];
function option(value, text) {
@@ -20,12 +24,19 @@ function option(value, text) {
return o;
}
// A word as a colored chip: Thrifty, Balanced and Best get the rank colors.
export function wordChip(word) {
return el("span", "tier t-" + word, WORDS[word]);
}
/**
* The fold for the open form. `models` is the agent's Models list ({ id, label }
* The panel for the open form. `models` is the agent's Models list ({ id, label }
* rows) or a function returning it, read at every redraw so a model added in the
* same form shows up. `hasEffort` adds the effort select.
* same form shows up. `hasEffort` adds the effort select. Returns
* { box, pills(id, label), refresh }: the summary box, a builder for one model's
* pill set, and the redraw the form's edits call through ctx.strengthsRefresh.
*/
export function strengthsFold(ctx, agentId, draft, { models, hasEffort }) {
export function strengthsPanel(ctx, agentId, draft, { models, hasEffort }) {
const key = ctx.openKey;
const owner = agentId || strengthOwner(key);
const shipped = (ctx.saved.strengths.shipped && ctx.saved.strengths.shipped[owner]) || {};
@@ -39,13 +50,18 @@ export function strengthsFold(ctx, agentId, draft, { models, hasEffort }) {
const rows = ctx.strengthDrafts.has(key) ? ctx.strengthDrafts.get(key) : ctx.saved.strengths.user && ctx.saved.strengths.user[owner];
return rows && typeof rows === "object" ? rows : {};
};
const state = () => {
const list = modelList();
const base = { shipped, models: list.map((m) => m.id), hasEffort };
return { list, user: userRows(), resolved: resolveStrengths({ ...base, user: userRows() }), dflt: resolveStrengths({ ...base, user: {} }) };
};
const labelOf = (id) => {
const m = modelList().find((x) => x.id === id);
return m ? m.label || m.id : id;
};
const details = el("details", "agent-fold prefs-agents-strengths");
details.open = ctx.strengthsOpen;
details.addEventListener("toggle", () => (ctx.strengthsOpen = details.open));
details.appendChild(el("summary", null, "Strengths in the loop"));
const body = el("div", "strength-body");
details.appendChild(body);
const box = el("div", "strength-body prefs-agents-strengths");
const pillSets = [];
function setRow(word, row) {
const next = { ...userRows() };
@@ -55,86 +71,107 @@ export function strengthsFold(ctx, agentId, draft, { models, hasEffort }) {
ctx.edited();
}
function draw() {
const active = document.activeElement;
const back = active && body.contains(active) ? { word: active.closest("[data-word]")?.dataset.word, field: active.dataset.field } : null;
body.replaceChildren();
const list = modelList();
if (!list.length) {
body.appendChild(el("p", "help strength-empty", "Add a model under Models first"));
function choose(word, id) {
const { resolved, dflt } = state();
const now = resolved[word];
if (now && now.model === id) {
// Tapping the pick again clears it only where nothing ships for the word;
// with a default, putting it back is Reset's job.
if (!dflt[word]) setRow(word, null);
return;
}
const base = { shipped, models: list.map((m) => m.id), hasEffort };
const user = userRows();
const resolved = resolveStrengths({ ...base, user });
const dflt = resolveStrengths({ ...base, user: {} });
const next = { model: id };
if (hasEffort && now && now.effort) next.effort = now.effort;
setRow(word, canonical(next) === canonical(dflt[word]) ? null : next);
}
for (const word of STRENGTH_ORDER) {
const row = el("div", "strength-row");
row.dataset.word = word;
row.appendChild(el("span", "strength-word", WORDS[word]));
const model = el("select");
model.dataset.field = "model";
model.setAttribute("aria-label", `${WORDS[word]} model`);
// Nothing ships for this word: "not mapped" is a real choice. With a default,
// clearing a row is Reset's job.
if (!dflt[word]) model.appendChild(option("", "not mapped"));
for (const m of list) model.appendChild(option(m.id, m.label && m.label !== m.id ? `${m.label} (${m.id})` : m.id));
model.value = resolved[word] ? resolved[word].model : "";
model.addEventListener("change", () => {
if (!model.value) return setRow(word, null);
const next = { model: model.value };
if (hasEffort && resolved[word] && resolved[word].effort) next.effort = resolved[word].effort;
setRow(word, canonical(next) === canonical(dflt[word]) ? null : next);
});
row.appendChild(model);
if (hasEffort) {
const effort = el("select");
effort.dataset.field = "effort";
effort.setAttribute("aria-label", `${WORDS[word]} effort`);
effort.disabled = !resolved[word];
effort.appendChild(option("", "no effort"));
for (const e of EFFORTS) effort.appendChild(option(e, e));
effort.value = (resolved[word] && resolved[word].effort) || "";
effort.addEventListener("change", () => {
const next = { model: resolved[word].model };
if (effort.value) next.effort = effort.value;
setRow(word, canonical(next) === canonical(dflt[word]) ? null : next);
});
row.appendChild(effort);
function refresh() {
const active = document.activeElement;
const back = active && box.contains(active) ? active.closest("[data-word]")?.dataset.word : null;
box.replaceChildren();
const { list, user, resolved, dflt } = state();
if (!list.length) {
box.appendChild(el("p", "help strength-empty", "Add a model first, then choose which one the loop uses for each strength."));
} else {
for (const word of STRENGTH_ORDER) {
const row = el("div", "strength-row");
row.dataset.word = word;
const label = el("span", "strength-word");
label.append(wordChip(word), el("small", "help", HINTS[word]));
row.appendChild(label);
const pick = resolved[word];
row.appendChild(el("span", pick ? "strength-model" : "strength-model none", pick ? labelOf(pick.model) : "not mapped"));
if (hasEffort) {
const effort = el("select");
effort.dataset.field = "effort";
effort.setAttribute("aria-label", `${WORDS[word]} effort`);
effort.disabled = !pick;
effort.appendChild(option("", "no effort"));
for (const e of EFFORTS) effort.appendChild(option(e, e));
effort.value = (pick && pick.effort) || "";
effort.addEventListener("change", () => {
const next = { model: pick.model };
if (effort.value) next.effort = effort.value;
setRow(word, canonical(next) === canonical(dflt[word]) ? null : next);
});
row.appendChild(effort);
}
if (Object.prototype.hasOwnProperty.call(user, word)) {
const reset = el("button", "btn small ghost strength-reset", "Reset");
reset.type = "button";
reset.dataset.field = "reset";
reset.setAttribute("aria-label", `Reset ${WORDS[word]}`);
reset.addEventListener("click", () => setRow(word, null));
row.appendChild(reset);
} else if (pick) {
row.appendChild(el("span", "help strength-default", "default"));
}
box.appendChild(row);
}
if (Object.prototype.hasOwnProperty.call(user, word)) {
const reset = el("button", "btn small ghost strength-reset", "Reset");
reset.type = "button";
reset.dataset.field = "reset";
reset.setAttribute("aria-label", `Reset ${WORDS[word]}`);
reset.addEventListener("click", () => setRow(word, null));
row.appendChild(reset);
} else if (resolved[word]) {
row.appendChild(el("span", "help strength-default", "default"));
}
body.appendChild(row);
const offered = STRENGTH_ORDER.filter((w) => resolved[w]).map((w) => WORDS[w]);
box.appendChild(
el(
"p",
"help strength-offer",
offered.length ? `The loop will offer: ${offered.join(", ")}` : "The loop will not offer a strength for this agent until one is mapped."
)
);
}
for (const set of pillSets) {
const now = state().resolved;
for (const p of set.pills) p.btn.setAttribute("aria-pressed", String(Boolean(now[p.word] && now[p.word].model === set.id)));
}
const offered = STRENGTH_ORDER.filter((w) => resolved[w]).map((w) => WORDS[w]);
body.appendChild(
el(
"p",
"help strength-offer",
offered.length ? `The loop will offer: ${offered.join(", ")}` : "The loop will not offer a strength for this agent until one is mapped."
)
);
if (back) {
// A Reset that was pressed is gone with its row's change: the model select takes the focus.
const row = body.querySelector(`[data-word="${back.word}"]`);
(row?.querySelector(`[data-field="${back.field}"]`) || row?.querySelector('[data-field="model"]'))?.focus();
// A Reset that was pressed is gone with its change: the row's effort select, else its pick, takes the focus.
const row = box.querySelector(`[data-word="${back}"]`);
const target = row?.querySelector("select") || document.querySelector(`.strength-pill[data-word="${back}"][aria-pressed="true"]`);
target?.focus();
}
}
ctx.strengthsRefresh = draw;
draw();
return details;
// One model's pill set: the three words as toggle buttons, one pressed per word.
function pills(id, label) {
const wrap = el("span", "strength-pills");
wrap.setAttribute("role", "group");
wrap.setAttribute("aria-label", `Use ${label} as`);
const set = { id, pills: [] };
const now = state().resolved;
for (const word of STRENGTH_ORDER) {
const btn = el("button", "strength-pill t-" + word, WORDS[word]);
btn.type = "button";
btn.dataset.word = word;
btn.dataset.model = id;
btn.setAttribute("aria-pressed", String(Boolean(now[word] && now[word].model === id)));
btn.setAttribute("aria-label", `Use ${label} as ${WORDS[word]}`);
btn.addEventListener("click", () => choose(word, id));
set.pills.push({ btn, word });
wrap.appendChild(btn);
}
pillSets.push(set);
return wrap;
}
ctx.strengthsRefresh = refresh;
refresh();
return { box, pills, refresh };
}
@@ -1,16 +1,19 @@
// Plan2Code Web Console - the agents view's collection side.
//
// The master-detail's left column for both mounts: Preferences draws one
// pickable row per agent (name, command, found badge, its models) plus the
// v3 orchestrator placeholder; the setup page draws the same rows with their
// found/outside/missing badges and the starter templates. While no form is
// open the right pane is this module's too: the empty text, or the picked
// entry's state and way forward (Start, Use it from here, the install lines).
// The collection side for both mounts. Preferences draws a roster of cards,
// one per agent (name, command, found badge, the model each strength uses),
// and the Add agent chooser, where the starter templates are an opt-in. The
// setup page keeps its master-detail list: the same agents with their
// found/outside/missing badges and the starter templates, and a right pane that
// shows the picked entry's state and way forward (Start, Use it from here, the
// install lines).
// It only draws and listens: every fetch and every piece of state lives in
// the mount, reached through `ctx`.
import { el, copyButton } from "../../render.js";
import { summaryRows, serverStateFor, modelNames, agentId, templateDraft } from "./agents-data.js";
import { summaryRows, serverStateFor, agentId, templateDraft, HAS_EFFORT } from "./agents-data.js";
import { STRENGTH_ORDER, resolveStrengths } from "../../strengths.js";
import { wordChip } from "./agents-strengths.js";
/* ------------------------------------------------------------- badges */
@@ -26,22 +29,46 @@ export function drawBadge(badge, state) {
if (state !== "unknown") badge.classList.add(state);
}
/* --------------------------------------------------------- the prefs rows */
/* -------------------------------------------------------- the prefs cards */
// One pickable row: the whole row is the Edit button, so it carries the
// data-key and the "Edit <name>" aria-label the flows rely on.
function prefsRow(ctx, row, check) {
const r = el("button", "split-row");
// A model's name without its gloss ("Sonnet, latest Sonnet" or "Opus plan: Opus in plan mode" is cut at the first separator), so a card line stays one line.
const GLOSS = new RegExp(" " + String.fromCharCode(8212) + " |, |: ");
const shortLabel = (label) => label.split(GLOSS)[0];
// The model each strength resolves to for one row, as [word, label, effort]
// triples; empty while the strengths did not load.
function strengthLines(ctx, row) {
if (!ctx.modelsLoaded) return [];
const isCli = row.key.startsWith("cli:");
const owner = isCli ? row.command : agentId(row.key);
const resolved = resolveStrengths({
shipped: (ctx.saved.strengths.shipped && ctx.saved.strengths.shipped[owner]) || {},
user: (ctx.saved.strengths.user && ctx.saved.strengths.user[owner]) || {},
models: row.models.map((m) => m.id),
hasEffort: isCli && HAS_EFFORT.includes(owner),
});
return STRENGTH_ORDER.map((word) => {
const pick = resolved[word];
const model = pick && row.models.find((m) => m.id === pick.model);
return [word, model ? shortLabel(model.label || model.id) : null, pick && pick.effort];
});
}
// One card: the whole card is the Edit button, so it carries the data-key and
// the "Edit <name>" aria-label the flows rely on.
function agentCard(ctx, row, check) {
const r = el("button", "agent-card");
r.type = "button";
r.dataset.key = row.key;
r.setAttribute("aria-label", "Edit " + row.name);
r.setAttribute("aria-current", ctx.openKey === row.key ? "true" : "false");
r.addEventListener("click", () => ctx.pick(row.key));
r.appendChild(el("span", "row-name", row.name));
const sub = el("span", "row-sub");
sub.id = "row-sub-" + row.key;
r.setAttribute("aria-describedby", sub.id);
sub.appendChild(el("code", null, row.command));
const top = el("span", "card-top");
const who = el("span", "card-who");
const name = el("span", "row-name", row.name);
if (row.key.startsWith("agent:")) name.append(" ", el("span", "tag", "Custom"));
who.append(name, el("code", null, row.command));
top.appendChild(who);
const badge = el("span", "prefs-badge");
const known = serverStateFor(ctx.saved, row);
if (known) {
@@ -55,11 +82,22 @@ function prefsRow(ctx, row, check) {
check.push(row);
}
}
sub.appendChild(badge);
const names = modelNames(row.models);
sub.appendChild(el("span", "row-models", names.length ? `${names.length}: ${names.join(", ")}` : "None"));
r.appendChild(sub);
if (row.noneShip) r.appendChild(el("span", "help row-note", `No models ship for ${row.name} yet; open this row to add your own.`));
top.appendChild(badge);
r.appendChild(top);
const lines = strengthLines(ctx, row);
if (lines.length) {
const tiers = el("span", "card-tiers");
for (const [word, label, effort] of lines) {
const line = el("span", "card-tier");
line.append(wordChip(word), label ? el("span", null, effort ? `${label} · ${effort}` : label) : el("span", "muted", "not mapped"));
tiers.appendChild(line);
}
r.appendChild(tiers);
}
const foot = el("span", "card-foot");
foot.append(el("span", "row-models", `${row.models.length} ${row.models.length === 1 ? "model" : "models"}`), el("span", "card-edit", "Edit ›"));
r.appendChild(foot);
if (row.noneShip && !row.models.length) r.appendChild(el("span", "help row-note", `No models ship for ${row.name} yet; open this card to add your own.`));
return r;
}
@@ -120,15 +158,14 @@ export function renderSummary(ctx) {
}
} else {
const check = [];
for (const row of summaryRows(ctx.saved)) list.appendChild(prefsRow(ctx, row, check));
if (ctx.saved.templates.length) {
list.appendChild(el("div", "split-list-head", "Or start from a template"));
for (const t of ctx.saved.templates) list.appendChild(setupRow(ctx, t, "setup:" + t.name));
}
const soon = el("div", "split-row soon");
soon.append(el("span", "row-name", "v3 orchestrator"), el("span", "row-sub", "Nothing to set yet."));
list.appendChild(soon);
for (const row of summaryRows(ctx.saved)) list.appendChild(agentCard(ctx, row, check));
const ghost = el("button", "agent-card ghost");
ghost.type = "button";
ghost.append(el("span", "plus", "+"), el("b", null, "Add an agent"), el("span", "muted", "From a starter template or your own command"));
ghost.addEventListener("click", () => ctx.openChooser());
list.appendChild(ghost);
if (check.length) ctx.checkFound(check);
return;
}
if (add) list.appendChild(add);
}
@@ -227,10 +264,8 @@ export function drawSummaryPane(ctx) {
const all = [...ctx.saved.builtins, ...ctx.saved.agents];
const entry = sel && all.find((e) => "setup:" + e.id === sel);
const template = sel && !entry && ctx.saved.templates.find((t) => "setup:" + t.name === sel);
if (ctx.mode !== "setup") {
pane.appendChild(template ? templatePane(ctx, template) : el("div", "split-empty", "Pick an agent on the left to edit it here."));
return;
}
// Preferences' drawer holds nothing while no form is open.
if (ctx.mode !== "setup") return;
if (entry) {
const box = el("div", "setup-detail");
const head = el("div", "form-head");
@@ -254,3 +289,71 @@ export function drawSummaryPane(ctx) {
}
pane.appendChild(el("div", "split-empty", "Pick an agent on the left to see its state and the way forward."));
}
/* ------------------------------------------------------ the Add agent chooser */
const TEMPLATE_STATE = { ok: "Installed on this computer", missing: "Not installed yet", unknown: "" };
// The Add agent sheet: the starter templates as an opt-in, each with whether
// its command is on this computer, and a Custom agent tile for any other tool.
// A template whose command an agent already uses is shown, not offered.
export function drawChooser(ctx) {
const box = ctx.$("chooser");
box.replaceChildren();
const scrim = el("div", "chooser-scrim");
scrim.addEventListener("click", () => ctx.closeChooser());
const sheet = el("div", "chooser-sheet");
sheet.setAttribute("role", "dialog");
sheet.setAttribute("aria-labelledby", "agents-chooser-title");
const head = el("div", "chooser-head");
const title = el("h3", null, "Add an agent");
title.id = "agents-chooser-title";
const close = el("button", "btn small ghost", "Cancel");
close.type = "button";
close.addEventListener("click", () => ctx.closeChooser());
head.append(title, close);
sheet.appendChild(head);
const have = new Set([...ctx.saved.builtins, ...ctx.saved.agents].map((a) => a.command));
if (ctx.saved.templates.length) {
sheet.appendChild(el("p", "help", "Start from a ready-made setup. You can change everything afterwards."));
const tiles = el("div", "chooser-tiles");
for (const t of ctx.saved.templates) {
const done = have.has(t.command);
const tile = el("button", "chooser-tile");
tile.type = "button";
tile.dataset.template = t.name;
tile.disabled = done;
const state = el("span", "chooser-state");
state.dataset.command = t.command;
const known = ctx.templateState.get(t.command);
state.textContent = done ? "Already added" : TEMPLATE_STATE[known || "unknown"];
if (known) state.classList.add(known);
tile.append(el("b", null, t.name), el("code", null, t.command));
if (t.note) tile.appendChild(el("span", "muted", t.note));
tile.appendChild(state);
tile.addEventListener("click", () => ctx.startNew(t));
tiles.appendChild(tile);
}
sheet.appendChild(tiles);
sheet.appendChild(el("div", "chooser-or", "or"));
} else {
sheet.appendChild(el("p", "help", "Add any command-line agent: give it a name and a command, then its models."));
}
const custom = el("button", "chooser-tile wide");
custom.type = "button";
custom.dataset.template = "";
custom.append(el("b", null, "Custom agent"), el("span", "muted", "Any command-line tool. You give it a name and a command, and add its models."));
custom.addEventListener("click", () => ctx.startNew(null));
sheet.appendChild(custom);
box.append(scrim, sheet);
}
// Fills each tile's "installed" line once /agents/test has answered for its command.
export function markTemplateState(ctx, command, state) {
for (const node of ctx.$("chooser").querySelectorAll(".chooser-state")) {
if (node.dataset.command !== command || node.textContent === "Already added") continue;
node.textContent = TEMPLATE_STATE[state];
node.classList.remove("ok", "missing");
if (state !== "unknown") node.classList.add(state);
}
}