Add the agent-less setup page, a shared agent list and the split Agents & models tab

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-03 04:08:27 -08:00
1 parent c122332657
commit 33f1783979
55 files changed
+5453 -1345

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,110 @@
// Plan2Code Web Console - the agents view's pure data helpers.
//
// Everything the agents view computes without touching the page: draft keys,
// saved lookups, dirty checks, summary rows, an agent's shape on the way in
// or out. No DOM access and no imports at module scope, so the page and
// `node --test` both import this file.
// The CLIs the launcher reads a model list for, in table order (the shipped bin/agents.json list).
export const MODEL_CLIS = ["claude", "devin", "codex"];
// What the table calls each built-in, and the command it runs (the launcher's CLIS ids).
export const BUILT_IN = { claude: "Claude", devin: "Devin", codex: "Codex" };
export function emptyLists() {
return Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
}
export function newAgent() {
return { name: "", command: "", args: [], prompt: "/plan2code", bypassArgs: [], modelArgs: ["--model", "{model}"], models: [] };
}
export function normalizeAgent(agent) {
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) if (!Array.isArray(agent[key])) agent[key] = [];
return agent;
}
// A form's draft key: "cli:<cli>" for a built-in's own models, "agent:<id>"
// for an added agent, "agent:new" for one being added.
export const cliOf = (key) => key.slice("cli:".length);
export const agentId = (key) => key.slice("agent:".length);
// What a draft is checked against in `saved`: a built-in's own models for a
// cli key, a fresh newAgent for "agent:new", the added agent for "agent:<id>".
export function savedEntry(saved, key) {
if (key.startsWith("cli:")) return saved.user[cliOf(key)] || [];
if (key === "agent:new") return newAgent();
return saved.agents.find((a) => a.id === agentId(key));
}
// JSON with object keys sorted, so a label removed and typed back counts as unchanged.
export function canonical(value) {
return JSON.stringify(value, (_, v) =>
v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v
);
}
export function isDirty(saved, drafts, key) {
return drafts.has(key) && canonical(drafts.get(key)) !== canonical(savedEntry(saved, key));
}
export function nameOf(saved, drafts, key) {
if (key.startsWith("cli:")) return BUILT_IN[cliOf(key)];
const draft = drafts.get(key);
return String((draft && draft.name) || "").trim() || savedEntry(saved, key)?.name || "a new agent";
}
export function modelNames(list) {
return list.map((m) => m.label || m.id);
}
// One row per agent, in order: the built-ins, then the added agents (the
// view appends the v3 orchestrator row itself).
export function summaryRows(saved) {
return [
...MODEL_CLIS.map((cli) => ({
key: "cli:" + cli,
name: BUILT_IN[cli],
command: cli,
models: [...saved.shipped[cli], ...saved.user[cli]],
noneShip: saved.shipped[cli].length === 0,
})),
...saved.agents.map((a) => ({ key: "agent:" + a.id, name: a.name, command: a.command, models: a.models })),
];
}
// The state GET /agents already worked out for a summary row's entry:
// "ok" or "missing" as drawBadge understands them, or null when the entry
// carries no state (an older server), which falls back to a live check.
export function serverStateFor(saved, row) {
const entry = row.key.startsWith("cli:")
? saved.builtins.find((b) => b.id === cliOf(row.key))
: saved.agents.find((a) => a.id === agentId(row.key));
if (!entry || !entry.state) return null;
return entry.state === "found" ? "ok" : "missing";
}
// The list as the server wants it: blank rows and models without an id dropped.
export function cleanAgent(a) {
return {
...a,
args: a.args.filter((v) => v !== ""),
bypassArgs: a.bypassArgs.filter((v) => v !== ""),
modelArgs: a.modelArgs.filter((v) => v !== ""),
models: a.models.filter((m) => m.id),
};
}
// A template's shape as a new-agent draft, so its Use opens the same form
// a hand-typed agent gets, prefilled rather than saved behind the back.
export function templateDraft(t) {
return {
name: t.name,
command: t.command,
prompt: t.prompt || "/plan2code",
args: t.args || [],
bypassArgs: t.bypassArgs || [],
modelArgs: t.modelArgs && t.modelArgs.length ? t.modelArgs : ["--model", "{model}"],
models: [],
};
}
@@ -0,0 +1,224 @@
// Plan2Code Web Console - the agents view's per-agent form, the detail pane.
//
// 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`.
import { el } from "../../render.js";
import { listEditor } from "./agents-list-editor.js";
import { BUILT_IN, cliOf, savedEntry, isDirty } from "./agents-data.js";
function agentField(label, field, child) {
const wrap = el("div", "agent-field");
wrap.dataset.field = field;
wrap.append(el("span", null, label), child);
return wrap;
}
function agentInput(ctx, agent, key, label, placeholder, trim) {
const input = el("input");
input.value = agent[key] || "";
input.placeholder = placeholder;
input.setAttribute("aria-label", label);
input.dataset.field = key;
input.addEventListener("input", () => {
agent[key] = trim ? input.value.trim() : input.value;
ctx.edited();
});
return input;
}
// The command's Test: where it would run from. Never saves.
function agentTest(ctx, agent) {
const wrap = el("div", "prefs-agents-test");
const test = el("button", "btn small", "Test");
test.type = "button";
const result = el("span", "help agent-test-result");
result.setAttribute("role", "status");
test.addEventListener("click", async () => {
const command = String(agent.command || "").trim();
if (!command) {
result.textContent = "Type a command first.";
return;
}
result.textContent = "Looking...";
result.textContent = await ctx.testCommand(command);
});
wrap.append(test, result);
return wrap;
}
// A folded section: `<details>` whose open state lives on the mount (`which`
// is "modelsOpen" or "argsOpen") so a redraw keeps it where the person left it.
function fold(ctx, which, title, cls, kids) {
const d = el("details", cls);
d.open = ctx[which];
d.addEventListener("toggle", () => (ctx[which] = d.open));
d.append(el("summary", null, title), ...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);
}
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 })
);
return [fold(ctx, "modelsOpen", "Models", "agent-fold", [note, comes, yours])];
}
function addedFields(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 })),
agentField("Model arguments", "modelArgs", listEditor({ list: draft.modelArgs, field: "modelArgs", placeholder: "--model={model}", addLabel: "Add an argument", aria: "Model arguments", onChange: ctx.edited })),
]);
return [
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,
args,
];
}
// 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()).
function formFoot(ctx, key) {
const foot = el("div", "agent-foot prefs-agents-foot");
const save = el("button", "btn small primary prefs-agents-save", "Save");
save.type = "button";
save.addEventListener("click", () => ctx.save(key));
const discard = el("button", "btn small ghost prefs-agents-discard", "Discard");
discard.type = "button";
discard.addEventListener("click", () => ctx.discard());
const badge = el("span", "prefs-unsaved-badge", "Unsaved");
foot.append(save, discard, badge);
if (ctx.formReplace) {
const anyway = el("button", "btn small danger prefs-agents-replace", "Save anyway");
anyway.type = "button";
anyway.addEventListener("click", () => ctx.save(key, { replace: true }));
foot.append(anyway);
}
if (key.startsWith("agent:") && key !== "agent:new") {
if (ctx.confirming) {
const yes = el("button", "btn small danger", "Yes, delete");
yes.type = "button";
yes.addEventListener("click", () => ctx.deleteAgent(key));
const keep = el("button", "btn small ghost", "Keep");
keep.type = "button";
keep.addEventListener("click", () => {
ctx.confirming = false;
ctx.drawForm();
});
foot.append(el("span", "help", "Delete this agent?"), yes, keep);
} else {
const del = el("button", "btn small ghost danger prefs-agents-delete", "Delete agent");
del.type = "button";
del.addEventListener("click", () => {
ctx.confirming = true;
ctx.drawForm();
});
foot.append(del);
}
}
return foot;
}
// The Unsaved badge and the Save/Discard buttons appear only while the open
// draft differs from what is saved.
export function renderDirty(ctx, key) {
const foot = ctx.$("form").querySelector(".prefs-agents-foot");
if (!foot || key !== ctx.openKey) return;
const dirty = isDirty(ctx.saved, ctx.drafts, key);
for (const sel of [".prefs-agents-save", ".prefs-agents-discard", ".prefs-unsaved-badge"]) foot.querySelector(sel).hidden = !dirty;
}
// 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";
function formFocus(form) {
const active = document.activeElement;
if (!active || !form.contains(active)) return null;
const at = { nth: [...form.querySelectorAll(FORM_FOCUSABLE)].indexOf(active) };
if (active instanceof HTMLInputElement) Object.assign(at, { start: active.selectionStart, end: active.selectionEnd });
return at;
}
function restoreFormFocus(form, at) {
if (!at) return;
const target = form.querySelectorAll(FORM_FOCUSABLE)[at.nth];
// A button the redraw hid (Save, once saved) hands focus to the heading.
if (!target || target.closest("[hidden]")) return form.querySelector(".prefs-agents-title")?.focus();
target.focus();
if (target instanceof HTMLInputElement && at.start !== undefined) {
try {
target.setSelectionRange(at.start, at.end);
} catch {}
}
}
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 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));
head.appendChild(title);
pane.appendChild(head);
const fields = el("div", "prefs-agents-fields");
fields.append(...(key.startsWith("cli:") ? builtInFields(ctx, cliOf(key), draft) : addedFields(ctx, draft)));
pane.appendChild(fields);
if (ctx.formError) {
for (const input of pane.querySelectorAll("input")) {
if (input.dataset.field === ctx.formError.field) input.classList.add("invalid");
}
pane.appendChild(el("p", "agent-error", ctx.formError.error));
}
if (ctx.formReplace && ctx.formReplace.length) pane.appendChild(el("p", "agent-error", ctx.formReplace.join(" ")));
pane.appendChild(formFoot(ctx, key));
renderDirty(ctx, key);
restoreFormFocus(pane, focus);
}
@@ -0,0 +1,74 @@
// Plan2Code Web Console - the agents form's row-list editor (arguments and models).
//
// The shared editor behind the three argument lists (args, bypassArgs,
// modelArgs) and the models list. Text rows hold one input; model rows hold an
// id and a name for the menu. Which list it edits and how its rows look come
// from the options, so each field configures its own copy.
import { el } from "../../render.js";
// `list` is the live array being edited (strings, or {id, label?} models).
// `kind` "text" | "models". `onChange` runs after every edit, add or remove.
export function listEditor({ list, kind = "text", field = kind === "models" ? "models" : "", placeholder = "", addLabel = "Add", optionalName = true, aria = "", onChange = () => {} }) {
const box = el("div", "agent-rows");
box.dataset.field = field;
const draw = () => {
box.replaceChildren();
list.forEach((item, i) => {
const row = el("div", kind === "models" ? "agent-row model" : "agent-row");
const remove = el("button", "btn small ghost", "Remove");
remove.type = "button";
remove.addEventListener("click", () => {
list.splice(i, 1);
draw();
onChange();
});
if (kind === "models") {
const id = el("input");
id.value = item.id || "";
id.placeholder = optionalName ? "Model id, for {model}" : "Model id";
id.setAttribute("aria-label", "Model id");
id.dataset.field = "models";
const label = el("input");
label.value = item.label || "";
label.placeholder = optionalName ? "Name shown in the menu (optional)" : "Name shown in the menu";
label.setAttribute("aria-label", "Name shown in the menu");
label.dataset.field = "models";
id.addEventListener("input", () => {
item.id = id.value.trim();
onChange();
});
label.addEventListener("input", () => {
const text = label.value.trim();
if (text || !optionalName) item.label = text;
else delete item.label;
onChange();
});
row.append(id, label, remove);
} else {
const input = el("input");
input.value = item;
input.placeholder = placeholder;
input.setAttribute("aria-label", aria);
input.dataset.field = field;
input.addEventListener("input", () => {
list[i] = input.value.trim();
onChange();
});
row.append(input, remove);
}
box.appendChild(row);
});
const add = el("button", "btn small ghost", addLabel);
add.type = "button";
add.addEventListener("click", () => {
list.push(kind === "models" ? (optionalName ? { id: "" } : { id: "", label: "" }) : "");
draw();
onChange();
box.querySelector(".agent-row:last-of-type input")?.focus();
});
box.appendChild(add);
};
draw();
return box;
}
@@ -0,0 +1,256 @@
// 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).
// 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";
/* ------------------------------------------------------------- badges */
export const BADGES = {
ok: "Found",
missing: "Not found on PATH",
unknown: "Not checked",
};
export function drawBadge(badge, state) {
badge.textContent = BADGES[state];
badge.classList.remove("ok", "missing");
if (state !== "unknown") badge.classList.add(state);
}
/* --------------------------------------------------------- the prefs rows */
// 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");
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 badge = el("span", "prefs-badge");
const known = serverStateFor(ctx.saved, row);
if (known) {
ctx.found.set(row.key, { command: row.command, state: known });
drawBadge(badge, known);
} else {
const last = ctx.found.get(row.key);
if (last && last.command === row.command) drawBadge(badge, last.state);
else {
badge.textContent = "Checking...";
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.`));
return r;
}
/* --------------------------------------------------------- the setup rows */
// The badge a setup row's state gets: the glanceable half, with the pane
// beside it saying what the state means and what can be done about it.
function setupStateBadge(entry) {
const badge = el("span", "prefs-badge");
if (entry.state === "found") {
badge.textContent = "Found";
badge.classList.add("ok");
} else if (entry.state === "outside") {
badge.textContent = "Found outside PATH";
badge.classList.add("missing");
} else if (entry.state === "missing") {
badge.textContent = "Not found";
badge.classList.add("missing");
} else {
badge.textContent = "Not checked";
}
return badge;
}
// A pickable setup row: selecting it fills the pane with the entry's state,
// not a form (custom agents get an Edit in that pane).
function setupRow(ctx, entry, key, badgeFor) {
const r = el("button", "split-row");
r.type = "button";
r.dataset.key = key;
r.setAttribute("aria-current", ctx.setupSel === key ? "true" : "false");
r.addEventListener("click", () => ctx.pickSetup(key));
r.appendChild(el("span", "row-name", entry.name || entry.id));
const sub = el("span", "row-sub");
sub.appendChild(el("code", null, entry.command));
if (badgeFor) sub.appendChild(badgeFor(entry));
r.appendChild(sub);
return r;
}
/* ---------------------------------------------------------- the list itself */
// The left column, whichever the mode: rows, the placeholder or templates,
// then the scaffold's Add agent button pinned last (grabbed before the list
// is cleared: a live query for it after replaceChildren finds nothing).
export function renderSummary(ctx) {
const list = ctx.$("table");
const add = ctx.$("add");
list.replaceChildren();
if (ctx.mode === "setup") {
const cli = ctx.forCli();
const builtins = [...ctx.saved.builtins].sort((a, b) => (a.id === cli ? -1 : b.id === cli ? 1 : 0));
for (const b of builtins) list.appendChild(setupRow(ctx, b, "setup:" + b.id, setupStateBadge));
for (const a of ctx.saved.agents) list.appendChild(setupRow(ctx, a, "setup:" + a.id, setupStateBadge));
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));
}
} 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);
if (check.length) ctx.checkFound(check);
}
if (add) list.appendChild(add);
}
/* ------------------------------------------------ the pane while nothing is open */
// How the person puts the found folder on PATH themselves, for the OS their
// browser reports. The server already knows where the agent is; this is the
// alternative to letting Plan2Code save that location for it.
function pathNote(folder) {
const os = navigator.platform || navigator.userAgent || "";
if (/win/i.test(os)) {
return "Or add its folder to your PATH: Settings > System > About > Advanced system settings > Environment Variables.";
}
if (/mac/i.test(os)) return `Or add its folder to PATH in ~/.zshrc: export PATH="${folder}:$PATH"`;
return `Or add its folder to PATH in ~/.bashrc: export PATH="${folder}:$PATH"`;
}
// The state area of a picked setup entry: the badge, what the state means,
// and the one thing to do about it (Start, Use it from here, the install lines).
function setupStateArea(ctx, entry) {
const area = el("div", "setup-agent-state");
const badge = setupStateBadge(entry);
if (entry.state === "found") {
const line = el("p", "setup-agent-line");
line.appendChild(badge);
if (entry.path) line.append(" ", el("span", "help", entry.path));
area.appendChild(line);
// A session opened for one CLI only offers that one's Start.
if (ctx.onStart && (!ctx.forCli() || entry.id === ctx.forCli())) {
const start = el("button", "btn small primary", "Start with this agent");
start.type = "button";
start.addEventListener("click", () => ctx.onStart(entry));
area.appendChild(start);
}
} else if (entry.state === "outside") {
const line = el("p", "setup-agent-line");
line.append(badge, ` Found at ${entry.path || ""}, but not on PATH`);
area.appendChild(line);
const use = el("button", "btn small", "Use it from here");
use.type = "button";
use.addEventListener("click", () => ctx.useFromHere(entry));
area.appendChild(use);
area.appendChild(el("p", "help", entry.folder ? pathNote(entry.folder) : "Or add its folder to your PATH yourself."));
} else {
area.appendChild(badge);
if (entry.state === "missing") {
for (const inst of Array.isArray(entry.install) ? entry.install : []) {
const d = el("div", "setup-install");
d.append(el("span", null, inst.label), el("code", null, inst.run));
if (inst.note) d.appendChild(el("span", "help", inst.note));
d.appendChild(copyButton(inst.run));
area.appendChild(d);
}
if (entry.installUrl) {
const a = el("a", null, "Install page");
a.href = entry.installUrl;
a.target = "_blank";
a.rel = "noopener";
area.appendChild(a);
}
}
}
return area;
}
// A template's pane half: its name, command and note with a Use that opens
// the new-agent form prefilled, shared by both mounts.
function templatePane(ctx, template) {
const box = el("div", "setup-detail");
const head = el("div", "form-head");
const title = el("h3", "prefs-agents-title");
title.append(el("span", null, template.name), el("code", null, template.command));
head.appendChild(title);
box.appendChild(head);
if (template.note) box.appendChild(el("p", "help", template.note));
const use = el("button", "btn small", "Use this template");
use.type = "button";
use.addEventListener("click", () => {
// Cloned: the form edits the draft in place, and saved.templates is
// the server's copy the next load draws from.
ctx.drafts.set("agent:new", structuredClone(templateDraft(template)));
ctx.pick("agent:new");
});
box.appendChild(use);
return box;
}
// The detail pane with no form open: the picked entry's state and way
// forward, a template's note and Use, or the empty text. In Preferences a
// template row drives the same pane; every other row opens a form.
export function drawSummaryPane(ctx) {
const pane = ctx.$("form");
pane.replaceChildren();
const sel = ctx.setupSel;
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;
}
if (entry) {
const box = el("div", "setup-detail");
const head = el("div", "form-head");
const title = el("h3", "prefs-agents-title");
title.append(el("span", null, entry.name || entry.id), el("code", null, entry.command));
head.appendChild(title);
box.append(head, setupStateArea(ctx, entry));
if (ctx.saved.agents.includes(entry)) {
const edit = el("button", "btn small", "Edit");
edit.type = "button";
edit.setAttribute("aria-label", "Edit " + (entry.name || entry.id));
edit.addEventListener("click", () => ctx.pick("agent:" + entry.id));
box.appendChild(edit);
}
pane.appendChild(box);
return;
}
if (template) {
pane.appendChild(templatePane(ctx, template));
return;
}
pane.appendChild(el("div", "split-empty", "Pick an agent on the left to see its state and the way forward."));
}
@@ -66,7 +66,7 @@ export function openPrefs(tab) {
}
// The unsaved prompt on screen: { resolve, promise, from }, or null. `from`
// is what had focus when it asked (the tab, Close, Back to summary, a field).
// is what had focus when it asked (the tab, Close, another agent's row, a field).
let asking = null;
// Everything in the dialog but the prompt, kept out of reach while it asks.
@@ -85,7 +85,7 @@ function endAsking(go) {
}
// Before anything leaves an agent form with an unsaved edit (Close, Esc, a
// backdrop click, another tab, Back to summary): Save, Discard or Keep
// backdrop click, another tab, another agent's row): Save, Discard or Keep
// editing, asked inside the dialog. Resolves true when it may go on.
export function confirmUnsaved() {
if (!hooks.hasUnsaved()) return Promise.resolve(true);
+182
View File
@@ -0,0 +1,182 @@
// Plan2Code Web Console - the agent-less setup screen: pick or install an
// agent, then hand the session to it. Only defines.
//
// `plan2code` opens this page when no agent can run. The list it draws is the
// same agents view User Preferences drives (mountAgentsView, handed in by
// core.js because a screen never imports a screen), in its "setup" mode: a
// row per agent with its found state and the one thing to do about it.
// Start posts the pick as a session action the waiting launcher collects;
// the new agent's console then calls /handover, which sends this page the
// `move` event that carries it across. The grace line only shows if that
// move never comes.
import { agentFound, framed } from "../app-bridge.js";
import { el } from "../render.js";
import { hooks, page, redraw, saveNow } from "../state.js";
const $ = (id) => document.getElementById(id);
// The screen, its mounted agents view, and the start it is waiting on. All
// module-level because renderMain clears the column every pass: re-attaching
// the SAME root keeps the DOM, the open form and every typed character.
let root = null;
let view = null;
let moved = false;
let graceTimer = null;
// Once the grace wait has ended the line stays drawn: a redraw rebuilds the
// pane from this flag rather than the element.
let graceShown = false;
// How long the starting pane waits for the `move` event before it points at
// the terminal. Overridable in tests through window.__P2C_SETUP_GRACE_MS.
const GRACE_MS = () => Number(window.__P2C_SETUP_GRACE_MS) || 120000;
// The skill's own Planny acting out "setup", cloned from the template in
// index.html so the drawing stays markup; the dock's Planny is the fallback.
function setupStage() {
const stage = el("div", "setup-stage");
const art = $("start-poses")?.content.querySelector('[data-pose="setup"]');
if (art) stage.appendChild(art.cloneNode(true));
else {
const bot = $("planny")?.cloneNode(true);
if (bot) {
bot.removeAttribute("id");
stage.appendChild(bot);
}
}
return stage;
}
// The pick is sent: the launcher turns it into a session that hands this
// tab over. `entry` is the agent row's object ({ id, name, ... }).
async function onStart(entry) {
const label = entry.name || entry.id;
page.local.setupStart = { id: entry.id, label, at: Date.now() };
saveNow();
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [{ i: "__start", type: "start", agent: entry.id }], reply: "Start with " + label }),
});
if (!res.ok) throw new Error("refused");
} catch {
// The send never landed, so the wait never starts: put the list back.
delete page.local.setupStart;
saveNow();
hooks.banner("That did not go through, but the console is still up. Nothing was lost, try again.", "warn");
redraw();
return;
}
redraw();
armGrace();
}
// The grace wait for the `move` event: the new session should take this tab
// over itself, and only a wait that ends unmoved earns the terminal hint.
function armGrace() {
clearTimeout(graceTimer);
graceTimer = setTimeout(() => {
graceTimer = null;
if (moved || !page.local.setupStart) return;
graceShown = true;
for (const note of document.querySelectorAll(".setup-no-page, .setup-back")) note.hidden = false;
}, GRACE_MS());
}
// The `move` event reached the page (core.js follows the url itself); this
// only stands the grace wait down so the hint can never appear mid-handover.
export function setupMoved(url) {
moved = true;
clearTimeout(graceTimer);
graceTimer = null;
}
// The pick-list pane, built once and re-attached every render. mountAgents
// is core.js's copy of mountAgentsView (a screen never imports a screen), so
// a bare import under a test simply leaves the list unmounted.
function buildRoot(mountAgents) {
const box = el("div", "setup-screen");
box.appendChild(setupStage());
box.appendChild(el("p", "card-kicker", "Agent setup"));
box.appendChild(el("h2", null, "No agent yet"));
box.appendChild(
el(
"p",
"help",
"Plan2Code runs your AI agent for you, but it could not find one on this computer. Pick one below, or install one and press Check again."
)
);
const agents = el("div", "setup-agents");
box.appendChild(agents);
const actions = el("div", "setup-actions");
const again = el("button", "btn small", "Check again");
again.type = "button";
again.addEventListener("click", () => view?.load());
actions.appendChild(again);
box.appendChild(actions);
if (mountAgents) {
// The setup page has no unsaved prompt of its own: picking a row is
// always free. The pick itself, not the dialog, is what can be lost.
view = mountAgents(agents, {
mode: "setup",
// A getter, not a snapshot: use-path on the asked-for built-in rewrites
// state.setup.forCli to the saved id, and the Start gate must see it.
forCli: () => (page.S && page.S.setup && page.S.setup.forCli) || null,
// In the app's window there is no waiting launcher to Start for: the
// app picks the found agent on its own launch card instead, and hears
// of it through agent-found.
onStart: framed() ? null : onStart,
onFound: framed() ? (entry) => agentFound(entry.id) : null,
confirmUnsaved: () => Promise.resolve(true),
});
view.wire();
view.load();
}
return box;
}
// The waiting pane: same bones as the starting screens, plus the hint the
// grace timer reveals if the new session never calls back.
function startingPane(started) {
const pane = el("div", "launching setup-starting");
pane.appendChild(setupStage());
pane.appendChild(el("p", "card-kicker", "On it"));
pane.appendChild(el("h2", "launch-title", `Starting ${started.label}…`));
pane.appendChild(el("p", "launch-hint", "This page moves to your session the moment it opens. No need to touch anything."));
const noPage = el("p", "help setup-no-page", `${started.label} did not open a page. Look at the terminal where you ran plan2code.`);
noPage.hidden = !graceShown;
pane.appendChild(noPage);
// A wait that died unmoved should not park the page on "Starting" forever:
// once the grace hint is up, the way back to the pick list shows beside it.
const back = el("button", "btn small setup-back", "Show the agent list again");
back.type = "button";
back.hidden = !graceShown;
back.addEventListener("click", () => {
delete page.local.setupStart;
graceShown = false;
saveNow();
redraw();
});
pane.appendChild(back);
return pane;
}
// The agent-less session's whole main column. The root is persistent rather
// than drawn each pass, so an in-progress form survives every re-render.
export function renderSetup(main, mountAgents) {
const started = page.local.setupStart;
if (started) {
// A reload mid-wait starts the wait over: the move may have gone unheard
// while the page was down, and the hint is its fallback.
if (!graceTimer && !moved && !graceShown) armGrace();
main.appendChild(startingPane(started));
return;
}
if (graceTimer) {
clearTimeout(graceTimer);
graceTimer = null;
}
if (!root) root = buildRoot(mountAgents);
main.appendChild(root);
}