mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-17 20:51:19 -08:00
Update the web console server, screens, help, prefs and loop setup, with matching page and logic suites
AI Assisted
This commit is contained in:
1 parent
2468027a5a
commit
8e34bf1005
119 files changed
+9957
-3728
No files matched your search
@@ -0,0 +1,713 @@
|
||||
// Plan2Code Web Console - User Preferences' Agents & models tab.
|
||||
//
|
||||
// A summary table of every agent (the built-in CLIs, the ones the person
|
||||
// added, and a row kept for the v3 orchestrator) whose Edit opens that agent's
|
||||
// full form. 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.
|
||||
|
||||
import { el } from "../render.js";
|
||||
import { hooks } from "../state.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// The CLIs the launcher reads a model list for, in table order (routes.mjs MODEL_CLIS).
|
||||
const MODEL_CLIS = ["claude", "devin", "codex"];
|
||||
|
||||
// What the table calls each built-in, and the command it runs (the launcher's CLIS ids).
|
||||
const BUILT_IN = { claude: "Claude", devin: "Devin", codex: "Codex" };
|
||||
|
||||
// The last server reply for each list. Unknown keys on an agent ride along untouched.
|
||||
let saved = { agents: [], user: emptyLists(), shipped: emptyLists() };
|
||||
|
||||
// At most one per form being edited: "cli:<cli>" for a built-in's own models,
|
||||
// "agent:<id>" for an added agent, "agent:new" for one being added.
|
||||
const drafts = new Map();
|
||||
|
||||
// The form on screen (a drafts key), or null while the summary shows.
|
||||
let openKey = null;
|
||||
|
||||
// The server's complaint about the open form, { field, error }, and a 409's
|
||||
// warnings while Save anyway is on offer.
|
||||
let formError = null;
|
||||
let formReplace = null;
|
||||
|
||||
// Delete agent waiting for its second click; the arguments fold's state, kept across redraws.
|
||||
let confirming = false;
|
||||
let argsOpen = false;
|
||||
|
||||
// The badge each summary row last showed, by row key: { command, state }.
|
||||
const found = new Map();
|
||||
|
||||
// Each open of the tab loads afresh: only the newest load's answers are drawn.
|
||||
let loadSeq = 0;
|
||||
|
||||
function emptyLists() {
|
||||
return Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
|
||||
}
|
||||
|
||||
// Whether the status line says "Deleted.", which the next form opened clears
|
||||
// (load warnings stay until the next open).
|
||||
let deletedNote = false;
|
||||
|
||||
function setAgentsStatus(text, isError, { deleted = false } = {}) {
|
||||
const status = $("agents-status");
|
||||
status.textContent = text;
|
||||
status.classList.toggle("error", Boolean(isError));
|
||||
deletedNote = deleted;
|
||||
}
|
||||
|
||||
function newAgent() {
|
||||
return { name: "", command: "", args: [], prompt: "/plan2code", bypassArgs: [], modelArgs: ["--model", "{model}"], models: [] };
|
||||
}
|
||||
|
||||
function normalizeAgent(agent) {
|
||||
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) if (!Array.isArray(agent[key])) agent[key] = [];
|
||||
return agent;
|
||||
}
|
||||
|
||||
const cliOf = (key) => key.slice("cli:".length);
|
||||
const agentId = (key) => key.slice("agent:".length);
|
||||
|
||||
function savedEntry(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.
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
function isDirty(key) {
|
||||
return drafts.has(key) && canonical(drafts.get(key)) !== canonical(savedEntry(key));
|
||||
}
|
||||
|
||||
function nameOf(key) {
|
||||
if (key.startsWith("cli:")) return BUILT_IN[cliOf(key)];
|
||||
const draft = drafts.get(key);
|
||||
return String((draft && draft.name) || "").trim() || savedEntry(key)?.name || "a new agent";
|
||||
}
|
||||
|
||||
const modelNames = (list) => list.map((m) => m.label || m.id);
|
||||
|
||||
/* ------------------------------------------------------------- summary */
|
||||
|
||||
// One row per agent, in order: the built-ins, the added agents, the orchestrator.
|
||||
function summaryRows() {
|
||||
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 })),
|
||||
];
|
||||
}
|
||||
|
||||
function renderSummary() {
|
||||
const body = $("agents-table").tBodies[0];
|
||||
body.replaceChildren();
|
||||
const check = [];
|
||||
for (const row of summaryRows()) {
|
||||
const tr = el("tr");
|
||||
tr.dataset.key = row.key;
|
||||
const name = el("td", "prefs-agents-name");
|
||||
name.append(el("span", null, row.name), el("code", null, row.command));
|
||||
if (row.noneShip) name.append(el("span", "help", `No models ship for ${row.name} yet; add your own in Edit.`));
|
||||
const models = el("td", "prefs-agents-models");
|
||||
const names = modelNames(row.models);
|
||||
models.textContent = names.length ? `${names.length}: ${names.join(", ")}` : "None";
|
||||
const badge = el("span", "prefs-badge");
|
||||
const last = found.get(row.key);
|
||||
if (last && last.command === row.command) drawBadge(badge, last.state);
|
||||
else {
|
||||
badge.textContent = "Checking...";
|
||||
check.push(row);
|
||||
}
|
||||
const edit = el("button", "btn small", "Edit");
|
||||
edit.type = "button";
|
||||
edit.setAttribute("aria-label", "Edit " + row.name);
|
||||
edit.addEventListener("click", () => openForm(row.key));
|
||||
const editCell = el("td", "prefs-agents-edit");
|
||||
editCell.append(edit);
|
||||
const badgeCell = el("td");
|
||||
badgeCell.append(badge);
|
||||
tr.append(name, models, badgeCell, editCell);
|
||||
body.appendChild(tr);
|
||||
}
|
||||
const soon = el("tr", "prefs-agents-soon");
|
||||
const soonName = el("td", "prefs-agents-name");
|
||||
soonName.append(el("span", null, "v3 orchestrator"), el("span", "help", "Nothing to set yet."));
|
||||
soon.append(soonName, el("td", "prefs-agents-models"), el("td"), el("td"));
|
||||
body.appendChild(soon);
|
||||
if (check.length) checkFound(check, loadSeq);
|
||||
}
|
||||
|
||||
const BADGES = {
|
||||
ok: "Found",
|
||||
missing: "Not found on PATH",
|
||||
unknown: "Not checked",
|
||||
};
|
||||
|
||||
function drawBadge(badge, state) {
|
||||
badge.textContent = BADGES[state];
|
||||
badge.classList.remove("ok", "missing");
|
||||
if (state !== "unknown") badge.classList.add(state);
|
||||
}
|
||||
|
||||
// Whether each row's command is on PATH, all at once. /agents/test only
|
||||
// resolves the command and never runs it.
|
||||
async function checkFound(rows, seq) {
|
||||
await Promise.all(
|
||||
rows.map(async (row) => {
|
||||
let state = "unknown";
|
||||
try {
|
||||
const res = await fetch("/agents/test", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ command: row.command }),
|
||||
});
|
||||
if (res.ok) state = (await res.json()).found ? "ok" : "missing";
|
||||
} catch {}
|
||||
if (seq !== loadSeq) return;
|
||||
found.set(row.key, { command: row.command, state });
|
||||
const badge = $("agents-table").querySelector(`tr[data-key="${CSS.escape(row.key)}"] .prefs-badge`);
|
||||
if (badge) drawBadge(badge, state);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- the form */
|
||||
|
||||
function showSummary(on) {
|
||||
$("agents-table").hidden = !on;
|
||||
$("agents-add").hidden = !on;
|
||||
$("agents-intro").hidden = !on;
|
||||
$("agents-form").hidden = on;
|
||||
}
|
||||
|
||||
function openForm(key) {
|
||||
if (deletedNote) setAgentsStatus("", false);
|
||||
openKey = key;
|
||||
formError = null;
|
||||
formReplace = null;
|
||||
confirming = false;
|
||||
argsOpen = key === "agent:new";
|
||||
if (!drafts.has(key)) drafts.set(key, structuredClone(key === "agent:new" ? newAgent() : savedEntry(key)));
|
||||
showSummary(false);
|
||||
drawForm();
|
||||
$("agents-form").querySelector("input")?.focus();
|
||||
}
|
||||
|
||||
// Back on the summary, focus goes to the row just left (its Edit), or to Add
|
||||
// agent when that row is gone (a new agent not saved, one just deleted).
|
||||
function closeForm() {
|
||||
const left = openKey;
|
||||
if (openKey) drafts.delete(openKey);
|
||||
openKey = null;
|
||||
formError = null;
|
||||
formReplace = null;
|
||||
confirming = false;
|
||||
$("agents-form").replaceChildren();
|
||||
showSummary(true);
|
||||
renderSummary();
|
||||
const row = left && $("agents-table").querySelector(`tr[data-key="${CSS.escape(left)}"] .prefs-agents-edit button`);
|
||||
(row || $("agents-add")).focus();
|
||||
}
|
||||
|
||||
function edited() {
|
||||
if (openKey) renderDirty(openKey);
|
||||
}
|
||||
|
||||
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(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;
|
||||
edited();
|
||||
});
|
||||
return input;
|
||||
}
|
||||
|
||||
// A list of text rows (arguments), with Remove on each and an Add under them.
|
||||
function agentArgsEditor(agent, key, label, placeholder, addLabel) {
|
||||
const box = el("div", "agent-rows");
|
||||
box.dataset.field = key;
|
||||
const draw = () => {
|
||||
box.replaceChildren();
|
||||
agent[key].forEach((value, i) => {
|
||||
const row = el("div", "agent-row");
|
||||
const input = el("input");
|
||||
input.value = value;
|
||||
input.placeholder = placeholder;
|
||||
input.setAttribute("aria-label", label);
|
||||
input.dataset.field = key;
|
||||
input.addEventListener("input", () => {
|
||||
agent[key][i] = input.value.trim();
|
||||
edited();
|
||||
});
|
||||
const remove = el("button", "btn small ghost", "Remove");
|
||||
remove.type = "button";
|
||||
remove.addEventListener("click", () => {
|
||||
agent[key].splice(i, 1);
|
||||
draw();
|
||||
edited();
|
||||
});
|
||||
row.append(input, remove);
|
||||
box.appendChild(row);
|
||||
});
|
||||
const add = el("button", "btn small ghost", addLabel);
|
||||
add.type = "button";
|
||||
add.addEventListener("click", () => {
|
||||
agent[key].push("");
|
||||
draw();
|
||||
edited();
|
||||
box.querySelector(".agent-row:last-of-type input")?.focus();
|
||||
});
|
||||
box.appendChild(add);
|
||||
};
|
||||
draw();
|
||||
return agentField(label, key, box);
|
||||
}
|
||||
|
||||
// A models list: an id and a name for the menu on each row. An added agent's
|
||||
// rows drop a blank name; a built-in's keep it, as models.json does.
|
||||
function agentModelsEditor(list, { label: fieldLabel = "Models", optionalName = true } = {}) {
|
||||
const box = el("div", "agent-rows");
|
||||
box.dataset.field = "models";
|
||||
const draw = () => {
|
||||
box.replaceChildren();
|
||||
list.forEach((m, i) => {
|
||||
const row = el("div", "agent-row model");
|
||||
const id = el("input");
|
||||
id.value = m.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 = m.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";
|
||||
const remove = el("button", "btn small ghost", "Remove");
|
||||
remove.type = "button";
|
||||
id.addEventListener("input", () => {
|
||||
m.id = id.value.trim();
|
||||
edited();
|
||||
});
|
||||
label.addEventListener("input", () => {
|
||||
const text = label.value.trim();
|
||||
if (text || !optionalName) m.label = text;
|
||||
else delete m.label;
|
||||
edited();
|
||||
});
|
||||
remove.addEventListener("click", () => {
|
||||
list.splice(i, 1);
|
||||
draw();
|
||||
edited();
|
||||
});
|
||||
row.append(id, label, remove);
|
||||
box.appendChild(row);
|
||||
});
|
||||
const add = el("button", "btn small ghost", "Add a model");
|
||||
add.type = "button";
|
||||
add.addEventListener("click", () => {
|
||||
list.push(optionalName ? { id: "" } : { id: "", label: "" });
|
||||
draw();
|
||||
edited();
|
||||
box.querySelector(".agent-row:last-of-type input")?.focus();
|
||||
});
|
||||
box.appendChild(add);
|
||||
};
|
||||
draw();
|
||||
return agentField(fieldLabel, "models", box);
|
||||
}
|
||||
|
||||
// The command's Test: where it would run from. Never saves.
|
||||
function agentTest(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...";
|
||||
try {
|
||||
const res = await fetch("/agents/test", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ command }),
|
||||
});
|
||||
const body = await res.json();
|
||||
if (!res.ok) result.textContent = body.error || "Could not test.";
|
||||
else result.textContent = body.found ? "Found at " + body.path : "Not found on PATH";
|
||||
} catch {
|
||||
result.textContent = "Could not test.";
|
||||
}
|
||||
});
|
||||
wrap.append(test, result);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function builtInFields(cli, draft) {
|
||||
const shipped = el("div", "models-list prefs-agents-shipped");
|
||||
shipped.setAttribute("aria-label", "Comes with Plan2Code");
|
||||
for (const m of 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 <id></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 (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.`));
|
||||
return [note, comes, agentModelsEditor(draft, { label: "Models you added", optionalName: false })];
|
||||
}
|
||||
|
||||
function addedFields(draft) {
|
||||
const command = agentField("Command", "command", agentInput(draft, "command", "Command", "Program to run, such as myagent", true));
|
||||
command.append(agentTest(draft));
|
||||
const fold = el("details", "prefs-agents-args");
|
||||
fold.open = argsOpen;
|
||||
fold.addEventListener("toggle", () => (argsOpen = fold.open));
|
||||
fold.append(
|
||||
el("summary", null, "Command-line arguments"),
|
||||
agentArgsEditor(draft, "args", "Arguments", "--message={prompt}", "Add an argument"),
|
||||
agentArgsEditor(draft, "bypassArgs", "Bypass arguments", "--yes-always", "Add an argument"),
|
||||
agentArgsEditor(draft, "modelArgs", "Model arguments", "--model={model}", "Add an argument"),
|
||||
);
|
||||
return [
|
||||
agentField("Name", "name", agentInput(draft, "name", "Name", "Name shown in the menu", true)),
|
||||
command,
|
||||
agentField("Start prompt", "prompt", agentInput(draft, "prompt", "Start prompt", "/plan2code (blank starts with nothing typed)", false)),
|
||||
agentModelsEditor(draft.models),
|
||||
fold,
|
||||
];
|
||||
}
|
||||
|
||||
// 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(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", () => saveForm(key));
|
||||
const discard = el("button", "btn small ghost prefs-agents-discard", "Discard");
|
||||
discard.type = "button";
|
||||
discard.addEventListener("click", () => discardOpen());
|
||||
const badge = el("span", "prefs-unsaved-badge", "Unsaved");
|
||||
foot.append(save, discard, badge);
|
||||
if (formReplace) {
|
||||
const anyway = el("button", "btn small danger prefs-agents-replace", "Save anyway");
|
||||
anyway.type = "button";
|
||||
anyway.addEventListener("click", () => saveForm(key, { replace: true }));
|
||||
foot.append(anyway);
|
||||
}
|
||||
if (key.startsWith("agent:") && key !== "agent:new") {
|
||||
if (confirming) {
|
||||
const yes = el("button", "btn small danger", "Yes, delete");
|
||||
yes.type = "button";
|
||||
yes.addEventListener("click", () => deleteAgent(key));
|
||||
const keep = el("button", "btn small ghost", "Keep");
|
||||
keep.type = "button";
|
||||
keep.addEventListener("click", () => {
|
||||
confirming = false;
|
||||
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", () => {
|
||||
confirming = true;
|
||||
drawForm();
|
||||
});
|
||||
foot.append(del);
|
||||
}
|
||||
}
|
||||
return foot;
|
||||
}
|
||||
|
||||
function renderDirty(key) {
|
||||
const foot = $("agents-form").querySelector(".prefs-agents-foot");
|
||||
if (!foot || key !== openKey) return;
|
||||
const dirty = isDirty(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 {}
|
||||
}
|
||||
}
|
||||
|
||||
function drawForm() {
|
||||
const form = $("agents-form");
|
||||
const key = openKey;
|
||||
const draft = drafts.get(key);
|
||||
const focus = formFocus(form);
|
||||
form.replaceChildren();
|
||||
const back = el("button", "btn small ghost prefs-agents-back", "Back to summary");
|
||||
back.type = "button";
|
||||
back.addEventListener("click", async () => {
|
||||
if (await hooks.confirmUnsaved()) closeForm();
|
||||
});
|
||||
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(key).name));
|
||||
const fields = el("div", "prefs-agents-fields");
|
||||
fields.append(...(key.startsWith("cli:") ? builtInFields(cliOf(key), draft) : addedFields(draft)));
|
||||
form.append(back, title, fields);
|
||||
if (formError) {
|
||||
for (const input of form.querySelectorAll("input")) {
|
||||
if (input.dataset.field === formError.field) input.classList.add("invalid");
|
||||
}
|
||||
form.append(el("p", "agent-error", formError.error));
|
||||
}
|
||||
if (formReplace) form.append(el("p", "agent-error", formReplace.join(" ")));
|
||||
form.append(formFoot(key));
|
||||
renderDirty(key);
|
||||
restoreFormFocus(form, focus);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- saving */
|
||||
|
||||
// The list as the server wants it: blank rows and models without an id dropped.
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
async function postJson(url, payload) {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { res, body: await res.json() };
|
||||
}
|
||||
|
||||
// The form's foot, for the Saved mark (or the error in its place).
|
||||
const formMark = (result) => hooks.markSaved($("agents-form").querySelector(".prefs-agents-foot"), result);
|
||||
|
||||
// Fresh from what was just saved: the form redraws on a clean draft.
|
||||
function savedAs(key) {
|
||||
drafts.delete(openKey);
|
||||
openKey = key;
|
||||
drafts.set(key, structuredClone(savedEntry(key)));
|
||||
formError = null;
|
||||
formReplace = null;
|
||||
drawForm();
|
||||
}
|
||||
|
||||
async function saveModelsFor(cli) {
|
||||
const sent = drafts.get("cli:" + cli).filter((m) => m.id);
|
||||
try {
|
||||
const { res, body } = await postJson("/models", { models: { ...saved.user, [cli]: sent } });
|
||||
if (!res.ok) {
|
||||
formMark({ ok: false, error: body.error || "Could not save." });
|
||||
return false;
|
||||
}
|
||||
saved.user[cli] = (body.user && body.user[cli]) || sent;
|
||||
} catch {
|
||||
formMark({ ok: false, error: "Could not save." });
|
||||
return false;
|
||||
}
|
||||
savedAs("cli:" + cli);
|
||||
formMark({ ok: true, text: "Saved. Restart plan2code to use it." });
|
||||
return true;
|
||||
}
|
||||
|
||||
async function saveAgentFor(key, { replace = false } = {}) {
|
||||
const draft = drafts.get(key);
|
||||
const isNew = key === "agent:new";
|
||||
if (isNew && (!String(draft.name || "").trim() || !String(draft.command || "").trim())) {
|
||||
formError = { field: String(draft.name || "").trim() ? "command" : "name", error: "Give it a name and a command first." };
|
||||
drawForm();
|
||||
return false;
|
||||
}
|
||||
const at = isNew ? saved.agents.length : saved.agents.findIndex((a) => a.id === agentId(key));
|
||||
const agents = saved.agents.map((a) => cleanAgent(a));
|
||||
agents.splice(at, isNew ? 0 : 1, cleanAgent(draft));
|
||||
try {
|
||||
const { res, body } = await postJson("/agents", replace ? { agents, replace: true } : { agents });
|
||||
if (res.status === 409) {
|
||||
formError = { field: null, error: body.error || "Not saved." };
|
||||
formReplace = Array.isArray(body.warnings) ? body.warnings : [];
|
||||
drawForm();
|
||||
return false;
|
||||
}
|
||||
if (!res.ok) {
|
||||
formError = { field: body.index === at ? body.field : null, error: body.error || "Could not save." };
|
||||
formReplace = null;
|
||||
drawForm();
|
||||
return false;
|
||||
}
|
||||
saved.agents = (Array.isArray(body.agents) ? body.agents : agents).map(normalizeAgent);
|
||||
} catch {
|
||||
formMark({ ok: false, error: "Could not save." });
|
||||
return false;
|
||||
}
|
||||
const id = saved.agents[at].id;
|
||||
found.delete(key);
|
||||
found.delete("agent:" + id);
|
||||
savedAs("agent:" + id);
|
||||
formMark({ ok: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
function saveForm(key, options) {
|
||||
return key.startsWith("cli:") ? saveModelsFor(cliOf(key)) : saveAgentFor(key, options);
|
||||
}
|
||||
|
||||
async function deleteAgent(key) {
|
||||
const agents = saved.agents.filter((a) => a.id !== agentId(key)).map(cleanAgent);
|
||||
confirming = false;
|
||||
try {
|
||||
const { res, body } = await postJson("/agents", { agents });
|
||||
if (!res.ok) {
|
||||
formError = { field: null, error: body.error || "Could not delete." };
|
||||
drawForm();
|
||||
return;
|
||||
}
|
||||
saved.agents = (Array.isArray(body.agents) ? body.agents : agents).map(normalizeAgent);
|
||||
} catch {
|
||||
formError = { field: null, error: "Could not delete." };
|
||||
drawForm();
|
||||
return;
|
||||
}
|
||||
found.delete(key);
|
||||
closeForm();
|
||||
setAgentsStatus("Deleted.", false, { deleted: true });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- the dialog's side */
|
||||
|
||||
// An open form whose draft differs from what is saved.
|
||||
export function hasUnsaved() {
|
||||
return openKey !== null && isDirty(openKey);
|
||||
}
|
||||
|
||||
// What the unsaved prompt calls the open form.
|
||||
export function unsavedName() {
|
||||
return openKey ? nameOf(openKey) : "";
|
||||
}
|
||||
|
||||
export function saveOpen() {
|
||||
return openKey ? saveForm(openKey) : Promise.resolve(true);
|
||||
}
|
||||
|
||||
export function discardOpen() {
|
||||
if (!openKey) return;
|
||||
if (openKey === "agent:new") return closeForm();
|
||||
drafts.set(openKey, structuredClone(savedEntry(openKey)));
|
||||
formError = null;
|
||||
formReplace = null;
|
||||
confirming = false;
|
||||
drawForm();
|
||||
}
|
||||
|
||||
// Back into the form after Keep editing or a failed Save: the marked field, else the first.
|
||||
export function focusOpen() {
|
||||
const form = $("agents-form");
|
||||
(form.querySelector("input.invalid") || form.querySelector("input"))?.focus();
|
||||
}
|
||||
|
||||
// Each time the dialog opens: the summary, from the server.
|
||||
export async function loadAgentsView() {
|
||||
const seq = ++loadSeq;
|
||||
openKey = null;
|
||||
drafts.clear();
|
||||
found.clear();
|
||||
formError = null;
|
||||
formReplace = null;
|
||||
confirming = false;
|
||||
$("agents-form").replaceChildren();
|
||||
showSummary(true);
|
||||
setAgentsStatus("", false);
|
||||
const [agents, models] = await Promise.all([
|
||||
fetch("/agents").then((r) => (r.ok ? r.json() : null)).catch(() => null),
|
||||
fetch("/models").then((r) => (r.ok ? r.json() : null)).catch(() => null),
|
||||
]);
|
||||
if (seq !== loadSeq) return;
|
||||
const problems = [];
|
||||
if (agents) {
|
||||
saved.agents = (Array.isArray(agents.agents) ? agents.agents : []).map(normalizeAgent);
|
||||
if (Array.isArray(agents.warnings)) problems.push(...agents.warnings);
|
||||
} else {
|
||||
saved.agents = [];
|
||||
problems.push("Agents could not be loaded.");
|
||||
}
|
||||
saved.user = emptyLists();
|
||||
saved.shipped = emptyLists();
|
||||
if (models) {
|
||||
for (const cli of MODEL_CLIS) {
|
||||
if (Array.isArray(models.user?.[cli])) saved.user[cli] = models.user[cli];
|
||||
if (Array.isArray(models.shipped?.[cli])) saved.shipped[cli] = models.shipped[cli];
|
||||
}
|
||||
} else {
|
||||
problems.push("Models could not be loaded.");
|
||||
}
|
||||
setAgentsStatus(problems.join(" "), problems.length > 0);
|
||||
renderSummary();
|
||||
}
|
||||
|
||||
export function wireAgentsView() {
|
||||
$("agents-add").addEventListener("click", () => openForm("agent:new"));
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
// Plan2Code Web Console - the Ask chat, the Subagents tab, and attaching files to notes.
|
||||
|
||||
import { page, saveNow, redraw, freshChat, hooks, scrollMemory, setDraft } from "../state.js";
|
||||
import { chatOffline, chatView, sendState as chatSendState, newestReplyId, CHAT_MAX_CHARS, nextAbout, CHAT_MAX_ATTACHMENTS, contextOptions } from "../chat.js";
|
||||
import { finish, activity, agentAdrift, isDashboard, selSpec, byId, isOpen } from "../selectors.js";
|
||||
import { chatAnswering, chatOffline, chatView, sendState as chatSendState, newestReplyId, CHAT_MAX_CHARS, nextAbout, CHAT_MAX_ATTACHMENTS, contextOptions } from "../chat.js";
|
||||
import { finish, activity, agentAdrift, isDashboard, selSpec, byId, isOpen, loopAskLocked, loopDriving } from "../selectors.js";
|
||||
import { el, md, isMac, lightDismiss, shortTime } from "../render.js";
|
||||
import { startersFor } from "../starters.js";
|
||||
import { looks } from "../looks.js";
|
||||
@@ -37,6 +37,7 @@ function askFrame() {
|
||||
agent: page.S.agent,
|
||||
agentLastSeenMs: Date.parse(page.agentLastSeen),
|
||||
now: Date.now(),
|
||||
answering: chatAnswering(base),
|
||||
});
|
||||
return { ...base, offline };
|
||||
}
|
||||
@@ -45,7 +46,13 @@ export function askState() {
|
||||
const frame = askFrame();
|
||||
const shown = chatView(frame, { pendingSends: page.local.chat.pending, agentActivity: activity() });
|
||||
const pendingSendCount = shown.rows.filter((r) => r.pending && !r.failed).length;
|
||||
return { frame, view: shown, send: chatSendState({ frameChat: frame, gone: page.gone, pendingSendCount }) };
|
||||
const send = chatSendState({ frameChat: frame, gone: page.gone, pendingSendCount });
|
||||
// The Implementation Loop locks Ask like everything else it drives (FR-15),
|
||||
// unless a question waits for the person (FR-14).
|
||||
if (send.canType && loopAskLocked()) {
|
||||
return { frame, view: shown, send: { state: "ok", text: "Ask is off while the loop builds.", canType: false } };
|
||||
}
|
||||
return { frame, view: shown, send };
|
||||
}
|
||||
|
||||
// The conversation a send belongs to. The page's own record wins over the
|
||||
@@ -760,7 +767,8 @@ export function renderSubagentsButton() {
|
||||
btn.setAttribute("aria-pressed", String(Boolean(page.subagentsFrame.on)));
|
||||
btn.title = label;
|
||||
btn.setAttribute("aria-label", label);
|
||||
btn.disabled = page.gone;
|
||||
// The Subagents switch is the person's setting for the next agent; the loop's phases are already started.
|
||||
btn.disabled = page.gone || loopDriving();
|
||||
}
|
||||
|
||||
// The Subagents dialog, filled from the frame each time it opens. A null
|
||||
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
byId,
|
||||
docs,
|
||||
isGitBoard,
|
||||
loopDriving,
|
||||
loopWaiting,
|
||||
} from "../selectors.js";
|
||||
import {
|
||||
lastOpenCard,
|
||||
@@ -316,14 +318,38 @@ function inFlightFor(item) {
|
||||
return sub ? { value: sub, summary: "" } : null;
|
||||
}
|
||||
|
||||
// While the Implementation Loop drives, an open card is a record, not a form
|
||||
// (FR-15): "handled" when the loop answers it itself, "locked" otherwise. The
|
||||
// one exception (FR-14) is a required question the loop does not handle, which
|
||||
// stays a live form while it waits for the person.
|
||||
function loopLockFor(item) {
|
||||
if (!loopDriving() || !isOpen(item) || finish()) return null;
|
||||
if (item.handledBy === "loop") return "handled";
|
||||
return loopWaiting() && item.required !== false ? null : "locked";
|
||||
}
|
||||
|
||||
function renderLoopLocked(card, item, why) {
|
||||
const box = el("div", "answered is-loop " + (why === "handled" ? "is-handled" : "is-locked"));
|
||||
if (why === "handled") {
|
||||
box.appendChild(el("p", "answered-head loop-tag", "The loop handles this"));
|
||||
box.appendChild(el("p", "answered-lock", "The Implementation Loop answers this one itself, so there is nothing to do here."));
|
||||
} else {
|
||||
box.appendChild(el("p", "answered-lock", "The Implementation Loop is building. This unlocks by itself if it needs you."));
|
||||
}
|
||||
card.appendChild(box);
|
||||
lockedOptions(card, item, []);
|
||||
}
|
||||
|
||||
export function renderCard(item) {
|
||||
const staged = page.local.staged[item.id];
|
||||
const flight = inFlightFor(item);
|
||||
const loopLock = loopLockFor(item);
|
||||
const card = el(
|
||||
"article",
|
||||
"card question" +
|
||||
(!isOpen(item) || finish() ? " is-answered" : staged ? " is-staged" : "") +
|
||||
(flight ? " is-inflight" : "")
|
||||
(flight ? " is-inflight" : "") +
|
||||
(loopLock ? " is-loop-" + loopLock : "")
|
||||
);
|
||||
|
||||
// Which question this card is for, so a render can tell whether the card it
|
||||
@@ -348,6 +374,8 @@ export function renderCard(item) {
|
||||
// send can no longer go anywhere and the form would be a trap.
|
||||
if (!isOpen(item) || finish()) {
|
||||
renderSettled(card, item);
|
||||
} else if (loopLock) {
|
||||
renderLoopLocked(card, item, loopLock);
|
||||
} else if (flight) {
|
||||
renderInFlight(card, item, flight);
|
||||
} else {
|
||||
@@ -355,7 +383,7 @@ export function renderCard(item) {
|
||||
if (build) build(card, item, staged);
|
||||
}
|
||||
|
||||
if (item.required === false && isOpen(item) && !flight && !finish()) {
|
||||
if (item.required === false && isOpen(item) && !flight && !finish() && !loopLock) {
|
||||
const skipped = Boolean(staged && staged.skipped);
|
||||
// A small accent chip, like a comment box's quick answer ("No changes"),
|
||||
// rather than an underlined link that reads as fine print.
|
||||
@@ -372,7 +400,7 @@ export function renderCard(item) {
|
||||
}
|
||||
}
|
||||
|
||||
if (isOpen(item) && !flight && !finish()) markGrowBox(card);
|
||||
if (isOpen(item) && !flight && !finish() && !loopLock) markGrowBox(card);
|
||||
return card;
|
||||
}
|
||||
|
||||
@@ -835,6 +863,28 @@ function buildChoice(card, item, staged) {
|
||||
}
|
||||
otherOption(list, item, staged, name);
|
||||
card.appendChild(list);
|
||||
clearRow(card, item);
|
||||
}
|
||||
|
||||
// Takes a one-answer question back to how it arrived: no pick, and nothing in
|
||||
// "Something else" (its draft too, or the render would put the words straight
|
||||
// back). A radio group cannot be unticked by clicking it again, so without
|
||||
// this a stray pick could only be swapped for another one. Only the builders
|
||||
// call it, and they only run for a form that has not been sent.
|
||||
function clearRow(card, item) {
|
||||
const row = el("div", "btn-row options-clear");
|
||||
const b = el("button", "btn small ghost", "Clear");
|
||||
b.type = "button";
|
||||
// An id so focus survives the render the click sets off (see withFocus).
|
||||
b.id = "clear-" + item.id;
|
||||
b.setAttribute("aria-label", "Clear your answer to this question");
|
||||
b.addEventListener("click", () => {
|
||||
const other = "other-" + item.id;
|
||||
if (page.local.drafts[other]) setDraft(other, "");
|
||||
stage(item.id, null);
|
||||
});
|
||||
row.appendChild(b);
|
||||
card.appendChild(row);
|
||||
}
|
||||
|
||||
function buildMulti(card, item, staged) {
|
||||
@@ -1335,6 +1385,7 @@ function buildMenu(card, item, staged) {
|
||||
list.appendChild(li);
|
||||
}
|
||||
card.appendChild(list);
|
||||
clearRow(card, item);
|
||||
|
||||
if (item.command) {
|
||||
const note = el("div", "card-note");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Plan2Code Web Console - User Preferences, Cleanup tab.
|
||||
// Plan2Code Web Console - User Preferences, the Cleanup section on the System tab.
|
||||
|
||||
import { formatBytes } from "../answers.js";
|
||||
import { el } from "../render.js";
|
||||
@@ -123,7 +123,7 @@ async function deleteCleanup() {
|
||||
setCleanupStatus((failed ? done + " " + failed + " could not be removed." : done) + keptLine, Boolean(failed));
|
||||
}
|
||||
|
||||
// The Cleanup tab's buttons, and starting over whenever Preferences closes.
|
||||
// The Cleanup section's buttons, and starting over whenever Preferences closes.
|
||||
export function wireCleanup() {
|
||||
$("cleanup-scan").addEventListener("click", scanCleanup);
|
||||
$("cleanup-delete").addEventListener("click", deleteCleanup);
|
||||
|
||||
@@ -50,7 +50,7 @@ import { faviconState, setFavicon } from "../favicon.js";
|
||||
import { helperRows, showTab } from "../subagents.js";
|
||||
import { FOOTER_TIERS, footerLabel } from "../workspace.js";
|
||||
import {
|
||||
activity, agentAdrift, agentWorking, asked, awaitingReply, byId, dashboardLive, docs, doingNow,
|
||||
activity, agentAdrift, agentWorking, askBusy, loopDriving, loopWaiting, loopWaitingKey, asked, awaitingReply, byId, dashboardLive, docs, doingNow,
|
||||
finish, gitAwaiting, isDashboard, isGitBoard, isOpen, isSpecFileView, items, loadOverview, myTurn, openItems,
|
||||
patience, pressStranded, reviewPending, scan, selSpec, sendCollected, specFileTabs, stagedCount, stranded,
|
||||
topics, workingMs, WORKING_GRACE_MS,
|
||||
@@ -58,6 +58,7 @@ import {
|
||||
} from "../selectors.js";
|
||||
import { sound } from "../sound.js";
|
||||
import { renderConfirm, renderDashboard } from "./dashboard.js";
|
||||
import { renderLoopSetup } from "./loop-setup.js";
|
||||
import { renderLaunching, renderWaiting } from "./starting.js";
|
||||
import { attachFiles, heldNotes, noteImages, pendingNotes, removeImage } from "../uploads.js";
|
||||
import { closeMentions } from "../mention-box.js";
|
||||
@@ -69,13 +70,13 @@ import { renderWorkspace, tellFolderIssues } from "./workspace.js";
|
||||
import { openHelpOn } from "./help-dialog.js";
|
||||
import { linkLeavesPage, startNewSession, tellApp } from "../app-bridge.js";
|
||||
import { askOfflineFlipped, askState, declineOpen, renderAside, renderAsk, renderSubagents, renderSubagentsButton } from "./ask.js";
|
||||
import { renderHandoff, renderHomeButton, renderStopButton, renderStopControls, renderStopping, stopInProgress, stopWarning } from "./ending.js";
|
||||
import { renderHandoff, renderLoopEnd, renderHomeButton, renderStopButton, renderStopControls, renderStopping, stopInProgress, stopWarning } from "./ending.js";
|
||||
import { renderNotepadButton } from "./notepad.js";
|
||||
import { renderActivities } from "./activities.js";
|
||||
|
||||
// What the entry needs from the screens at start-up, handed on from here: only
|
||||
// the core imports a screen.
|
||||
export { wakeHoldsChime, wireDashboard } from "./dashboard.js";
|
||||
export { launchSkill, wakeHoldsChime, wireDashboard } from "./dashboard.js";
|
||||
export { fillSky } from "./starting.js";
|
||||
export { fitGrowBox, wireCards } from "./cards.js";
|
||||
export { wireDocs } from "./docs.js";
|
||||
@@ -84,9 +85,12 @@ export { syncWorkspaceScope, wireWorkspace } from "./workspace.js";
|
||||
export { maybeWelcome, openHelpOn, wireHelp } from "./help-dialog.js";
|
||||
export { wireCleanup } from "./cleanup.js";
|
||||
export { startLooks, wireLooks } from "./looks.js";
|
||||
export { confirmUnsaved, markSaved, openPrefs, wirePrefs } from "./prefs-dialog.js";
|
||||
export { discardOpen, focusOpen, hasUnsaved, loadAgentsView, saveOpen, unsavedName, wireAgentsView } from "./agents-view.js";
|
||||
export { wireEnding } from "./ending.js";
|
||||
export { wireNotepad } from "./notepad.js";
|
||||
export { wireActivities } from "./activities.js";
|
||||
export { openLoopSetup, wireLoopSetup } from "./loop-setup.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -293,6 +297,11 @@ export function adopt(body) {
|
||||
page.inApp = Boolean(body.inApp);
|
||||
// Help's `.for-app` / `.for-browser` wording switches on this (help.css).
|
||||
document.documentElement.classList.toggle("in-app", page.inApp);
|
||||
// The Implementation Loop's lock: `loop: { driving: true }` on the state,
|
||||
// ended by the app's `loopEnd`. Screens ask loopDriving(); the class is for
|
||||
// the stylesheet.
|
||||
page.loop = (body.state && body.state.loop && body.state.loop.driving === true) || body.loop === true ? { driving: true } : null;
|
||||
document.documentElement.classList.toggle("loop-driving", loopDriving());
|
||||
// Always replaced: an absent key means no update.
|
||||
page.updateFrame = body.update || null;
|
||||
// Always replaced too: an older server sends none, and then there is no switch.
|
||||
@@ -318,8 +327,9 @@ export function adopt(body) {
|
||||
// session; what this page kept for the last skill -- the question on
|
||||
// screen, the open tab, anything staged or typed against its item ids --
|
||||
// goes too. The launch in flight and the dashboard's spec pick are about the
|
||||
// hand-off itself, so they stay. A skill run inline from another (a quick
|
||||
// task's review) keeps all of it.
|
||||
// hand-off itself, so they stay, and so does the Ask tab: the conversation
|
||||
// outlives the hop. A skill run inline from another (a quick task's review)
|
||||
// keeps all of it.
|
||||
if (startsClean(prevWorkflow, page.S.workflow)) {
|
||||
// The pick rides into the skill it launched, never back home: arriving at
|
||||
// the dashboard, the picker starts on the most recently touched spec still
|
||||
@@ -331,13 +341,15 @@ export function adopt(body) {
|
||||
const keepNote = Boolean(ns) && page.S.workflow !== "dashboard" && page.S.workflow === ns.workflow;
|
||||
page.local = {
|
||||
...fresh(),
|
||||
chat: page.local.chat,
|
||||
launching: page.local.launching,
|
||||
...(keepPick ? { specSel: page.local.specSel } : {}),
|
||||
...(keepNote ? { noteSend: ns } : {}),
|
||||
};
|
||||
save();
|
||||
page.selected = null;
|
||||
page.view = "questions";
|
||||
// Someone reading the Ask tab across the hop stays on it.
|
||||
if (page.view !== "ask") page.view = "questions";
|
||||
// And forget which tab is drawn, or the next render would store the old
|
||||
// skill's offset straight back under a tab id the new one may reuse.
|
||||
scrollMemory.clear();
|
||||
@@ -394,7 +406,10 @@ export function adopt(body) {
|
||||
// session under its own workflow, so `dashboard` stops being what the state
|
||||
// says it is. A finish while still on the dashboard is the launch declined
|
||||
// or the session ended; either way the menu is not mid-handoff any more.
|
||||
if (!isDashboard() || finish()) page.dashPick = null;
|
||||
if (!isDashboard() || finish()) {
|
||||
page.dashPick = null;
|
||||
page.loopSetup = null;
|
||||
}
|
||||
// A launch (or an ending) mid wake-up: cut it short rather than play on
|
||||
// over a page that is no longer the menu.
|
||||
if (page.wake && (!isDashboard() || finish())) page.wake.abort.abort();
|
||||
@@ -505,7 +520,7 @@ export function adopt(body) {
|
||||
}
|
||||
|
||||
// The chat's half of adopt(). A new conversation (New conversation pressed in
|
||||
// any tab, or a skill switch) is a clean page: nothing typed or waiting for
|
||||
// any tab) is a clean page: nothing typed or waiting for
|
||||
// the old one carries over. Conversations only ever count up, so a frame that
|
||||
// names an older one than this page already moved to is a late frame, not a
|
||||
// switch. Sends the server has now echoed stop being pending.
|
||||
@@ -515,8 +530,7 @@ function adoptChat() {
|
||||
if (page.local.chat.conversation == null) page.local.chat.conversation = conv;
|
||||
else if (conv > page.local.chat.conversation) {
|
||||
// What they were typing, and what they had attached to it, is theirs:
|
||||
// a new conversation started elsewhere (another tab, a skill switch)
|
||||
// must not wipe a message they have not sent yet.
|
||||
// a new conversation started elsewhere (another tab) must not wipe a message they have not sent yet.
|
||||
page.local.chat = { ...freshChat(), history: page.local.chat.history, draft: page.local.chat.draft, images: page.local.chat.images, about: null, conversation: conv };
|
||||
page.chatError = "";
|
||||
page.askRowCount = 0;
|
||||
@@ -996,13 +1010,20 @@ function renderMeter() {
|
||||
// a command to copy into a new conversation.
|
||||
const fresh = $("meter-fresh");
|
||||
fresh.hidden = page.meterFrame.level === "green";
|
||||
// The loop's agents run on; a new session mid-loop is the loop banner's Stop.
|
||||
const built = fresh.querySelector(".meter-fresh-btn");
|
||||
if (built) {
|
||||
built.disabled = loopDriving();
|
||||
built.title = loopDriving() ? "The loop is building. Stop it from the banner at the top of the window." : "";
|
||||
}
|
||||
if (fresh.hidden || fresh.dataset.built) return;
|
||||
fresh.dataset.built = "1";
|
||||
if (page.inApp) {
|
||||
// The same press as the app bar's New Session, confirm and all.
|
||||
const press = el("button", "btn small primary meter-fresh-btn", "Start a New Session");
|
||||
press.type = "button";
|
||||
press.addEventListener("click", () => tellApp("new-session"));
|
||||
press.addEventListener("click", () => !loopDriving() && tellApp("new-session"));
|
||||
press.disabled = loopDriving();
|
||||
fresh.append(press);
|
||||
return;
|
||||
}
|
||||
@@ -1050,7 +1071,9 @@ function renderChrome() {
|
||||
// The menu has no questions to count: an empty bar there reads as a stall.
|
||||
document.querySelector(".progress-block").hidden = (isDashboard() || page.S.workflow === "git") && !finish();
|
||||
$("progress-text").textContent = total
|
||||
? `${done} of ${total} ${building ? "done" : "answered"}`
|
||||
? loopDriving() && building
|
||||
? `${done} of ${total} tasks in this phase`
|
||||
: `${done} of ${total} ${building ? "done" : "answered"}`
|
||||
: h.stage || "Getting started";
|
||||
$("confidence").textContent = h.confidence || "";
|
||||
$("progress-fill").style.width = pct + "%";
|
||||
@@ -1087,6 +1110,10 @@ let moodVar = 0;
|
||||
const STRANDED_LINE =
|
||||
"Plan2Code is not running. Your answers are saved and waiting for it. If the terminal is idle, type **continue** there and it will pick them up; it may also be waiting for your permission approval.";
|
||||
|
||||
// The agent is out of `wait` answering an Ask message (askBusy()), so a send
|
||||
// waits for it to finish that first.
|
||||
const ASK_BUSY_LINE = "Plan2Code is answering your Ask message. Your answers are saved, and it picks them up after that.";
|
||||
|
||||
// A finished screen's press that nothing is collecting (pressStranded()).
|
||||
const PRESS_STRANDED_LINE =
|
||||
"Plan2Code is not running. Your choice is saved and waiting for it. If the terminal is idle, type **continue** there and it will pick it up; it may also be waiting for your permission approval.";
|
||||
@@ -1252,6 +1279,9 @@ export function renderStatus() {
|
||||
const hint = quiet && page.inApp ? APPROVAL_HINT_IN_APP : quiet;
|
||||
return say("work", hint || activity() || "Plan2Code is thinking…", fmtMs(workingMs()), true, Boolean(hint));
|
||||
}
|
||||
// Only once something is waiting on it, and nothing else is theirs to answer:
|
||||
// with a card still open, "Sent. N still for you" is the truer line.
|
||||
if (askBusy() && !myTurn().length && (page.pendingResult || awaitingReply().length)) return say("work", ASK_BUSY_LINE, "", true);
|
||||
// Between pressing Send and the agent picking it up, the agent's own status
|
||||
// is still "waiting" because it has not started yet. Reading that as "your
|
||||
// turn" told someone who had just answered everything that the ball was back
|
||||
@@ -1520,6 +1550,7 @@ function paintMain(main) {
|
||||
// falls through to the ordinary path below, which hands it the card.
|
||||
if (isDashboard() && !finish()) {
|
||||
if (page.local.launching) renderLaunching(main);
|
||||
else if (page.loopSetup) renderLoopSetup(main);
|
||||
else if (page.dashPick) {
|
||||
// A spec-switch under an open confirm can gray the pick out. Rather
|
||||
// than offer START on a card that cannot launch, drop back to the
|
||||
@@ -1559,6 +1590,15 @@ function paintMain(main) {
|
||||
return;
|
||||
}
|
||||
|
||||
// How the Implementation Loop ended, from the app's `loopEnd`: its own
|
||||
// screen, ahead of any card the last phase left behind.
|
||||
if (page.S.loopEnd && !finish()) {
|
||||
const card = renderLoopEnd(page.S.loopEnd);
|
||||
card.classList.add("is-primary");
|
||||
main.appendChild(card);
|
||||
return;
|
||||
}
|
||||
|
||||
const list = asked();
|
||||
if (!list.length) {
|
||||
// A session can end before it asked anything at all (a build that needed
|
||||
@@ -1620,6 +1660,9 @@ export function renderFooter() {
|
||||
if (foot) foot.classList.toggle("is-dash", Boolean(isDashboard() && !finish()));
|
||||
// A finished dashboard keeps its summary line but still has nothing to send.
|
||||
if (foot) foot.classList.toggle("is-dash-done", Boolean(isDashboard() && finish()));
|
||||
// A loop at work has nothing for the person to send, so no Send to suggest
|
||||
// otherwise; it comes back the moment a question waits.
|
||||
if (foot) foot.classList.toggle("is-loop-idle", loopDriving() && !loopWaiting() && !finish());
|
||||
|
||||
const summary = $("footer-summary");
|
||||
const notes = pendingNotes();
|
||||
@@ -1904,13 +1947,16 @@ export async function send() {
|
||||
e.status = res.status;
|
||||
throw e;
|
||||
}
|
||||
// Ask locks again once the loop's question is answered (FR-14); it opens
|
||||
// for the next, different one.
|
||||
if (loopWaiting()) page.local.askLockedAfterSend = loopWaitingKey();
|
||||
markSent(payload);
|
||||
banner("Sent. Plan2Code is picking it up now.", "good");
|
||||
setTimeout(() => banner(null), 4000);
|
||||
// A menu option the agent marked `fresh` is a clean start, which under the
|
||||
// app is the bar's New Session; the agent still gets the pick, so a
|
||||
// declined confirm carries on with its usual finish.
|
||||
const freshMenu = page.inApp ? freshMenuPick(actions) : null;
|
||||
const freshMenu = page.inApp && !loopDriving() ? freshMenuPick(actions) : null;
|
||||
if (freshMenu) startNewSession(freshMenu.command ? handoffText({ command: freshMenu.command }) : "");
|
||||
} catch (err) {
|
||||
if (err && err.pending) {
|
||||
@@ -2108,8 +2154,9 @@ export function wireChrome() {
|
||||
// Escape is the confirm pane's Back — but not while a dialog has it. Native
|
||||
// dialogs close themselves on the same key; backing out of the pick at the
|
||||
// same time would be two undos for one press.
|
||||
if (e.key === "Escape" && page.dashPick && isDashboard() && !finish() && !document.querySelector("dialog[open]")) {
|
||||
if (e.key === "Escape" && (page.dashPick || page.loopSetup) && isDashboard() && !finish() && !document.querySelector("dialog[open]")) {
|
||||
page.dashPick = null;
|
||||
page.loopSetup = null;
|
||||
redraw();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -9,11 +9,12 @@ import {
|
||||
handoffList,
|
||||
loadOverview,
|
||||
finish,
|
||||
loopDriving,
|
||||
} from "../selectors.js";
|
||||
import { hooks, page, redraw, saveNow } from "../state.js";
|
||||
import { el, approvalTip, mdInto, releasesLink, copyButton, lightDismiss } from "../render.js";
|
||||
import { needsRoleNudge, ROLE_NOT_SET } from "../starters.js";
|
||||
import { looks, renderSwatches, saveLooks } from "../looks.js";
|
||||
import { looks, saveLooks } from "../looks.js";
|
||||
import { RED_BANNER, RED_BANNER_IN_APP } from "../meter.js";
|
||||
import {
|
||||
dashNoteKind,
|
||||
@@ -23,6 +24,8 @@ import {
|
||||
CATALOG_GROUPS,
|
||||
SKILL_CATALOG,
|
||||
catalogEntry,
|
||||
LOOP_ENTRY,
|
||||
OUTSIDE_APP_LINE,
|
||||
launchVariant,
|
||||
SPEC_STATE_LABELS,
|
||||
chipDetail,
|
||||
@@ -74,7 +77,6 @@ function roleNudge() {
|
||||
const setUp = el("button", "btn small primary", "Set up preferences");
|
||||
setUp.type = "button";
|
||||
setUp.addEventListener("click", () => {
|
||||
renderSwatches();
|
||||
// Closed without a role is a "Not now" too: having been to the dialog,
|
||||
// they were asked, and the banner does not come back (Help says so).
|
||||
$("looks-modal").addEventListener(
|
||||
@@ -88,7 +90,7 @@ function roleNudge() {
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
$("looks-modal").showModal();
|
||||
hooks.openPrefs("appearance");
|
||||
});
|
||||
const notNow = el("button", "btn tiny ghost", "Not now");
|
||||
notNow.type = "button";
|
||||
@@ -243,12 +245,16 @@ export function renderDashboard(main) {
|
||||
let shown = 0;
|
||||
for (const g of CATALOG_GROUPS) {
|
||||
const entries = SKILL_CATALOG.filter((e) => e.group === g.id && (!hide || available(e)));
|
||||
if (!entries.length) continue;
|
||||
shown += entries.length;
|
||||
// The desktop app's Implementation Loop card closes its group. Outside the
|
||||
// app it is always drawn, grayed, so the feature can be found.
|
||||
const loopCard = LOOP_ENTRY && LOOP_ENTRY.group === g.id && (!page.inApp || !hide || available(LOOP_ENTRY));
|
||||
if (!entries.length && !loopCard) continue;
|
||||
shown += entries.length + (loopCard ? 1 : 0);
|
||||
const section = el("section", "dash-group");
|
||||
section.appendChild(el("h3", "dash-group-title", g.title));
|
||||
const grid = el("div", "dash-grid");
|
||||
for (const e of entries) grid.appendChild(dashCard(e, menu));
|
||||
if (loopCard) grid.appendChild(dashCard(LOOP_ENTRY, menu));
|
||||
section.appendChild(grid);
|
||||
wrap.appendChild(section);
|
||||
}
|
||||
@@ -664,7 +670,7 @@ async function readHandoff(h) {
|
||||
}
|
||||
|
||||
function dashCard(entry, menu) {
|
||||
const presentation = cardPresentation(entry, scan(), selSpec(), menu);
|
||||
const presentation = entry.appOnly ? loopPresentation(entry, menu) : cardPresentation(entry, scan(), selSpec(), menu);
|
||||
// The agent's `recommend` and detail describe the initially selected spec.
|
||||
// Other picker choices derive both from the scan, so stale context never
|
||||
// follows a person to a different spec or to "start from scratch". A grayed
|
||||
@@ -675,7 +681,7 @@ function dashCard(entry, menu) {
|
||||
"dash-card" + (presentation.recommended ? " is-suggested" : "") + (going ? " is-going" : "")
|
||||
);
|
||||
b.type = "button";
|
||||
b.disabled = Boolean(page.local.launching) || page.gone || page.pendingResult || !presentation.on;
|
||||
b.disabled = Boolean(page.local.launching) || page.gone || page.pendingResult || loopDriving() || !presentation.on;
|
||||
if (!presentation.on && presentation.reason) b.title = presentation.reason;
|
||||
|
||||
const head = el("span", "dash-card-head");
|
||||
@@ -693,12 +699,39 @@ function dashCard(entry, menu) {
|
||||
b.appendChild(foot);
|
||||
|
||||
b.addEventListener("click", () => {
|
||||
// The loop card opens its own setup screen instead of a confirm pane.
|
||||
if (entry.appOnly) return hooks.openLoopSetup(selSpec());
|
||||
page.dashPick = entry;
|
||||
redraw();
|
||||
});
|
||||
if (entry.appOnly) b.appendChild(loopHelpLink());
|
||||
return b;
|
||||
}
|
||||
|
||||
// The loop card is lit only inside the desktop app and, there, by the same
|
||||
// rule as Implement (a documented or building spec). Never recommended or
|
||||
// pre-selected: a person opts into running unattended.
|
||||
function loopPresentation(entry, menu) {
|
||||
if (!page.inApp) return { on: false, reason: OUTSIDE_APP_LINE, recommended: false, detail: "" };
|
||||
return { ...cardPresentation(entry, scan(), selSpec(), menu), recommended: false };
|
||||
}
|
||||
|
||||
// "How the loop works" on the card: a link inside a button is not allowed, so
|
||||
// it is a span that acts like one and keeps the click from opening the setup.
|
||||
function loopHelpLink() {
|
||||
const a = el("span", "dash-card-link", "How the loop works");
|
||||
a.setAttribute("role", "link");
|
||||
a.tabIndex = 0;
|
||||
const open = (e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
hooks.openHelpOn("loop");
|
||||
};
|
||||
a.addEventListener("click", open);
|
||||
a.addEventListener("keydown", (e) => (e.key === "Enter" || e.key === " ") && open(e));
|
||||
return a;
|
||||
}
|
||||
|
||||
// "Start with a note from your Notebook": the switch a lit card's confirm
|
||||
// pane offers when noteSwitchShows() says so. The pane is rebuilt on every
|
||||
// state frame, so what the person did lives here, keyed to the card and the
|
||||
@@ -806,8 +839,18 @@ function drawNoteBox(entry, box, cmdNote) {
|
||||
again();
|
||||
if (state.on && (state.tabs === null || state.failed)) refreshNoteTabs(state, true);
|
||||
});
|
||||
label.append(toggle, el("span", null, "Start with a note from your Notebook"));
|
||||
box.appendChild(label);
|
||||
label.append(toggle, el("span", "confirm-note-switch-text", "Start with a note from your Notebook"));
|
||||
// A callout row, so the switch stands out under the card's long text; the
|
||||
// hint sits outside the label to keep the checkbox's name short.
|
||||
const head = el("div", "confirm-note-head" + (state.on ? " is-on" : ""));
|
||||
head.appendChild(label);
|
||||
if (!state.on) {
|
||||
const hint = el("span", "confirm-note-hint", "Hand it a tab you wrote earlier, with its pictures.");
|
||||
hint.id = "confirm-note-hint";
|
||||
toggle.setAttribute("aria-describedby", hint.id);
|
||||
head.appendChild(hint);
|
||||
}
|
||||
box.appendChild(head);
|
||||
|
||||
const picked = state.on && state.tabs ? state.tabs.find((t) => t.id === state.picked && t.read) : null;
|
||||
cmdNote.textContent = picked ? " + note: " + picked.name : "";
|
||||
@@ -834,11 +877,11 @@ function drawNoteBox(entry, box, cmdNote) {
|
||||
b.setAttribute("aria-pressed", String(t.id === state.picked));
|
||||
b.appendChild(el("span", "confirm-note-tab-name", t.name));
|
||||
if (t.sent) {
|
||||
const badge = el("span", "notepad-sent-badge", "sent");
|
||||
const badge = el("span", "notepad-sent-badge", "previously sent");
|
||||
badge.setAttribute("aria-hidden", "true");
|
||||
b.appendChild(badge);
|
||||
}
|
||||
b.setAttribute("aria-label", t.name + (t.sent ? ", sent" : "") + (empty ? ", empty" : ""));
|
||||
b.setAttribute("aria-label", t.name + (t.sent ? ", previously sent" : "") + (empty ? ", empty" : ""));
|
||||
if (empty) b.title = t.read ? "This tab has no text or pictures." : "This tab could not be read.";
|
||||
b.addEventListener("click", () => {
|
||||
if (state.picked === t.id) return;
|
||||
@@ -985,7 +1028,6 @@ export function renderConfirm(main, entry) {
|
||||
const cmdNote = el("span", "confirm-cmd-note");
|
||||
cmdNote.hidden = true;
|
||||
if (noteSwitchShows(entry, scan(), selSpec())) {
|
||||
pane.appendChild(el("hr", "confirm-rule"));
|
||||
const box = el("div", "confirm-note-box");
|
||||
// Which control in the box has the focus, so a rebuild of the whole pane
|
||||
// can hand it back (see the end of this function).
|
||||
@@ -1032,7 +1074,7 @@ export function renderConfirm(main, entry) {
|
||||
// A pick is a send like a brief or a stop: it names no question, so `__launch`
|
||||
// marks the action as being about the session, and it reaches the agent
|
||||
// through the same wait loop. The dashboard reads `skill` off it.
|
||||
async function launchSkill(entry) {
|
||||
export async function launchSkill(entry) {
|
||||
if (page.gone || page.pendingResult || page.local.launching || finish()) return;
|
||||
const target = launchTarget(entry, selSpec());
|
||||
// The card was clickable, so this should never fire — but a spec picked in
|
||||
|
||||
@@ -42,9 +42,14 @@ import {
|
||||
agentWorking,
|
||||
awaitingReply,
|
||||
isDashboard,
|
||||
loopDriving,
|
||||
} from "../selectors.js";
|
||||
|
||||
// What the session buttons say while the Implementation Loop drives: its own
|
||||
// strip in the app's top bar stops it, not this page.
|
||||
const LOOP_LOCK_TITLE = "The loop is building. Stop it from the banner at the top of the window.";
|
||||
import { docSavedNote, downloadDoc } from "../doc-files.js";
|
||||
import { startNewSession } from "../app-bridge.js";
|
||||
import { startNewSession, tellApp } from "../app-bridge.js";
|
||||
import { pendingNotes } from "../uploads.js";
|
||||
|
||||
// The end of the session, and the only screen in this page whose job is to
|
||||
@@ -152,7 +157,110 @@ function closeGuideHeld() {
|
||||
return ["review", "commit", "changelog", "dashboard", "launch"].includes(page.local.afterBuild) || reviewPending() === "asked";
|
||||
}
|
||||
|
||||
// Which stop-screen button was pressed and is waiting on the app's answer, so a
|
||||
// second press cannot send the same request twice.
|
||||
let loopPressed = null;
|
||||
|
||||
const LOOP_BUTTONS = [
|
||||
["resume", "loop-resume", "Resume the loop", "primary"],
|
||||
["fix", "loop-fix", "Fix it by hand", ""],
|
||||
["finalize", "loop-finalize", "Finalize", "primary"],
|
||||
];
|
||||
|
||||
function shortHash(h) {
|
||||
return typeof h === "string" ? h.slice(0, 7) : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* How the Implementation Loop ended, drawn from the app's `loopEnd`: a stop
|
||||
* (why, what was committed, what is left uncommitted, what can be done next) or
|
||||
* a finish (every phase built, its commit, and a count of each kind of decision
|
||||
* its agent made; the report behind the button holds them all).
|
||||
*/
|
||||
export function renderLoopEnd(end) {
|
||||
const card = el("article", "card handoff loop-end");
|
||||
const finished = end.kind === "finished";
|
||||
card.appendChild(el("p", "card-kicker", finished ? "Loop finished" : "Loop stopped"));
|
||||
card.appendChild(el("h2", null, finished ? "Every phase is built" : end.line));
|
||||
if (finished && end.line) card.appendChild(el("p", "loop-line", end.line));
|
||||
|
||||
const evidence = end.evidence && docs().find((d) => d.id === end.evidence);
|
||||
if (evidence) {
|
||||
const read = el("button", "btn small", finished ? "Read the full report" : "Read why, and the report so far");
|
||||
read.type = "button";
|
||||
read.addEventListener("click", () => {
|
||||
page.view = "doc:" + evidence.id;
|
||||
redraw();
|
||||
});
|
||||
card.appendChild(read);
|
||||
}
|
||||
|
||||
const phases = Array.isArray(end.phases) ? end.phases : [];
|
||||
if (phases.length) {
|
||||
const table = el("table", "loop-end-phases");
|
||||
const head = el("tr");
|
||||
const cols = finished ? ["Phase", "Commit", "Fixed", "Not fixed", "Left open", "Assumed", "Other decisions", "Retries"] : ["Phase", "Commit"];
|
||||
for (const c of cols) head.appendChild(el("th", null, c));
|
||||
table.appendChild(head);
|
||||
for (const ph of phases) {
|
||||
const row = el("tr");
|
||||
row.appendChild(el("td", null, `Phase ${ph.n}: ${ph.name}`));
|
||||
const commit = el("td");
|
||||
if (ph.commit) commit.appendChild(el("code", null, shortHash(ph.commit)));
|
||||
else commit.textContent = "not committed";
|
||||
row.appendChild(commit);
|
||||
if (finished) {
|
||||
for (const count of [ph.fixed, ph.skipped, ph.left, ph.assumed, ph.decisions, ph.retries]) {
|
||||
row.appendChild(el("td", null, String(count ?? 0)));
|
||||
}
|
||||
}
|
||||
table.appendChild(row);
|
||||
}
|
||||
card.appendChild(table);
|
||||
}
|
||||
|
||||
const files = Array.isArray(end.uncommitted) ? end.uncommitted : [];
|
||||
if (files.length) {
|
||||
card.appendChild(el("h3", null, "Uncommitted in this phase"));
|
||||
const list = el("ul", "loop-end-files");
|
||||
const fill = (items, into) => items.forEach((f) => into.appendChild(el("li", null, f)));
|
||||
fill(files.slice(0, 10), list);
|
||||
if (files.length > 10) {
|
||||
const more = el("details");
|
||||
more.appendChild(el("summary", null, `${files.length - 10} more files`));
|
||||
const rest = el("ul", "loop-end-files");
|
||||
fill(files.slice(10), rest);
|
||||
more.appendChild(rest);
|
||||
card.append(list, more);
|
||||
} else {
|
||||
card.appendChild(list);
|
||||
}
|
||||
}
|
||||
|
||||
const can = Array.isArray(end.can) ? end.can : [];
|
||||
const actions = el("div", "loop-end-actions");
|
||||
for (const [key, message, label, kind] of LOOP_BUTTONS) {
|
||||
if (!can.includes(key)) continue;
|
||||
const b = el("button", "btn" + (kind ? " " + kind : ""), label);
|
||||
b.type = "button";
|
||||
b.disabled = page.gone || (loopPressed === message && !page.loopAction);
|
||||
b.addEventListener("click", () => {
|
||||
loopPressed = message;
|
||||
page.loopAction = null;
|
||||
tellApp(message);
|
||||
redraw();
|
||||
});
|
||||
actions.appendChild(b);
|
||||
}
|
||||
if (actions.childElementCount) card.appendChild(actions);
|
||||
if (page.loopAction && !page.loopAction.ok) {
|
||||
card.appendChild(el("p", "loop-error", page.loopAction.error));
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
export function renderHandoff(fin) {
|
||||
if (page.S && page.S.loopEnd) return renderLoopEnd(page.S.loopEnd);
|
||||
const card = el("article", "card handoff");
|
||||
card.appendChild(el("p", "card-kicker", finishPaused(fin) ? "Session paused" : "Session ended"));
|
||||
card.appendChild(el("h2", null, fin.headline));
|
||||
@@ -586,8 +694,8 @@ export function renderStopButton() {
|
||||
const gate = turnGate({ gone: page.gone, pendingResult: page.pendingResult, waiting: agentHasTheBall() });
|
||||
// A way home in flight holds Stop back too, unless the agent went quiet
|
||||
// after collecting it: Stop's resume screen is then the only way out.
|
||||
b.disabled = Boolean(gate) || (Boolean(page.local.homeward) && !agentAdrift());
|
||||
b.title = {
|
||||
b.disabled = Boolean(gate) || (Boolean(page.local.homeward) && !agentAdrift()) || loopDriving();
|
||||
b.title = loopDriving() ? LOOP_LOCK_TITLE : {
|
||||
gone: "Not connected right now.",
|
||||
pending: "Your last answers are still being picked up. You can stop once they have been.",
|
||||
waiting: "Plan2Code is working on your answers. You can stop once it replies.",
|
||||
@@ -617,8 +725,8 @@ export function renderHomeButton() {
|
||||
warned: Boolean(page.S) && Boolean(stopWarning()),
|
||||
});
|
||||
b.hidden = st.hidden;
|
||||
b.disabled = st.disabled;
|
||||
b.title = st.title;
|
||||
b.disabled = st.disabled || loopDriving();
|
||||
b.title = loopDriving() ? LOOP_LOCK_TITLE : st.title;
|
||||
}
|
||||
|
||||
function openHomeConfirm() {
|
||||
|
||||
@@ -4,7 +4,8 @@ import { looksReady, looks, saveLooks } from "../looks.js";
|
||||
import { page } from "../state.js";
|
||||
import { isDashboard, finish, agentAdrift } from "../selectors.js";
|
||||
import { releasesLink, el, copyButton, lightDismiss } from "../render.js";
|
||||
import { HELP_TABS, helpTabFor, helpKeyTarget } from "../help.js";
|
||||
import { HELP_TABS, helpTabFor } from "../help.js";
|
||||
import { wireTabs } from "../tabs.js";
|
||||
import { CATALOG_GROUPS, SKILL_CATALOG } from "../answers.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
@@ -196,6 +197,8 @@ function renderAppWording(root) {
|
||||
}
|
||||
|
||||
let helpBuilt = false;
|
||||
// The tabs, wired by tabs.js once the content is built.
|
||||
let helpTabs = null;
|
||||
|
||||
async function renderHelpVersion() {
|
||||
const slot = $("help-version");
|
||||
@@ -261,43 +264,31 @@ function buildHelp() {
|
||||
const code = row.querySelector("code");
|
||||
row.appendChild(copyButton(code.textContent, "btn small handoff-copy", code));
|
||||
}
|
||||
for (const t of HELP_TABS) {
|
||||
const btn = el("button", "help-tab");
|
||||
btn.type = "button";
|
||||
btn.id = "help-tab-" + t.id;
|
||||
btn.setAttribute("role", "tab");
|
||||
btn.setAttribute("aria-controls", "help-panel-" + t.id);
|
||||
btn.setAttribute("aria-selected", "false");
|
||||
btn.tabIndex = -1;
|
||||
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
svg.setAttribute("class", "help-tab-icon");
|
||||
svg.setAttribute("aria-hidden", "true");
|
||||
const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
|
||||
use.setAttribute("href", "#hi-" + t.id);
|
||||
svg.appendChild(use);
|
||||
btn.appendChild(svg);
|
||||
btn.appendChild(el("span", null, t.label));
|
||||
btn.addEventListener("click", () => selectHelpTab(t.id));
|
||||
tabs.appendChild(btn);
|
||||
const panel = panels.querySelector(`section.help-panel[data-tab="${t.id}"]`);
|
||||
panel.id = "help-panel-" + t.id;
|
||||
panel.setAttribute("role", "tabpanel");
|
||||
panel.setAttribute("aria-labelledby", "help-tab-" + t.id);
|
||||
panel.tabIndex = 0;
|
||||
panel.hidden = true;
|
||||
}
|
||||
helpTabs = wireTabs({
|
||||
tabs: HELP_TABS,
|
||||
list: tabs,
|
||||
panels,
|
||||
prefix: "help",
|
||||
tabClass: "help-tab",
|
||||
renderTab: (t, btn) => {
|
||||
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
svg.setAttribute("class", "help-tab-icon");
|
||||
svg.setAttribute("aria-hidden", "true");
|
||||
const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
|
||||
use.setAttribute("href", "#hi-" + t.id);
|
||||
svg.appendChild(use);
|
||||
btn.appendChild(svg);
|
||||
btn.appendChild(el("span", null, t.label));
|
||||
},
|
||||
onSelect: () => {
|
||||
$("help-panels").scrollTop = 0;
|
||||
},
|
||||
});
|
||||
helpBuilt = true;
|
||||
}
|
||||
|
||||
export function selectHelpTab(id) {
|
||||
for (const t of HELP_TABS) {
|
||||
const on = t.id === id;
|
||||
const btn = $("help-tab-" + t.id);
|
||||
btn.setAttribute("aria-selected", String(on));
|
||||
btn.tabIndex = on ? 0 : -1;
|
||||
$("help-panel-" + t.id).hidden = !on;
|
||||
}
|
||||
$("help-panels").scrollTop = 0;
|
||||
helpTabs.select(id);
|
||||
}
|
||||
|
||||
export function openHelp() {
|
||||
@@ -372,14 +363,6 @@ export function wireHelp() {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return;
|
||||
}
|
||||
if (!e.target.classList || !e.target.classList.contains("help-tab")) return;
|
||||
const current = HELP_TABS.findIndex((t) => "help-tab-" + t.id === e.target.id);
|
||||
const n = helpKeyTarget(e.key, current, HELP_TABS.length);
|
||||
if (n < 0) return;
|
||||
e.preventDefault();
|
||||
selectHelpTab(HELP_TABS[n].id);
|
||||
$("help-tab-" + HELP_TABS[n].id).focus();
|
||||
});
|
||||
}
|
||||
@@ -1,444 +1,19 @@
|
||||
// Plan2Code Web Console - User Preferences: looks, sounds and the launcher's model menus.
|
||||
// Plan2Code Web Console - User Preferences: the look and sound controls. The
|
||||
// Agents & models tab is agents-view.js's.
|
||||
|
||||
import { adoptLooks, applyLooks, loadLooks, looks, renderSwatches, resetLooks, saveLooks, syncLooks } from "../looks.js";
|
||||
import { adoptLooks, applyLooks, loadLooks, looks, renderSwatches, saveLooks, syncLooks } from "../looks.js";
|
||||
import { dropHeldSound, releaseHeldSound, sound, soundOn } from "../sound.js";
|
||||
import { hushTones, tone, unlockTones } from "../tones.js";
|
||||
import { hushMusic } from "../music.js";
|
||||
import { SOUND_EVENTS, soundKey } from "../palette.js";
|
||||
import { ROLES, ROLE_NOT_SET, ROLE_NOT_SET_LABEL, needsRoleNudge, normalizeRole } from "../starters.js";
|
||||
import { isDashboard } from "../selectors.js";
|
||||
import { el, lightDismiss } from "../render.js";
|
||||
import { page, redraw } from "../state.js";
|
||||
import { el } from "../render.js";
|
||||
import { hooks, page, redraw } from "../state.js";
|
||||
import { framed, onAppMessage, tellApp } from "../app-bridge.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
function setModelsStatus(text, isError) {
|
||||
const status = $("models-status");
|
||||
status.textContent = text;
|
||||
status.classList.toggle("error", Boolean(isError));
|
||||
}
|
||||
|
||||
// Models: the launcher's menu. The built-in list ships with every install and is read-only
|
||||
// here; what the person adds is saved to the server, which the launcher reads on its next run.
|
||||
let modelsData = null;
|
||||
|
||||
// The CLIs the launcher reads a model list for, in tab order (routes.mjs MODEL_CLIS).
|
||||
const MODEL_CLIS = ["claude", "devin", "codex"];
|
||||
|
||||
let modelsTab = "claude";
|
||||
|
||||
function renderModels() {
|
||||
for (const cli of MODEL_CLIS) {
|
||||
$("models-tab-" + cli).setAttribute("aria-pressed", String(cli === modelsTab));
|
||||
}
|
||||
const shipped = $("models-shipped");
|
||||
const user = $("models-user");
|
||||
shipped.replaceChildren();
|
||||
user.replaceChildren();
|
||||
if (!modelsData) {
|
||||
setModelsStatus("Models could not be loaded.", true);
|
||||
return;
|
||||
}
|
||||
for (const m of modelsData.shipped[modelsTab] || []) {
|
||||
const row = el("div", "models-row locked");
|
||||
row.append(el("span", null, m.id), el("span", null, m.label || ""));
|
||||
shipped.appendChild(row);
|
||||
}
|
||||
const mine = modelsData.user[modelsTab];
|
||||
mine.forEach((m, i) => {
|
||||
const row = el("div", "models-row");
|
||||
const id = el("input");
|
||||
id.value = m.id;
|
||||
id.placeholder = "Model id";
|
||||
id.setAttribute("aria-label", "Model id");
|
||||
const label = el("input");
|
||||
label.value = m.label;
|
||||
label.placeholder = "Name shown in the menu";
|
||||
label.setAttribute("aria-label", "Name shown in the menu");
|
||||
const remove = el("button", "btn small ghost", "Remove");
|
||||
remove.type = "button";
|
||||
id.addEventListener("change", () => { m.id = id.value.trim(); saveModels(); });
|
||||
label.addEventListener("change", () => { m.label = label.value.trim(); saveModels(); });
|
||||
remove.addEventListener("click", () => {
|
||||
mine.splice(i, 1);
|
||||
saveModels();
|
||||
renderModels();
|
||||
});
|
||||
row.append(id, label, remove);
|
||||
user.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
async function saveModels() {
|
||||
try {
|
||||
const res = await fetch("/models", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ models: modelsData.user }),
|
||||
});
|
||||
const body = await res.json();
|
||||
if (!res.ok) return setModelsStatus(body.error || "Could not save.", true);
|
||||
setModelsStatus("Saved. Restart plan2code to use it.", false);
|
||||
} catch {
|
||||
setModelsStatus("Could not save.", true);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadModelsData() {
|
||||
try {
|
||||
const res = await fetch("/models");
|
||||
if (res.ok) modelsData = await res.json();
|
||||
} catch {}
|
||||
renderModels();
|
||||
}
|
||||
|
||||
// Agents: CLIs Plan2Code did not find on its own, saved whole to ~/.plan2code/agents.json.
|
||||
// Each card edits its entry in place (unknown keys ride along untouched); every change
|
||||
// saves the whole list. A new card is not sent until it has a name and a command.
|
||||
let agentsData = [];
|
||||
|
||||
// The server's complaint about one card, drawn on it: { index, field, error } (index into agentsData).
|
||||
let agentsError = null;
|
||||
|
||||
// The entry whose Delete is waiting for a second click.
|
||||
let agentsConfirming = null;
|
||||
|
||||
// Every change saves, so two saves can be in flight at once: only the newest one's answer is drawn.
|
||||
let agentsSaveSeq = 0;
|
||||
|
||||
// The list as last loaded or saved, as sent: a change that leaves it the same (a field of a new
|
||||
// card still held back) sends nothing.
|
||||
let agentsLastSent = null;
|
||||
|
||||
function setAgentsStatus(text, isError) {
|
||||
const status = $("agents-status");
|
||||
status.textContent = text;
|
||||
status.classList.toggle("error", Boolean(isError));
|
||||
}
|
||||
|
||||
function newAgent() {
|
||||
return { name: "", command: "", args: [], prompt: "/plan2code", bypassArgs: [], modelArgs: ["--model", "{model}"], models: [] };
|
||||
}
|
||||
|
||||
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(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("change", () => {
|
||||
agent[key] = trim ? input.value.trim() : input.value;
|
||||
saveAgents();
|
||||
});
|
||||
return input;
|
||||
}
|
||||
|
||||
// A list of text rows (arguments), with Remove on each and an Add under them.
|
||||
function agentArgsEditor(agent, key, label, placeholder, addLabel) {
|
||||
const box = el("div", "agent-rows");
|
||||
box.dataset.field = key;
|
||||
const draw = () => {
|
||||
box.replaceChildren();
|
||||
agent[key].forEach((value, i) => {
|
||||
const row = el("div", "agent-row");
|
||||
const input = el("input");
|
||||
input.value = value;
|
||||
input.placeholder = placeholder;
|
||||
input.setAttribute("aria-label", label);
|
||||
input.dataset.field = key;
|
||||
input.addEventListener("change", () => { agent[key][i] = input.value.trim(); saveAgents(); });
|
||||
const remove = el("button", "btn small ghost", "Remove");
|
||||
remove.type = "button";
|
||||
remove.addEventListener("click", () => {
|
||||
agent[key].splice(i, 1);
|
||||
draw();
|
||||
saveAgents();
|
||||
});
|
||||
row.append(input, remove);
|
||||
box.appendChild(row);
|
||||
});
|
||||
const add = el("button", "btn small ghost", addLabel);
|
||||
add.type = "button";
|
||||
add.addEventListener("click", () => {
|
||||
agent[key].push("");
|
||||
draw();
|
||||
box.querySelector(".agent-row:last-of-type input")?.focus();
|
||||
});
|
||||
box.appendChild(add);
|
||||
};
|
||||
draw();
|
||||
return agentField(label, key, box);
|
||||
}
|
||||
|
||||
// The models list: an id and an optional name for the menu on each row.
|
||||
function agentModelsEditor(agent) {
|
||||
const box = el("div", "agent-rows");
|
||||
box.dataset.field = "models";
|
||||
const draw = () => {
|
||||
box.replaceChildren();
|
||||
agent.models.forEach((m, i) => {
|
||||
const row = el("div", "agent-row model");
|
||||
const id = el("input");
|
||||
id.value = m.id || "";
|
||||
id.placeholder = "Model id, for {model}";
|
||||
id.setAttribute("aria-label", "Model id");
|
||||
id.dataset.field = "models";
|
||||
const label = el("input");
|
||||
label.value = m.label || "";
|
||||
label.placeholder = "Name shown in the menu (optional)";
|
||||
label.setAttribute("aria-label", "Name shown in the menu");
|
||||
label.dataset.field = "models";
|
||||
const remove = el("button", "btn small ghost", "Remove");
|
||||
remove.type = "button";
|
||||
id.addEventListener("change", () => { m.id = id.value.trim(); saveAgents(); });
|
||||
label.addEventListener("change", () => {
|
||||
const text = label.value.trim();
|
||||
if (text) m.label = text;
|
||||
else delete m.label;
|
||||
saveAgents();
|
||||
});
|
||||
remove.addEventListener("click", () => {
|
||||
agent.models.splice(i, 1);
|
||||
draw();
|
||||
saveAgents();
|
||||
});
|
||||
row.append(id, label, remove);
|
||||
box.appendChild(row);
|
||||
});
|
||||
const add = el("button", "btn small ghost", "Add a model");
|
||||
add.type = "button";
|
||||
add.addEventListener("click", () => {
|
||||
agent.models.push({ id: "" });
|
||||
draw();
|
||||
box.querySelector(".agent-row:last-of-type input")?.focus();
|
||||
});
|
||||
box.appendChild(add);
|
||||
};
|
||||
draw();
|
||||
return agentField("Models", "models", box);
|
||||
}
|
||||
|
||||
// Test, and Delete with its confirm step on the card itself (never the browser's confirm()).
|
||||
function agentFoot(agent) {
|
||||
const foot = el("div", "agent-foot");
|
||||
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...";
|
||||
try {
|
||||
const res = await fetch("/agents/test", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ command }),
|
||||
});
|
||||
const body = await res.json();
|
||||
if (!res.ok) result.textContent = body.error || "Could not test.";
|
||||
else result.textContent = body.found ? "Found at " + body.path : "Not found on PATH";
|
||||
} catch {
|
||||
result.textContent = "Could not test.";
|
||||
}
|
||||
});
|
||||
foot.append(test);
|
||||
if (agentsConfirming === agent) {
|
||||
const ask = el("span", "help", "Delete this agent?");
|
||||
const yes = el("button", "btn small danger", "Yes, delete");
|
||||
yes.type = "button";
|
||||
const keep = el("button", "btn small ghost", "Keep");
|
||||
keep.type = "button";
|
||||
yes.addEventListener("click", async () => {
|
||||
agentsConfirming = null;
|
||||
agentsData.splice(agentsData.indexOf(agent), 1);
|
||||
agentsError = null;
|
||||
renderAgents();
|
||||
await saveAgents();
|
||||
});
|
||||
keep.addEventListener("click", () => {
|
||||
agentsConfirming = null;
|
||||
renderAgents();
|
||||
});
|
||||
foot.append(ask, yes, keep);
|
||||
} else {
|
||||
const del = el("button", "btn small ghost danger", "Delete");
|
||||
del.type = "button";
|
||||
del.addEventListener("click", () => {
|
||||
agentsConfirming = agent;
|
||||
renderAgents();
|
||||
});
|
||||
foot.append(del);
|
||||
}
|
||||
foot.append(result);
|
||||
return foot;
|
||||
}
|
||||
|
||||
// Which field or button has focus, so a redraw (an id assigned, an error marked) puts the
|
||||
// person back where they were, with what they had typed: { card, nth, value, start, end }.
|
||||
const AGENT_FOCUSABLE = "input, button";
|
||||
|
||||
function agentsFocus(list) {
|
||||
const active = document.activeElement;
|
||||
const card = active && list.contains(active) ? active.closest(".agent-card") : null;
|
||||
if (!card) return null;
|
||||
const at = { card: [...list.children].indexOf(card), nth: [...card.querySelectorAll(AGENT_FOCUSABLE)].indexOf(active) };
|
||||
if (active instanceof HTMLInputElement) Object.assign(at, { value: active.value, start: active.selectionStart, end: active.selectionEnd });
|
||||
return at;
|
||||
}
|
||||
|
||||
function restoreAgentsFocus(list, at) {
|
||||
const card = at && list.children[at.card];
|
||||
const target = card && card.querySelectorAll(AGENT_FOCUSABLE)[at.nth];
|
||||
if (!target) return;
|
||||
if (!(target instanceof HTMLInputElement) || at.value === undefined) {
|
||||
target.focus();
|
||||
return;
|
||||
}
|
||||
const drawn = target.value;
|
||||
target.value = at.value;
|
||||
target.focus();
|
||||
try {
|
||||
target.setSelectionRange(at.start, at.end);
|
||||
} catch {}
|
||||
// Text typed before the redraw is not in agentsData yet, and the browser fires no change
|
||||
// for a value set from script, so leaving the field sends it on.
|
||||
if (at.value !== drawn) target.addEventListener("blur", () => target.dispatchEvent(new Event("change")), { once: true });
|
||||
}
|
||||
|
||||
function renderAgents() {
|
||||
const list = $("agents-list");
|
||||
const focus = agentsFocus(list);
|
||||
list.replaceChildren();
|
||||
agentsData.forEach((agent, i) => {
|
||||
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) {
|
||||
if (!Array.isArray(agent[key])) agent[key] = [];
|
||||
}
|
||||
const card = el("div", "agent-card");
|
||||
const top = el("div", "agent-top");
|
||||
top.append(
|
||||
agentField("Name", "name", agentInput(agent, "name", "Name", "Name shown in the menu", true)),
|
||||
agentField("Command", "command", agentInput(agent, "command", "Command", "Program to run, such as myagent", true)),
|
||||
);
|
||||
card.append(
|
||||
top,
|
||||
agentArgsEditor(agent, "args", "Arguments", "--message={prompt}", "Add an argument"),
|
||||
agentField("Start prompt", "prompt", agentInput(agent, "prompt", "Start prompt", "/plan2code (blank starts with nothing typed)", false)),
|
||||
agentArgsEditor(agent, "bypassArgs", "Bypass arguments", "--yes-always", "Add an argument"),
|
||||
agentArgsEditor(agent, "modelArgs", "Model arguments", "--model={model}", "Add an argument"),
|
||||
agentModelsEditor(agent),
|
||||
);
|
||||
if (agentsError && agentsError.index === i) {
|
||||
card.classList.add("invalid");
|
||||
for (const input of card.querySelectorAll("input")) {
|
||||
if (input.dataset.field === agentsError.field) input.classList.add("invalid");
|
||||
}
|
||||
card.appendChild(el("p", "agent-error", agentsError.error));
|
||||
}
|
||||
card.appendChild(agentFoot(agent));
|
||||
list.appendChild(card);
|
||||
});
|
||||
restoreAgentsFocus(list, focus);
|
||||
}
|
||||
|
||||
// The list as the server wants it: blank rows dropped, and a new card without both a name and
|
||||
// a command (one still being typed) left out, so its first field is not refused as half an
|
||||
// agent. `kept` maps each sent entry back to its place.
|
||||
function agentsPayload() {
|
||||
const kept = [];
|
||||
const agents = [];
|
||||
agentsData.forEach((a, i) => {
|
||||
if (!a.id && (!String(a.name || "").trim() || !String(a.command || "").trim())) return;
|
||||
kept.push(i);
|
||||
agents.push({
|
||||
...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),
|
||||
});
|
||||
});
|
||||
return { kept, agents };
|
||||
}
|
||||
|
||||
// `replace` is the person's Save anyway, over a file holding entries this page could not read.
|
||||
async function saveAgents({ replace = false } = {}) {
|
||||
const { kept, agents } = agentsPayload();
|
||||
const sent = JSON.stringify(agents);
|
||||
if (!replace && agentsError === null && sent === agentsLastSent) return;
|
||||
const seq = ++agentsSaveSeq;
|
||||
try {
|
||||
const res = await fetch("/agents", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(replace ? { agents, replace: true } : { agents }),
|
||||
});
|
||||
const body = await res.json();
|
||||
if (seq !== agentsSaveSeq) return;
|
||||
if (res.status === 409) {
|
||||
const warnings = Array.isArray(body.warnings) ? body.warnings : [];
|
||||
setAgentsStatus([body.error || "Not saved.", ...warnings].join(" "), true);
|
||||
$("agents-replace").hidden = false;
|
||||
return;
|
||||
}
|
||||
$("agents-replace").hidden = true;
|
||||
if (!res.ok) {
|
||||
const at = Number.isInteger(body.index) ? kept[body.index] : undefined;
|
||||
agentsError = at === undefined ? null : { index: at, field: body.field, error: body.error || "Could not save." };
|
||||
setAgentsStatus(at === undefined ? body.error || "Could not save." : "Not saved. Fix the marked agent.", true);
|
||||
renderAgents();
|
||||
return;
|
||||
}
|
||||
// Ids are assigned on the first save: take the server's entries, and redraw only then
|
||||
// (or to clear a mark), so typing in another card is not interrupted.
|
||||
const fresh = agents.some((a) => !a.id) || agentsError !== null;
|
||||
agentsError = null;
|
||||
agentsLastSent = sent;
|
||||
setAgentsStatus("Saved.", false);
|
||||
if (fresh) {
|
||||
kept.forEach((at, n) => { agentsData[at] = body.agents[n]; });
|
||||
agentsLastSent = JSON.stringify(agentsPayload().agents);
|
||||
renderAgents();
|
||||
}
|
||||
} catch {
|
||||
if (seq === agentsSaveSeq) setAgentsStatus("Could not save.", true);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAgents() {
|
||||
agentsError = null;
|
||||
agentsConfirming = null;
|
||||
agentsLastSent = null;
|
||||
$("agents-replace").hidden = true;
|
||||
try {
|
||||
const res = await fetch("/agents");
|
||||
if (res.ok) {
|
||||
const body = await res.json();
|
||||
agentsData = Array.isArray(body.agents) ? body.agents : [];
|
||||
for (const agent of agentsData) {
|
||||
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) if (!Array.isArray(agent[key])) agent[key] = [];
|
||||
}
|
||||
agentsLastSent = JSON.stringify(agentsPayload().agents);
|
||||
const warnings = Array.isArray(body.warnings) ? body.warnings : [];
|
||||
setAgentsStatus(warnings.join(" "), warnings.length > 0);
|
||||
} else {
|
||||
setAgentsStatus("Agents could not be loaded.", true);
|
||||
}
|
||||
} catch {
|
||||
setAgentsStatus("Agents could not be loaded.", true);
|
||||
}
|
||||
renderAgents();
|
||||
}
|
||||
|
||||
// Following the system, the saved looks painted before anything is drawn, and
|
||||
// the sound cues let go on the next touch. `boot` is the page's boot data.
|
||||
export function startLooks(boot) {
|
||||
@@ -461,25 +36,15 @@ export function startLooks(boot) {
|
||||
}
|
||||
}
|
||||
|
||||
// Preferences' buttons and fields.
|
||||
// The fieldset a control sits in, for the Saved mark beside its legend.
|
||||
const fieldsetOf = (node) => node.closest("fieldset");
|
||||
|
||||
// Preferences' look and sound fields. Opening and closing the dialog, its tabs
|
||||
// and Back to default are prefs-dialog.js's.
|
||||
export function wireLooks() {
|
||||
lightDismiss($("looks-modal"));
|
||||
$("btn-looks").addEventListener("click", () => {
|
||||
renderSwatches();
|
||||
setModelsStatus("", false);
|
||||
loadModelsData();
|
||||
loadAgents();
|
||||
$("looks-modal").showModal();
|
||||
});
|
||||
$("looks-done").addEventListener("click", () => $("looks-modal").close());
|
||||
$("looks-modal").addEventListener("close", () => {
|
||||
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) redraw();
|
||||
});
|
||||
$("looks-reset").addEventListener("click", () => {
|
||||
resetLooks();
|
||||
saveLooks();
|
||||
redraw();
|
||||
});
|
||||
for (const [value, label] of [[ROLE_NOT_SET, ROLE_NOT_SET_LABEL], ...ROLES.map((r) => [r.id, r.label])]) {
|
||||
const option = el("option", null, label);
|
||||
option.value = value;
|
||||
@@ -487,7 +52,7 @@ export function wireLooks() {
|
||||
}
|
||||
$("looks-role").addEventListener("change", (e) => {
|
||||
looks.role = normalizeRole(e.target.value);
|
||||
saveLooks();
|
||||
hooks.markSaved(fieldsetOf(e.target), saveLooks());
|
||||
// The dashboard banner, and the starter templates and Ask starters on any
|
||||
// page, all order themselves by the role.
|
||||
if (page.S) redraw();
|
||||
@@ -495,13 +60,13 @@ export function wireLooks() {
|
||||
for (const radio of document.querySelectorAll('input[name="looks-theme"]')) {
|
||||
radio.addEventListener("change", () => {
|
||||
looks.theme = radio.value;
|
||||
saveLooks();
|
||||
hooks.markSaved(fieldsetOf(radio), saveLooks());
|
||||
});
|
||||
}
|
||||
for (const radio of document.querySelectorAll('input[name="looks-width"]')) {
|
||||
radio.addEventListener("change", () => {
|
||||
looks.width = radio.value;
|
||||
saveLooks();
|
||||
hooks.markSaved(fieldsetOf(radio), saveLooks());
|
||||
});
|
||||
}
|
||||
$("looks-sound").addEventListener("change", (e) => {
|
||||
@@ -509,15 +74,31 @@ export function wireLooks() {
|
||||
// Held cues are moments, not mail: muted, they are dropped rather than
|
||||
// saved up to fire all at once the next time sound comes back on.
|
||||
if (!looks.sound) dropHeldSound();
|
||||
saveLooks();
|
||||
hooks.markSaved(fieldsetOf(e.target), saveLooks());
|
||||
// Turning them on is the one change you can hear: the question chime, or
|
||||
// the first cue still ticked when that one is not.
|
||||
const preview = ["question", ...Object.keys(SOUND_EVENTS)].find(soundOn);
|
||||
if (preview) sound(preview);
|
||||
});
|
||||
// The games' sounds: off silences a game playing now; on plays a blip.
|
||||
$("looks-activity-sounds").addEventListener("change", (e) => {
|
||||
looks.activitySounds = e.target.checked;
|
||||
if (!looks.activitySounds) hushTones();
|
||||
hooks.markSaved(fieldsetOf(e.target), saveLooks());
|
||||
if (looks.activitySounds) {
|
||||
unlockTones();
|
||||
tone("go");
|
||||
}
|
||||
});
|
||||
// The games' music: off stops a track playing now.
|
||||
$("looks-game-music").addEventListener("change", (e) => {
|
||||
looks.gameMusic = e.target.checked;
|
||||
if (!looks.gameMusic) hushMusic();
|
||||
hooks.markSaved(fieldsetOf(e.target), saveLooks());
|
||||
});
|
||||
$("looks-activities").addEventListener("change", (e) => {
|
||||
looks.hideActivities = !e.target.checked;
|
||||
saveLooks();
|
||||
hooks.markSaved(fieldsetOf(e.target), saveLooks());
|
||||
// The die comes and goes with the next render, which also closes an open
|
||||
// Activities window, paused.
|
||||
redraw();
|
||||
@@ -527,40 +108,12 @@ export function wireLooks() {
|
||||
const event = box.dataset.sound;
|
||||
looks[soundKey(event)] = box.checked;
|
||||
if (!box.checked) dropHeldSound(event);
|
||||
saveLooks();
|
||||
hooks.markSaved(fieldsetOf(box), saveLooks());
|
||||
// Ticking one plays it, so the label has a sound to go with it.
|
||||
if (box.checked) sound(event);
|
||||
});
|
||||
}
|
||||
|
||||
for (const cli of MODEL_CLIS) {
|
||||
$("models-tab-" + cli).addEventListener("click", () => {
|
||||
modelsTab = cli;
|
||||
renderModels();
|
||||
});
|
||||
}
|
||||
$("models-add").addEventListener("click", () => {
|
||||
if (!modelsData) return;
|
||||
modelsData.user[modelsTab].push({ id: "", label: "" });
|
||||
renderModels();
|
||||
$("models-user").querySelector(".models-row:last-child input")?.focus();
|
||||
});
|
||||
$("agents-add").addEventListener("click", () => {
|
||||
agentsData.push(newAgent());
|
||||
renderAgents();
|
||||
$("agents-list").querySelector(".agent-card:last-child input")?.focus();
|
||||
});
|
||||
$("agents-replace").addEventListener("click", () => {
|
||||
$("agents-replace").hidden = true;
|
||||
saveAgents({ replace: true });
|
||||
});
|
||||
$("models-reset").addEventListener("click", () => {
|
||||
if (!modelsData) return;
|
||||
modelsData.user = Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
|
||||
saveModels();
|
||||
renderModels();
|
||||
});
|
||||
|
||||
// Desktop app: the taskbar switch, kept by the app in its own app.json. The
|
||||
// app says what it holds once the page is up; checked until it does.
|
||||
if (framed()) {
|
||||
|
||||
@@ -0,0 +1,550 @@
|
||||
// Plan2Code Web Console - the Implementation Loop's setup screen, drawn by the page from the console's saved setup and the app's facts; defines only.
|
||||
//
|
||||
// The dashboard's loop card opens this in place of the cards. Nothing here
|
||||
// runs an agent: Start saves the setup through POST /loop-setup, then asks the
|
||||
// desktop app (`loop-start { spec }`), which reads the setup itself and
|
||||
// confirms in its own window. The quick check is typed text the page never
|
||||
// runs or sends to the app.
|
||||
|
||||
import { el } from "../render.js";
|
||||
import { hooks, page, redraw } from "../state.js";
|
||||
import { SKILL_CATALOG } from "../answers.js";
|
||||
import { postJson } from "../net.js";
|
||||
import { tellApp, wireLoopMessages } from "../app-bridge.js";
|
||||
|
||||
const LEVELS = [
|
||||
["critical", "Critical"],
|
||||
["warning", "Warning"],
|
||||
["suggestion", "Suggestion"],
|
||||
];
|
||||
|
||||
const ON_QUESTION = [
|
||||
["guess", "Take the agent's best guess", "The agent picks the likeliest answer and records the assumption."],
|
||||
["pause", "Pause and wait for me", "The loop holds and calls you; nothing is lost while you are away."],
|
||||
["stop", "Stop the loop", "The loop ends at that phase and tells you what it asked."],
|
||||
];
|
||||
|
||||
const AFTER_LAST = [
|
||||
["offer-finalize", "Stop and offer Finalize", "You press Finalize when you have looked it over."],
|
||||
["run-finalize", "Run Finalize automatically", "Finalize starts by itself once every phase is built."],
|
||||
];
|
||||
|
||||
const DEFAULT_NOTIFY_PARAM = "message";
|
||||
// What the setup can send a notification to. `name` is the label for the field
|
||||
// the person names, on the kinds that have one.
|
||||
const NOTIFY_KINDS = [
|
||||
{ id: "query", label: "A web address, with the message in its query string", placeholder: "https://example.com/hook", hint: "The app calls this address with a GET.", name: "Query string name for the message" },
|
||||
{ id: "discord", label: "Discord webhook", placeholder: "https://discord.com/api/webhooks/...", hint: "In Discord: Edit Channel, Integrations, Webhooks, then Copy Webhook URL." },
|
||||
{ id: "slack", label: "Slack webhook", placeholder: "https://hooks.slack.com/services/...", hint: "An Incoming Webhook URL from your Slack app's settings." },
|
||||
{ id: "teams", label: "Microsoft Teams webhook", placeholder: "https://...", hint: 'In Teams: Workflows, the template "Post to a channel when a webhook request is received", then copy its URL.' },
|
||||
{ id: "google-chat", label: "Google Chat webhook", placeholder: "https://chat.googleapis.com/v1/spaces/...", hint: "In the space: Apps & integrations, Webhooks, then copy the URL." },
|
||||
{ id: "json", label: "A web address, with the message in a JSON body", placeholder: "https://example.com/hook", hint: "The app sends a POST with a JSON object holding the message, for any other service.", name: "JSON field name for the message" },
|
||||
];
|
||||
const SMART_DETAIL = "A fresh agent reads the review's findings and fixes the ones worth fixing. A skipped Critical stops the phase.";
|
||||
|
||||
/** Called by the page's start-up: hear the app's answers to the loop's requests. */
|
||||
export function wireLoopSetup() {
|
||||
wireLoopMessages(page, redraw);
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the setup screen for `spec` (the picker's selected spec object). The
|
||||
* saved setup and the read-only facts come from the console; the agent, model
|
||||
* and permission facts come from the app.
|
||||
*/
|
||||
export async function openLoopSetup(spec) {
|
||||
if (!spec || !spec.dir || page.gone || page.pendingResult || page.local.launching) return;
|
||||
const dir = spec.dir;
|
||||
page.loopStart = null;
|
||||
page.loopNotifyTest = null;
|
||||
page.loopSetup = { spec: dir, loaded: false, failed: false, form: null, facts: null, problems: [], starting: false };
|
||||
tellApp("loop-facts");
|
||||
redraw();
|
||||
const mine = page.loopSetup;
|
||||
let res;
|
||||
try {
|
||||
res = await fetch("/loop-setup?spec=" + encodeURIComponent(dir), { cache: "no-store" });
|
||||
} catch {
|
||||
res = null;
|
||||
}
|
||||
if (page.loopSetup !== mine) return;
|
||||
if (!res || !res.ok) {
|
||||
mine.failed = true;
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
const answer = await res.json().catch(() => null);
|
||||
if (page.loopSetup !== mine) return;
|
||||
if (!answer) {
|
||||
mine.failed = true;
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
const { phasesLeft, branch, pending, suggestedQuickCheck, remembered, saved, ...setup } = answer;
|
||||
mine.form = {
|
||||
review: setup.review !== false,
|
||||
fixMode: setup.fixMode === "levels" ? "levels" : "smart",
|
||||
fix: Array.isArray(setup.fix) ? [...setup.fix] : LEVELS.map(([k]) => k),
|
||||
commit: setup.commit !== false,
|
||||
onQuestion: setup.onQuestion || "guess",
|
||||
afterLast: setup.afterLast || "offer-finalize",
|
||||
quickCheck: typeof setup.quickCheck === "string" ? setup.quickCheck : "",
|
||||
retryOnce: setup.retryOnce !== false,
|
||||
silenceMinutes: Number.isInteger(setup.silenceMinutes) ? setup.silenceMinutes : 20,
|
||||
notifyKind: NOTIFY_KINDS.some((k) => k.id === setup.notifyKind) ? setup.notifyKind : "query",
|
||||
notifyUrl: typeof setup.notifyUrl === "string" ? setup.notifyUrl : "",
|
||||
notifyParam: setup.notifyParam || DEFAULT_NOTIFY_PARAM,
|
||||
};
|
||||
// A first visit with nothing typed starts from the project's own check.
|
||||
if (!remembered && !mine.form.quickCheck && suggestedQuickCheck) mine.form.quickCheck = suggestedQuickCheck;
|
||||
mine.facts = {
|
||||
phasesLeft: Array.isArray(phasesLeft) ? phasesLeft : [],
|
||||
branch: typeof branch === "string" ? branch : "",
|
||||
pending: Number.isInteger(pending) ? pending : null,
|
||||
};
|
||||
mine.loaded = true;
|
||||
redraw();
|
||||
}
|
||||
|
||||
function close() {
|
||||
page.loopSetup = null;
|
||||
page.loopStart = null;
|
||||
redraw();
|
||||
}
|
||||
|
||||
/**
|
||||
* Why Start is grayed, or "" when it can go (FR-5), in the spec's order.
|
||||
* Exported for the page's unit tests.
|
||||
*/
|
||||
export function startBlock(form, facts, appFacts) {
|
||||
if (!form || !facts) return "Loading the setup...";
|
||||
if (form.commit && facts.pending !== null && facts.pending > 0) {
|
||||
return `Commit each phase needs a clean tree: ${facts.pending} uncommitted ${facts.pending === 1 ? "change" : "changes"}.`;
|
||||
}
|
||||
if (!appFacts) return "Asking the app...";
|
||||
if (appFacts.permissionMode === "checked") return "The loop needs permission checks off. Start a New Session with checks off first.";
|
||||
if (appFacts.promptSupport === false) return "This agent cannot be started with a first prompt.";
|
||||
if (!facts.phasesLeft.length) return "Nothing left to build in this spec.";
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* What is wrong with the web address fields as typed, or "". The server checks
|
||||
* again on save; this is the line that shows while typing.
|
||||
*/
|
||||
export function notifyProblem(url, param, kind = "query") {
|
||||
const address = url.trim();
|
||||
if (!address) return "";
|
||||
if (!/^https?:\/\//i.test(address)) return "The web address must start with http:// or https://.";
|
||||
let good = /^https?:\/\/[^/?#@]+([/?#][!-~]*)?$/i.test(address) && !/[^!-~]/.test(address);
|
||||
if (good) {
|
||||
try {
|
||||
good = Boolean(new URL(address).hostname);
|
||||
} catch {
|
||||
good = false;
|
||||
}
|
||||
}
|
||||
if (!good) return "That is not a web address the app can call. Leave out any user name or password, and percent-encode spaces and accents.";
|
||||
const named = NOTIFY_KINDS.some((k) => k.id === kind && k.name);
|
||||
if (named && !/^[A-Za-z0-9._~-]{1,64}$/.test(param.trim() || DEFAULT_NOTIFY_PARAM)) return "The name can only use letters, digits, and - _ . ~";
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The chat service a pasted address belongs to, or "". A webhook needs a POST:
|
||||
* a GET to a Discord webhook answers 200 and posts nothing, so staying on the
|
||||
* query string kind would look like it worked.
|
||||
*/
|
||||
export function kindForUrl(url) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(url.trim());
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
const host = parsed.hostname.toLowerCase();
|
||||
const under = (domain) => host === domain || host.endsWith(`.${domain}`);
|
||||
if ((under("discord.com") || under("discordapp.com")) && parsed.pathname.startsWith("/api/webhooks/")) return "discord";
|
||||
if (host === "hooks.slack.com") return "slack";
|
||||
if (host === "chat.googleapis.com") return "google-chat";
|
||||
if (under("logic.azure.com") || under("powerplatform.com") || under("powerautomate.com")) return "teams";
|
||||
return "";
|
||||
}
|
||||
|
||||
function field(label, hint) {
|
||||
const box = el("div", "loop-field");
|
||||
box.appendChild(el("p", "loop-label", label));
|
||||
if (hint) box.appendChild(el("p", "loop-hint", hint));
|
||||
return box;
|
||||
}
|
||||
|
||||
function toggle(id, text, checked, onChange) {
|
||||
const label = el("label", "loop-switch");
|
||||
const input = el("input");
|
||||
input.type = "checkbox";
|
||||
input.id = id;
|
||||
input.checked = checked;
|
||||
input.addEventListener("change", () => onChange(input.checked));
|
||||
label.append(input, el("span", null, text));
|
||||
return label;
|
||||
}
|
||||
|
||||
function radios(name, options, current, onChange) {
|
||||
const group = el("div", "loop-radios");
|
||||
group.setAttribute("role", "radiogroup");
|
||||
for (const [value, text, detail] of options) {
|
||||
const label = el("label", "loop-radio");
|
||||
const input = el("input");
|
||||
input.type = "radio";
|
||||
input.name = name;
|
||||
input.id = `loop-${name}-${value}`;
|
||||
input.checked = current === value;
|
||||
input.addEventListener("change", () => input.checked && onChange(value));
|
||||
const body = el("span", "loop-radio-body");
|
||||
body.appendChild(el("span", "loop-radio-text", text));
|
||||
if (detail) body.appendChild(el("span", "loop-radio-detail", detail));
|
||||
label.append(input, body);
|
||||
group.appendChild(label);
|
||||
}
|
||||
return group;
|
||||
}
|
||||
|
||||
function factRow(list, label, value) {
|
||||
const row = el("div", "loop-fact");
|
||||
row.appendChild(el("dt", null, label));
|
||||
row.appendChild(el("dd", null, value));
|
||||
list.appendChild(row);
|
||||
}
|
||||
|
||||
function agentLine(facts, doing) {
|
||||
if (!facts) return "Asking the app...";
|
||||
const bits = [facts.agentLabel || facts.agent || "the app's agent"];
|
||||
bits.push(facts.model ? `model ${facts.model}` : "default model");
|
||||
bits.push(facts.effort ? `effort ${facts.effort}` : "default effort");
|
||||
return `${bits.join(", ")} (the app's launch choice, for ${doing})`;
|
||||
}
|
||||
|
||||
export function renderLoopSetup(main) {
|
||||
const s = page.loopSetup;
|
||||
const pane = el("div", "dash-confirm loop-setup");
|
||||
pane.appendChild(el("p", "card-kicker", "Step 3 · Implementation Loop"));
|
||||
pane.appendChild(el("h2", "dash-title", "Set up the loop"));
|
||||
const specLine = el("p", "confirm-spec");
|
||||
specLine.append(el("span", null, "for "), el("code", null, s.spec));
|
||||
pane.appendChild(specLine);
|
||||
|
||||
if (s.failed) {
|
||||
pane.appendChild(el("p", "loop-error", "The setup could not be read. Go back and try again."));
|
||||
} else if (!s.loaded) {
|
||||
const wait = el("p", "dash-working");
|
||||
wait.append(el("span", "spinner tiny"), el("span", null, "Loading the setup..."));
|
||||
pane.appendChild(wait);
|
||||
} else {
|
||||
drawBody(pane, s);
|
||||
}
|
||||
|
||||
const actions = el("div", "confirm-actions");
|
||||
const back = el("button", "btn ghost", "Back");
|
||||
back.type = "button";
|
||||
back.addEventListener("click", close);
|
||||
actions.appendChild(back);
|
||||
const help = el("button", "linky loop-help", "How the loop works");
|
||||
help.type = "button";
|
||||
help.addEventListener("click", () => hooks.openHelpOn("loop"));
|
||||
actions.appendChild(help);
|
||||
pane.appendChild(actions);
|
||||
main.appendChild(pane);
|
||||
}
|
||||
|
||||
function drawBody(pane, s) {
|
||||
const f = s.form;
|
||||
const redo = () => {
|
||||
s.problems = [];
|
||||
redraw();
|
||||
};
|
||||
|
||||
// What the app will do, in three plain lines (FR-3).
|
||||
const lines = el("div", "loop-lines");
|
||||
for (const text of [
|
||||
"The app builds each remaining phase in a fresh agent session, one after another, while you are away.",
|
||||
"After each phase it checks the work, marks it done and, if you chose, commits it to this branch. It never pushes.",
|
||||
"You can watch, play an Activity or stop it at any time from the banner at the top of the window.",
|
||||
]) {
|
||||
lines.appendChild(el("p", "loop-line", text));
|
||||
}
|
||||
pane.appendChild(lines);
|
||||
|
||||
// The read-only facts (FR-3).
|
||||
const facts = el("dl", "loop-facts");
|
||||
const left = s.facts.phasesLeft;
|
||||
factRow(facts, "Phases left", left.length ? left.map((p) => `Phase ${p.n}: ${p.name}`).join("\n") : "None");
|
||||
factRow(facts, "Building", agentLine(page.loopFacts, "building"));
|
||||
factRow(facts, "Reviewing", f.review ? agentLine(page.loopFacts, "reviewing") : "Review is off");
|
||||
factRow(facts, "Branch", s.facts.branch || "unknown");
|
||||
factRow(facts, "Uncommitted changes", s.facts.pending === null ? "unknown" : String(s.facts.pending));
|
||||
pane.appendChild(facts);
|
||||
|
||||
// The fields (FR-2, FR-4).
|
||||
const form = el("div", "loop-form");
|
||||
|
||||
const review = field("Review");
|
||||
review.appendChild(toggle("loop-review", "Review each phase with a fresh agent before it counts", f.review, (v) => ((f.review = v), redo())));
|
||||
form.appendChild(review);
|
||||
|
||||
if (f.review) {
|
||||
const fix = field("Fix findings");
|
||||
fix.appendChild(
|
||||
radios(
|
||||
"fixmode",
|
||||
[
|
||||
["smart", "Smart pick", SMART_DETAIL],
|
||||
["levels", "By level", "The agent fixes every finding at the levels you tick."],
|
||||
],
|
||||
f.fixMode,
|
||||
(v) => ((f.fixMode = v), redo())
|
||||
)
|
||||
);
|
||||
if (f.fixMode === "levels") {
|
||||
const row = el("div", "loop-ticks");
|
||||
for (const [key, text] of LEVELS) {
|
||||
row.appendChild(
|
||||
toggle(`loop-fix-${key}`, text, f.fix.includes(key), (on) => {
|
||||
f.fix = LEVELS.map(([k]) => k).filter((k) => (k === key ? on : f.fix.includes(k)));
|
||||
redo();
|
||||
})
|
||||
);
|
||||
}
|
||||
fix.appendChild(row);
|
||||
}
|
||||
form.appendChild(fix);
|
||||
}
|
||||
|
||||
const ask = field("When a phase asks something");
|
||||
ask.appendChild(radios("onquestion", ON_QUESTION, f.onQuestion, (v) => ((f.onQuestion = v), redo())));
|
||||
form.appendChild(ask);
|
||||
|
||||
const after = field("After the last phase");
|
||||
after.appendChild(radios("afterlast", AFTER_LAST, f.afterLast, (v) => ((f.afterLast = v), redo())));
|
||||
form.appendChild(after);
|
||||
|
||||
const notify = field(
|
||||
"Send a notification",
|
||||
"When the loop waits on your answer or ends, except when you stop it yourself, the app sends a short message saying which. Leave the address empty to send nothing."
|
||||
);
|
||||
const kindLabel = el("label", "loop-number");
|
||||
kindLabel.appendChild(el("span", null, "Send to"));
|
||||
const kindSelect = el("select", "loop-text");
|
||||
kindSelect.id = "loop-notify-kind";
|
||||
for (const kind of NOTIFY_KINDS) {
|
||||
const option = el("option", null, kind.label);
|
||||
option.value = kind.id;
|
||||
kindSelect.appendChild(option);
|
||||
}
|
||||
kindSelect.value = f.notifyKind;
|
||||
kindLabel.appendChild(kindSelect);
|
||||
const kindHint = el("p", "loop-hint");
|
||||
const notifyInput = el("input", "loop-text");
|
||||
notifyInput.type = "text";
|
||||
notifyInput.inputMode = "url";
|
||||
notifyInput.id = "loop-notify-url";
|
||||
notifyInput.value = f.notifyUrl;
|
||||
notifyInput.maxLength = 2000;
|
||||
notifyInput.setAttribute("aria-label", "Web address to call");
|
||||
const paramRow = el("div");
|
||||
const paramLabel = el("label", "loop-number");
|
||||
const paramText = el("span");
|
||||
paramLabel.appendChild(paramText);
|
||||
const paramInput = el("input", "loop-text loop-param");
|
||||
paramInput.type = "text";
|
||||
paramInput.id = "loop-notify-param";
|
||||
paramInput.value = f.notifyParam;
|
||||
paramInput.placeholder = DEFAULT_NOTIFY_PARAM;
|
||||
paramInput.maxLength = 64;
|
||||
paramLabel.appendChild(paramInput);
|
||||
paramRow.appendChild(paramLabel);
|
||||
const notifyWarn = el("p", "loop-warn");
|
||||
const testRow = el("div", "loop-test");
|
||||
const testButton = el("button", "btn", "Send a test");
|
||||
testButton.type = "button";
|
||||
testButton.id = "loop-notify-test";
|
||||
testButton.addEventListener("click", () => sendTest(s));
|
||||
testRow.appendChild(testButton);
|
||||
const testLine = notifyTestLine();
|
||||
if (testLine) testRow.appendChild(testLine);
|
||||
const showNotify = () => {
|
||||
const kind = NOTIFY_KINDS.find((k) => k.id === f.notifyKind);
|
||||
kindSelect.value = kind.id;
|
||||
kindHint.textContent = kind.hint;
|
||||
notifyInput.placeholder = kind.placeholder;
|
||||
paramText.textContent = kind.name || "";
|
||||
paramRow.hidden = !kind.name || f.notifyUrl.trim() === "";
|
||||
const problem = notifyProblem(f.notifyUrl, f.notifyParam, kind.id);
|
||||
notifyWarn.textContent = problem;
|
||||
notifyWarn.hidden = !problem;
|
||||
testButton.disabled = Boolean(problem) || f.notifyUrl.trim() === "" || Boolean(page.loopNotifyTest && page.loopNotifyTest.waiting) || s.starting;
|
||||
};
|
||||
// What a test said was about the address as it was.
|
||||
const forgetTest = () => {
|
||||
if (page.loopNotifyTest && !page.loopNotifyTest.waiting) {
|
||||
page.loopNotifyTest = null;
|
||||
testRow.querySelector("p")?.remove();
|
||||
}
|
||||
};
|
||||
notifyInput.addEventListener("input", () => {
|
||||
f.notifyUrl = notifyInput.value;
|
||||
forgetTest();
|
||||
// A pasted webhook picks its own kind, unless the person chose one here.
|
||||
const service = kindForUrl(f.notifyUrl);
|
||||
if (service && f.notifyKind === "query" && !s.notifyKindChosen) f.notifyKind = service;
|
||||
showNotify();
|
||||
});
|
||||
kindSelect.addEventListener("change", () => {
|
||||
f.notifyKind = kindSelect.value;
|
||||
forgetTest();
|
||||
s.notifyKindChosen = true;
|
||||
showNotify();
|
||||
});
|
||||
paramInput.addEventListener("input", () => {
|
||||
f.notifyParam = paramInput.value;
|
||||
forgetTest();
|
||||
showNotify();
|
||||
});
|
||||
showNotify();
|
||||
notify.append(kindLabel, notifyInput, kindHint, paramRow, notifyWarn, testRow);
|
||||
form.appendChild(notify);
|
||||
|
||||
const check = field("Quick check", "A command the app runs after each phase, such as npm run build. The page never runs it.");
|
||||
const checkInput = el("input", "loop-text");
|
||||
checkInput.type = "text";
|
||||
checkInput.id = "loop-quickcheck";
|
||||
checkInput.value = f.quickCheck;
|
||||
checkInput.placeholder = "npm run build";
|
||||
checkInput.maxLength = 500;
|
||||
checkInput.setAttribute("aria-label", "Quick check command");
|
||||
const checkWarn = el("p", "loop-warn", "No check runs after each phase.");
|
||||
checkWarn.hidden = f.quickCheck.trim() !== "";
|
||||
checkInput.addEventListener("input", () => {
|
||||
f.quickCheck = checkInput.value.replace(/[\r\n]+/g, " ");
|
||||
checkWarn.hidden = f.quickCheck.trim() !== "";
|
||||
});
|
||||
check.append(checkInput, checkWarn);
|
||||
form.appendChild(check);
|
||||
|
||||
const retry = field("If a phase crashes or goes quiet");
|
||||
retry.appendChild(toggle("loop-retry", "Retry it once", f.retryOnce, (v) => ((f.retryOnce = v), redo())));
|
||||
const silence = el("label", "loop-number");
|
||||
silence.appendChild(el("span", null, "Count the agent as stuck after this many minutes with no activity"));
|
||||
const silenceInput = el("input", "loop-text loop-narrow");
|
||||
silenceInput.type = "number";
|
||||
silenceInput.id = "loop-silence";
|
||||
silenceInput.min = "1";
|
||||
silenceInput.max = "60";
|
||||
silenceInput.step = "1";
|
||||
silenceInput.value = String(f.silenceMinutes);
|
||||
silenceInput.addEventListener("input", () => {
|
||||
f.silenceMinutes = Number(silenceInput.value);
|
||||
});
|
||||
silence.appendChild(silenceInput);
|
||||
retry.appendChild(silence);
|
||||
retry.appendChild(el("p", "loop-hint", "No activity means no file changes, in the project or the agent's session, so allow for your slowest build or test run. Waiting on your answer does not count."));
|
||||
form.appendChild(retry);
|
||||
|
||||
const commit = field("Commit");
|
||||
commit.appendChild(toggle("loop-commit", "Commit each phase to the current branch", f.commit, (v) => ((f.commit = v), redo())));
|
||||
form.appendChild(commit);
|
||||
|
||||
pane.appendChild(form);
|
||||
|
||||
// Start and the one line saying why it is grayed (FR-5).
|
||||
const block = startBlock(f, s.facts, page.loopFacts);
|
||||
const gated = Boolean(block);
|
||||
const foot = el("div", "loop-start");
|
||||
if (gated) {
|
||||
const why = el("p", "loop-why", block);
|
||||
why.setAttribute("role", "status");
|
||||
foot.appendChild(why);
|
||||
if (f.commit && s.facts.pending > 0) foot.appendChild(gitButton());
|
||||
}
|
||||
if (s.problems.length) {
|
||||
const bad = el("ul", "loop-problems");
|
||||
for (const p of s.problems) bad.appendChild(el("li", null, p));
|
||||
foot.appendChild(bad);
|
||||
}
|
||||
const waiting = s.starting && !page.loopStart;
|
||||
if (waiting) foot.appendChild(el("p", "loop-why", "Waiting for the app's confirm..."));
|
||||
if (page.loopStart && !page.loopStart.ok) foot.appendChild(el("p", "loop-error", page.loopStart.error));
|
||||
if (page.loopStart && page.loopStart.ok) foot.appendChild(el("p", "loop-why", "The loop is starting..."));
|
||||
const start = el("button", "btn primary", "Start the loop");
|
||||
start.type = "button";
|
||||
start.id = "loop-start";
|
||||
start.disabled = gated || waiting || page.gone || page.pendingResult || Boolean(page.loopStart && page.loopStart.ok);
|
||||
start.addEventListener("click", () => startLoop(s));
|
||||
foot.appendChild(start);
|
||||
pane.appendChild(foot);
|
||||
}
|
||||
|
||||
/** The line beside Send a test, or null with nothing to say. */
|
||||
function notifyTestLine() {
|
||||
const test = page.loopNotifyTest;
|
||||
if (!test) return null;
|
||||
if (test.waiting) return el("p", "loop-why", "Waiting for the app's confirm...");
|
||||
if (!test.ok) return el("p", "loop-error", test.error);
|
||||
if (test.sent) return el("p", "loop-why", "Sent, and the address answered OK. Check that the message arrived.");
|
||||
return null;
|
||||
}
|
||||
|
||||
function gitButton() {
|
||||
const b = el("button", "btn", "Open the Git board");
|
||||
b.type = "button";
|
||||
b.addEventListener("click", () => {
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-git");
|
||||
if (entry) hooks.launchSkill(entry);
|
||||
});
|
||||
return b;
|
||||
}
|
||||
|
||||
/** The form as the console saves it. */
|
||||
function setupBody(f) {
|
||||
return { ...f, quickCheck: f.quickCheck.trim(), notifyUrl: f.notifyUrl.trim(), notifyParam: f.notifyParam.trim() || DEFAULT_NOTIFY_PARAM };
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a test: save, so the app can read what is on screen, then ask it. The
|
||||
* message names nothing: the app takes the address from the saved setup and
|
||||
* confirms it in its own dialog, as it does for Start.
|
||||
*/
|
||||
async function sendTest(s) {
|
||||
const f = s.form;
|
||||
if (!f.notifyUrl.trim() || notifyProblem(f.notifyUrl, f.notifyParam, f.notifyKind) || (page.loopNotifyTest && page.loopNotifyTest.waiting)) return;
|
||||
s.problems = [];
|
||||
page.loopNotifyTest = { waiting: true };
|
||||
redraw();
|
||||
const { status, body: answer } = await postJson("/loop-setup", setupBody(f));
|
||||
if (page.loopSetup !== s) return;
|
||||
if (status !== 200 || !answer || answer.ok !== true) {
|
||||
page.loopNotifyTest = null;
|
||||
s.problems = Array.isArray(answer && answer.problems) && answer.problems.length ? answer.problems : ["The setup could not be saved. Try again."];
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
tellApp("loop-notify-test");
|
||||
}
|
||||
|
||||
async function startLoop(s) {
|
||||
const f = s.form;
|
||||
if (startBlock(f, s.facts, page.loopFacts) || (s.starting && !page.loopStart)) return;
|
||||
s.problems = [];
|
||||
page.loopStart = null;
|
||||
s.starting = true;
|
||||
redraw();
|
||||
const { status, body: answer } = await postJson("/loop-setup", setupBody(f));
|
||||
if (page.loopSetup !== s) return;
|
||||
if (status !== 200 || !answer || answer.ok !== true) {
|
||||
s.starting = false;
|
||||
s.problems = Array.isArray(answer && answer.problems) && answer.problems.length ? answer.problems : ["The setup could not be saved. Try again."];
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
tellApp("loop-start", { spec: s.spec });
|
||||
redraw();
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
// Plan2Code Web Console - the User Preferences dialog: its tabs, the one way
|
||||
// to open and close it, the Saved mark, Back to default for the tab on screen
|
||||
// and the prompt that stops an unsaved agent edit being lost.
|
||||
|
||||
import { onSwatchSaved, renderSwatches, resetLooks, saveLooks } from "../looks.js";
|
||||
import { PREFS_TABS, prefsOpenTab, prefsResetScope } from "../prefs.js";
|
||||
import { wireTabs } from "../tabs.js";
|
||||
import { el, lightDismiss } from "../render.js";
|
||||
import { hooks, redraw } from "../state.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
let prefsTabs = null;
|
||||
|
||||
// Back to default only where the tab has looks to reset.
|
||||
function showResetFor(id) {
|
||||
$("looks-reset").hidden = prefsResetScope(id) === null;
|
||||
}
|
||||
|
||||
// The small mark at the top right of a fieldset, level with its legend:
|
||||
// "Saved", fading, or the error in its place, kept until that fieldset saves
|
||||
// again. `result` is what saveLooks() resolves, or a Promise of it; a `text`
|
||||
// in it replaces the word Saved.
|
||||
const markTimers = new WeakMap();
|
||||
|
||||
function clearMark(mark) {
|
||||
clearTimeout(markTimers.get(mark));
|
||||
if (mark.classList.contains("is-saved")) mark.textContent = "";
|
||||
}
|
||||
|
||||
export async function markSaved(fieldset, result) {
|
||||
if (!fieldset) return;
|
||||
let mark = fieldset.querySelector(":scope > .prefs-saved");
|
||||
if (!mark) {
|
||||
mark = el("span", "prefs-saved");
|
||||
mark.setAttribute("role", "status");
|
||||
// Gone after the fade, or after the same time when motion is reduced and
|
||||
// no animation runs to say so (the timer below).
|
||||
mark.addEventListener("animationend", () => clearMark(mark));
|
||||
fieldset.appendChild(mark);
|
||||
}
|
||||
const { ok, error, text } = (await result) || { ok: true };
|
||||
// A newer save owns the mark: an earlier one's timer must not blank it.
|
||||
clearTimeout(markTimers.get(mark));
|
||||
mark.classList.remove("is-saved", "error");
|
||||
// Restart the fade when the same fieldset saves twice in a row.
|
||||
void mark.offsetWidth;
|
||||
if (ok) {
|
||||
mark.textContent = text || "Saved";
|
||||
mark.classList.add("is-saved");
|
||||
markTimers.set(mark, setTimeout(() => clearMark(mark), 2200));
|
||||
} else {
|
||||
mark.textContent = error || "Could not save.";
|
||||
mark.classList.add("error");
|
||||
}
|
||||
}
|
||||
|
||||
// Every way in: the gear, the dashboard's Set up preferences, or a caller
|
||||
// naming the tab it wants. Agents and models load each time it opens.
|
||||
export function openPrefs(tab) {
|
||||
renderSwatches();
|
||||
hooks.loadAgentsView();
|
||||
prefsTabs.select(prefsOpenTab(tab));
|
||||
$("looks-modal").showModal();
|
||||
$("prefs-tab-" + prefsTabs.current()).focus();
|
||||
}
|
||||
|
||||
// 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).
|
||||
let asking = null;
|
||||
|
||||
// Everything in the dialog but the prompt, kept out of reach while it asks.
|
||||
const behindPrompt = () => [$("looks-title"), $("looks-modal").querySelector(".prefs-body"), $("looks-modal").querySelector(".modal-actions")];
|
||||
|
||||
function endAsking(go) {
|
||||
$("prefs-unsaved").hidden = true;
|
||||
for (const node of behindPrompt()) node.inert = false;
|
||||
const { resolve, from } = asking;
|
||||
asking = null;
|
||||
// Keep editing (or a failed Save) goes back into the form; going on hands
|
||||
// focus back to what asked, so the action it carries on with owns it.
|
||||
if (!go) hooks.focusOpen();
|
||||
else if (from && from.isConnected && !from.closest("[hidden]")) from.focus();
|
||||
resolve(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
|
||||
// editing, asked inside the dialog. Resolves true when it may go on.
|
||||
export function confirmUnsaved() {
|
||||
if (!hooks.hasUnsaved()) return Promise.resolve(true);
|
||||
if (asking) return asking.promise;
|
||||
let resolve;
|
||||
const promise = new Promise((r) => (resolve = r));
|
||||
asking = { resolve, promise, from: document.activeElement };
|
||||
$("prefs-unsaved-name").textContent = hooks.unsavedName();
|
||||
for (const node of behindPrompt()) node.inert = true;
|
||||
$("prefs-unsaved").hidden = false;
|
||||
$("prefs-unsaved-save").disabled = false;
|
||||
$("prefs-unsaved-save").focus();
|
||||
return promise;
|
||||
}
|
||||
|
||||
// Plain true while nothing is unsaved, so a tab switch or a close happens in
|
||||
// this same tick.
|
||||
const guard = () => (hooks.hasUnsaved() || asking ? confirmUnsaved() : true);
|
||||
|
||||
async function closePrefs() {
|
||||
if (await guard()) $("looks-modal").close();
|
||||
}
|
||||
|
||||
function wireUnsaved() {
|
||||
const box = el("div", "prefs-unsaved");
|
||||
box.id = "prefs-unsaved";
|
||||
box.hidden = true;
|
||||
box.setAttribute("role", "alertdialog");
|
||||
box.setAttribute("aria-labelledby", "prefs-unsaved-title");
|
||||
box.setAttribute("aria-describedby", "prefs-unsaved-text");
|
||||
const inner = el("div", "prefs-unsaved-box");
|
||||
const title = el("h3", null, "Unsaved changes");
|
||||
title.id = "prefs-unsaved-title";
|
||||
const text = el("p");
|
||||
text.id = "prefs-unsaved-text";
|
||||
const name = el("strong");
|
||||
name.id = "prefs-unsaved-name";
|
||||
text.append("You have unsaved changes to ", name, ".");
|
||||
const save = el("button", "btn small primary", "Save");
|
||||
save.type = "button";
|
||||
save.id = "prefs-unsaved-save";
|
||||
const discard = el("button", "btn small ghost", "Discard");
|
||||
discard.type = "button";
|
||||
const keep = el("button", "btn small ghost", "Keep editing");
|
||||
keep.type = "button";
|
||||
save.addEventListener("click", async () => {
|
||||
save.disabled = true;
|
||||
const ok = await hooks.saveOpen();
|
||||
save.disabled = false;
|
||||
if (asking) endAsking(ok);
|
||||
});
|
||||
discard.addEventListener("click", () => {
|
||||
hooks.discardOpen();
|
||||
endAsking(true);
|
||||
});
|
||||
keep.addEventListener("click", () => endAsking(false));
|
||||
const actions = el("div", "prefs-unsaved-actions");
|
||||
actions.append(save, discard, keep);
|
||||
inner.append(title, text, actions);
|
||||
box.append(inner);
|
||||
$("looks-modal").append(box);
|
||||
}
|
||||
|
||||
export function wirePrefs() {
|
||||
const dlg = $("looks-modal");
|
||||
wireUnsaved();
|
||||
lightDismiss(dlg, guard);
|
||||
$("looks-done").addEventListener("click", closePrefs);
|
||||
// Esc: held while a form has an unsaved edit, and Keep editing while the prompt asks.
|
||||
dlg.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Escape") return;
|
||||
if (asking) {
|
||||
e.preventDefault();
|
||||
endAsking(false);
|
||||
} else if (hooks.hasUnsaved()) {
|
||||
e.preventDefault();
|
||||
closePrefs();
|
||||
}
|
||||
});
|
||||
dlg.addEventListener("cancel", (e) => {
|
||||
if (!asking && !hooks.hasUnsaved()) return;
|
||||
e.preventDefault();
|
||||
if (!asking) closePrefs();
|
||||
});
|
||||
hooks.wireAgentsView();
|
||||
prefsTabs = wireTabs({
|
||||
tabs: PREFS_TABS,
|
||||
list: $("prefs-tabs"),
|
||||
panels: $("prefs-panels"),
|
||||
prefix: "prefs",
|
||||
tabClass: "prefs-tab",
|
||||
beforeSelect: () => guard(),
|
||||
// The hint describes the tab rather than naming it, so a screen reader's
|
||||
// tab name stays the label, at any width.
|
||||
renderTab: (t, btn) => {
|
||||
const hint = el("span", "prefs-tab-hint", t.hint);
|
||||
hint.id = "prefs-hint-" + t.id;
|
||||
hint.setAttribute("aria-hidden", "true");
|
||||
btn.append(el("span", "prefs-tab-label", t.label), hint);
|
||||
btn.setAttribute("aria-describedby", hint.id);
|
||||
},
|
||||
onSelect: (id) => {
|
||||
showResetFor(id);
|
||||
$("looks-modal").querySelector(".prefs-body").scrollTop = 0;
|
||||
},
|
||||
});
|
||||
$("btn-looks").addEventListener("click", () => openPrefs());
|
||||
$("looks-reset").addEventListener("click", () => {
|
||||
const tab = prefsTabs.current();
|
||||
const keys = prefsResetScope(tab);
|
||||
if (!keys) return;
|
||||
resetLooks(keys);
|
||||
const saved = saveLooks();
|
||||
redraw();
|
||||
markSaved($("prefs-panel-" + tab).querySelector("fieldset"), saved);
|
||||
});
|
||||
onSwatchSaved((saved) => markSaved($("looks-swatches").closest("fieldset"), saved));
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { page, redraw } from "../state.js";
|
||||
import { el, approvalTip } from "../render.js";
|
||||
import { startPose, startingHint, staleLaunchFeedback, workflowTitle } from "../answers.js";
|
||||
import { skillByName } from "../skills.js";
|
||||
import { agentAdrift, doingNow, docs } from "../selectors.js";
|
||||
import { agentAdrift, doingNow, docs, loopDriving } from "../selectors.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -132,10 +132,12 @@ function renderStarting(main) {
|
||||
const elapsed = startingElapsed();
|
||||
const pane = posePane(main, "launching starting", page.S.workflow);
|
||||
pane.appendChild(el("p", "card-kicker", "Starting up"));
|
||||
pane.appendChild(el("h2", "launch-title", `Starting ${workflowTitle(page.S.workflow)}`));
|
||||
const looping = loopDriving();
|
||||
pane.appendChild(el("h2", "launch-title", looping ? "The loop is starting this phase" : `Starting ${workflowTitle(page.S.workflow)}`));
|
||||
pane.appendChild(el("p", "launch-quip", START_QUIPS[Math.floor(elapsed / 2600) % START_QUIPS.length]));
|
||||
pane.appendChild(el("p", "launch-hint", startingHint(elapsed)));
|
||||
pane.appendChild(approvalTip());
|
||||
// A loop runs with permission checks off, so no approval will come.
|
||||
if (!looping) pane.appendChild(approvalTip());
|
||||
startLaunchTicker();
|
||||
}
|
||||
|
||||
@@ -180,8 +182,17 @@ function startLaunchTicker() {
|
||||
}
|
||||
}
|
||||
|
||||
// A phase that has reported is not starting: the app is checking the report,
|
||||
// running the quick check and committing, which can take minutes.
|
||||
function renderLoopChecking(main) {
|
||||
const pane = posePane(main, "waiting-pane", page.S.workflow);
|
||||
pane.appendChild(el("h2", null, "The loop is checking this phase"));
|
||||
pane.appendChild(el("p", null, "The agent has reported. The app is checking that against the spec before it moves on, so you don't need to do anything."));
|
||||
}
|
||||
|
||||
export function renderWaiting(main) {
|
||||
const doing = doingNow();
|
||||
if (!doing && loopDriving() && page.S.loopOutcome) return renderLoopChecking(main);
|
||||
// Nothing asked and nothing said yet: the session is still starting.
|
||||
if (!doing) return renderStarting(main);
|
||||
// The same Planny the session started with, still at it: the spinner that
|
||||
@@ -199,7 +210,9 @@ export function renderWaiting(main) {
|
||||
}
|
||||
pane.appendChild(title);
|
||||
pane.appendChild(el("p", null, doing));
|
||||
const ask = "If Plan2Code needs you, the question appears here on its own.";
|
||||
const ask = loopDriving()
|
||||
? "The loop is running this phase by itself, so you don't need to do anything. If it needs you, the question appears here."
|
||||
: "If Plan2Code needs you, the question appears here on its own.";
|
||||
if (!docs().length) {
|
||||
pane.appendChild(el("p", null, ask));
|
||||
return;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { hooks, page } from "../state.js";
|
||||
import { copyButton, el, lightDismiss, selectContents } from "../render.js";
|
||||
import { selSpec, specList, workspaceFolders } from "../selectors.js";
|
||||
import { loopDriving, selSpec, specList, workspaceFolders } from "../selectors.js";
|
||||
import { postJson } from "../net.js";
|
||||
import { nameProblem } from "../workspace.js";
|
||||
|
||||
@@ -114,6 +114,12 @@ export function renderWorkspace() {
|
||||
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
|
||||
$("workspace-browse").hidden = Boolean(page.wsFrame && page.wsFrame.remote);
|
||||
$("workspace-scope").textContent = workspaceScopeText();
|
||||
// The loop's agents were started with this workspace; changing it now would
|
||||
// reach nobody (FR-15). Reading and copying paths stays.
|
||||
const locked = loopDriving();
|
||||
for (const id of ["workspace-add", "workspace-browse", "workspace-path"]) $(id).disabled = locked || (id === "workspace-add" && wsBusy);
|
||||
for (const rm of list.querySelectorAll(".ws-remove")) rm.disabled = locked;
|
||||
if (locked) setAddMsg("The workspace is fixed while the loop builds.");
|
||||
}
|
||||
|
||||
function workspaceRow(f) {
|
||||
@@ -281,7 +287,7 @@ function paintWorkspaceRow(li, f) {
|
||||
// sent when the person took a suggested name after a clash.
|
||||
async function addWorkspaceFolder(path, name) {
|
||||
const trimmed = String(path || "").trim();
|
||||
if (!trimmed || wsBusy) return;
|
||||
if (!trimmed || wsBusy || loopDriving()) return;
|
||||
wsBusy = true;
|
||||
$("workspace-add").disabled = true;
|
||||
const { status, body } = await postJson("/workspace/add", name ? { path: trimmed, name } : { path: trimmed });
|
||||
@@ -318,7 +324,7 @@ async function addWorkspaceFolder(path, name) {
|
||||
|
||||
async function browseWorkspace() {
|
||||
const b = $("workspace-browse");
|
||||
if (b.disabled) return;
|
||||
if (b.disabled || loopDriving()) return;
|
||||
b.disabled = true;
|
||||
setAddMsg("Waiting for the folder picker…");
|
||||
const { status, body } = await postJson("/workspace/browse", {});
|
||||
|
||||
Reference in new issue
Block a user