mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-18 13:01:18 -08:00
Split the web console into by-job files, add page tests and a docs-table test, plus docs
AI Assisted
This commit is contained in:
1 parent
699a827cae
commit
3edb4468a8
121 files changed
+25603
-20145
No files matched your search
@@ -0,0 +1,855 @@
|
||||
// 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 { el, md, isMac, lightDismiss, shortTime } from "../render.js";
|
||||
import { startersFor } from "../starters.js";
|
||||
import { looks } from "../looks.js";
|
||||
import { thumbs, uploadUrl, docChip, attachTray, CHAT_IMAGES, attachFiles, incomingFiles, deleteUrl, sentAttachments, noteImages, attachRow } from "../uploads.js";
|
||||
import { attachMentions } from "../mention-box.js";
|
||||
import { pickerAccept, attachmentKind, noteAwaiting, threadWho, threadText } from "../answers.js";
|
||||
import { postJson } from "../net.js";
|
||||
import { CHECKIN_LINE, helperRows, showSwitch, switchLabel, defaultInstruction, PATHFINDER_RESEARCH_LINE } from "../subagents.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// The Quick question chat's page-local state, gone on a reload (the frame's
|
||||
// own `chat` block, the Ask tab's dot and the rest are on `page`, state.js).
|
||||
let chatSending = false;
|
||||
|
||||
let chatResetting = false;
|
||||
|
||||
let askPaintedOffline = false;
|
||||
|
||||
export const declineOpen = new Map();
|
||||
|
||||
const deciding = new Set();
|
||||
|
||||
// The frame's chat block, with `offline` worked out now rather than when the
|
||||
// frame was sent: the agent comes and goes between frames, and /ping keeps
|
||||
// agentLastSeen current. The frame's own verdict stands when there is no clock.
|
||||
function askFrame() {
|
||||
const base = page.chatFrame || { conversation: 0, messages: [], typed: 0, limit: 10, offline: false };
|
||||
if (!page.S || !page.agentLastSeen) return base;
|
||||
const offline = chatOffline({
|
||||
finish: finish(),
|
||||
agent: page.S.agent,
|
||||
agentLastSeenMs: Date.parse(page.agentLastSeen),
|
||||
now: Date.now(),
|
||||
});
|
||||
return { ...base, offline };
|
||||
}
|
||||
|
||||
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 }) };
|
||||
}
|
||||
|
||||
// The conversation a send belongs to. The page's own record wins over the
|
||||
// frame for the moment after a 409 stale, before the new frame lands.
|
||||
const askConversation = () => page.local.chat.conversation ?? askFrame().conversation;
|
||||
|
||||
export function renderAsk(main) {
|
||||
const { frame, view: v, send: ss } = askState();
|
||||
// Anything drawn here has been seen: no dot for it later.
|
||||
const newest = newestReplyId(frame);
|
||||
if (newest && page.local.chat.lastSeenReplyId !== newest) {
|
||||
page.local.chat.lastSeenReplyId = newest;
|
||||
saveNow();
|
||||
}
|
||||
page.chatDot = false;
|
||||
askPaintedOffline = ss.state === "offline";
|
||||
|
||||
const pane = el("section", "ask-pane");
|
||||
const head = el("div", "ask-head");
|
||||
head.appendChild(el("h2", null, "Quick question"));
|
||||
head.appendChild(el("span", "ask-counter", v.counterText));
|
||||
const reset = el("button", "btn small ghost", "New conversation");
|
||||
reset.type = "button";
|
||||
reset.disabled = ss.state === "offline" || chatResetting;
|
||||
reset.addEventListener("click", newConversation);
|
||||
head.appendChild(reset);
|
||||
pane.appendChild(head);
|
||||
|
||||
const list = el("div", "ask-list");
|
||||
list.setAttribute("role", "log");
|
||||
list.setAttribute("aria-live", "polite");
|
||||
if (!v.rows.length) list.appendChild(askStarters(ss));
|
||||
const notes = new Map(v.rows.filter((r) => r.kind === "decision").map((r) => [r.re, r.text]));
|
||||
for (const r of v.rows) list.appendChild(askRow(r, ss, notes));
|
||||
pane.appendChild(list);
|
||||
pane.appendChild(askComposer(ss));
|
||||
main.appendChild(pane);
|
||||
|
||||
// Back where the person left the list, unless something new arrived (or it
|
||||
// is the first look), which brings the newest row into view.
|
||||
const saved = scrollMemory.get("ask");
|
||||
const grew = v.rows.length > page.askRowCount;
|
||||
page.askRowCount = v.rows.length;
|
||||
list.scrollTop = !saved || grew ? list.scrollHeight : saved.top;
|
||||
}
|
||||
|
||||
// An empty conversation offers a few questions for this step, the role's
|
||||
// first. A click only fills the box: nothing is ever sent for the person.
|
||||
function askStarters(ss) {
|
||||
const box = el("div", "ask-starters");
|
||||
box.appendChild(el("p", "ask-starters-lead", "Not sure what to ask? Try one of these:"));
|
||||
for (const starter of startersFor(page.S.workflow, looks.role, { hasContext: Boolean(page.local.chat.about) })) {
|
||||
const b = el("button", "ask-starter", starter.text);
|
||||
b.type = "button";
|
||||
b.disabled = !ss.canType;
|
||||
b.addEventListener("click", () => {
|
||||
page.local.chat.draft = starter.text;
|
||||
saveNow();
|
||||
redraw();
|
||||
const ta = $("ask-input");
|
||||
if (!ta) return;
|
||||
ta.focus();
|
||||
ta.setSelectionRange(ta.value.length, ta.value.length);
|
||||
});
|
||||
box.appendChild(b);
|
||||
}
|
||||
return box;
|
||||
}
|
||||
|
||||
function askRow(r, ss, notes) {
|
||||
if (r.kind === "decision") {
|
||||
const row = el("div", "ask-row decision");
|
||||
row.appendChild(el("p", "ask-decision", r.decision !== "approve" ? "You declined the edit." : r.done ? "You approved the edit." : "You approved the edit, please wait..."));
|
||||
if (r.text) row.appendChild(el("p", "ask-text", r.text));
|
||||
return row;
|
||||
}
|
||||
if (r.kind === "agent") {
|
||||
const row = el("div", "ask-row agent");
|
||||
row.appendChild(el("div", "msg-who", "Plan2Code"));
|
||||
row.appendChild(md(r.md, "md"));
|
||||
if (r.proposal) row.appendChild(askProposal(r, ss, notes.get(r.id)));
|
||||
if (Array.isArray(r.changed) && r.changed.length) {
|
||||
const ul = el("ul", "ask-changed");
|
||||
for (const c of r.changed) {
|
||||
const li = el("li");
|
||||
li.appendChild(el("code", null, c.file));
|
||||
li.appendChild(el("span", "ask-changed-count", ` +${c.added} −${c.removed}`));
|
||||
ul.appendChild(li);
|
||||
}
|
||||
row.appendChild(ul);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
const row = el("div", "ask-row person" + (r.pending ? " pending" : ""));
|
||||
if (r.about && r.about.label) row.appendChild(el("p", "ask-about", "About: " + r.about.label));
|
||||
row.appendChild(el("p", "ask-text", r.text));
|
||||
const hasImages = r.images && r.images.length;
|
||||
const hasFiles = r.files && r.files.length;
|
||||
if (hasImages || hasFiles) {
|
||||
const tray = el("div", "attach-tray");
|
||||
for (const img of r.images || []) {
|
||||
const fig = el("figure", "attach-thumb is-ready");
|
||||
const pic = el("img");
|
||||
pic.src = thumbs.get(img.key) || uploadUrl(img);
|
||||
pic.alt = img.name || "image";
|
||||
fig.appendChild(pic);
|
||||
tray.appendChild(fig);
|
||||
}
|
||||
for (const file of r.files || []) tray.appendChild(docChip(file, "ready"));
|
||||
row.appendChild(tray);
|
||||
}
|
||||
if (r.pending && r.failed) {
|
||||
const fail = el("p", "ask-waiting ask-failed", "Not sent — retry");
|
||||
const retry = el("button", "btn tiny", "Retry");
|
||||
retry.type = "button";
|
||||
retry.disabled = ss.state === "offline" || chatSending;
|
||||
retry.addEventListener("click", () => retryChat(r.tempId));
|
||||
fail.appendChild(retry);
|
||||
row.appendChild(fail);
|
||||
} else if (r.pending) {
|
||||
row.appendChild(el("p", "ask-waiting", "Sending…"));
|
||||
} else if (r.waiting) {
|
||||
const wait = el("p", "ask-waiting");
|
||||
// Picked up and still answering: the ring says so, unless the agent has
|
||||
// gone quiet, when a turning ring would pass a dead session for a slow one.
|
||||
if (r.working && ss.state !== "offline" && !agentAdrift()) {
|
||||
const spin = el("span", "spinner tiny");
|
||||
spin.setAttribute("aria-hidden", "true");
|
||||
wait.appendChild(spin);
|
||||
}
|
||||
wait.appendChild(el("span", null, r.waitingText));
|
||||
row.appendChild(wait);
|
||||
if (r.activity) row.appendChild(el("p", "ask-waiting", "Right now: " + r.activity));
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
function askProposal(r, ss, note) {
|
||||
const box = el("div", "ask-proposal");
|
||||
box.appendChild(el("p", "note-kicker", "Proposed change"));
|
||||
box.appendChild(md(r.proposal.summary, "md"));
|
||||
const files = el("ul", "ask-proposal-files");
|
||||
for (const f of r.proposal.files || []) {
|
||||
const li = el("li");
|
||||
li.appendChild(el("code", null, f));
|
||||
files.appendChild(li);
|
||||
}
|
||||
box.appendChild(files);
|
||||
|
||||
if (r.decided) {
|
||||
box.appendChild(el("p", "ask-decided " + r.decided, r.decided === "approve" ? "Approved" : "Declined"));
|
||||
if (note) box.appendChild(el("p", "help", note));
|
||||
return box;
|
||||
}
|
||||
const busy = deciding.has(r.id) || ss.state === "offline";
|
||||
const row = el("div", "ask-proposal-actions");
|
||||
const approve = el("button", "btn small primary", "Approve");
|
||||
approve.type = "button";
|
||||
approve.disabled = busy;
|
||||
approve.addEventListener("click", () => decideChat(r.id, "approve", ""));
|
||||
row.appendChild(approve);
|
||||
if (!declineOpen.has(r.id)) {
|
||||
const decline = el("button", "btn small ghost", "Decline");
|
||||
decline.type = "button";
|
||||
decline.disabled = busy;
|
||||
decline.addEventListener("click", () => {
|
||||
declineOpen.set(r.id, "");
|
||||
redraw();
|
||||
$("decline-" + r.id)?.focus();
|
||||
});
|
||||
row.appendChild(decline);
|
||||
} else {
|
||||
const input = el("input");
|
||||
input.type = "text";
|
||||
input.id = "decline-" + r.id;
|
||||
input.placeholder = "Why not? (optional)";
|
||||
input.maxLength = CHAT_MAX_CHARS;
|
||||
input.value = declineOpen.get(r.id) || "";
|
||||
input.addEventListener("input", () => declineOpen.set(r.id, input.value));
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Enter") return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
decideChat(r.id, "decline", input.value);
|
||||
});
|
||||
row.appendChild(input);
|
||||
const go = el("button", "btn small", "Send decline");
|
||||
go.type = "button";
|
||||
go.disabled = busy;
|
||||
go.addEventListener("click", () => decideChat(r.id, "decline", declineOpen.get(r.id) || ""));
|
||||
row.appendChild(go);
|
||||
}
|
||||
box.appendChild(row);
|
||||
if (deciding.has(r.id)) box.appendChild(el("p", "help", "Sent. It will show here once Plan2Code has it."));
|
||||
return box;
|
||||
}
|
||||
|
||||
const COUNTER_FROM = 3500;
|
||||
|
||||
function askComposer(ss) {
|
||||
const comp = el("div", "ask-composer");
|
||||
const about = page.local.chat.about;
|
||||
if (about) {
|
||||
const chip = el("div", "ask-about-chip");
|
||||
chip.appendChild(el("span", null, "About: " + about.label));
|
||||
const x = el("button", "attach-remove", "×");
|
||||
x.type = "button";
|
||||
x.setAttribute("aria-label", "Send without this");
|
||||
x.addEventListener("click", () => {
|
||||
Object.assign(page.local.chat, nextAbout(page.local.chat, { type: "drop" }));
|
||||
saveNow();
|
||||
redraw();
|
||||
});
|
||||
chip.appendChild(x);
|
||||
comp.appendChild(chip);
|
||||
}
|
||||
if (page.local.chat.images.length) comp.appendChild(attachTray(CHAT_IMAGES, page.local.chat.images));
|
||||
|
||||
const ta = el("textarea");
|
||||
ta.id = "ask-input";
|
||||
ta.placeholder = "Ask anything about this project";
|
||||
ta.value = page.local.chat.draft || "";
|
||||
ta.disabled = !ss.canType;
|
||||
ta.setAttribute("aria-label", "Your question");
|
||||
attachMentions(ta);
|
||||
comp.appendChild(ta);
|
||||
|
||||
const row = el("div", "ask-actions");
|
||||
const add = el("button", "btn small ghost", "+ Attach file");
|
||||
add.type = "button";
|
||||
add.setAttribute("aria-label", "Add files to this question");
|
||||
add.disabled = !ss.canType || page.local.chat.images.length >= CHAT_MAX_ATTACHMENTS;
|
||||
const picker = el("input");
|
||||
picker.type = "file";
|
||||
picker.accept = pickerAccept();
|
||||
picker.multiple = true;
|
||||
picker.hidden = true;
|
||||
add.addEventListener("click", () => picker.click());
|
||||
picker.addEventListener("change", () => {
|
||||
attachFiles(CHAT_IMAGES, picker.files);
|
||||
picker.value = "";
|
||||
});
|
||||
row.appendChild(add);
|
||||
row.appendChild(picker);
|
||||
if (!page.local.chat.about) row.appendChild(addContext(ss));
|
||||
|
||||
// Where the counter sits, the reason Send is off when it cannot be typed in:
|
||||
// the limit, the last question still waiting, or nobody there to answer.
|
||||
const counter = el("span", "ask-count");
|
||||
if (!ss.canType) {
|
||||
const cls = ss.state === "offline" ? "is-offline" : ss.state === "limit" ? "is-limit" : "is-waiting";
|
||||
row.appendChild(el("p", "ask-disabled-note " + cls, ss.text));
|
||||
} else {
|
||||
row.appendChild(counter);
|
||||
const hint = el("span", "ask-send-hint");
|
||||
hint.appendChild(el("kbd", null, isMac() ? "⌘" : "Ctrl"));
|
||||
hint.appendChild(document.createTextNode(" + "));
|
||||
hint.appendChild(el("kbd", null, "Enter"));
|
||||
row.appendChild(hint);
|
||||
}
|
||||
|
||||
const go = el("button", "btn small primary", "Send");
|
||||
go.type = "button";
|
||||
row.appendChild(go);
|
||||
comp.appendChild(row);
|
||||
if (page.chatError) comp.appendChild(el("p", "ask-error", page.chatError));
|
||||
|
||||
const held = () => page.local.chat.images.some((img) => img.status !== "ready");
|
||||
const sync = () => {
|
||||
const len = ta.value.length;
|
||||
counter.textContent = len >= COUNTER_FROM ? `${len} / ${CHAT_MAX_CHARS}` : "";
|
||||
counter.classList.toggle("is-over", len > CHAT_MAX_CHARS);
|
||||
go.disabled = !ss.canType || chatSending || !ta.value.trim() || len > CHAT_MAX_CHARS || held();
|
||||
};
|
||||
sync();
|
||||
ta.addEventListener("input", () => {
|
||||
page.local.chat.draft = ta.value;
|
||||
saveNow();
|
||||
sync();
|
||||
});
|
||||
// Ctrl/Cmd+Enter sends and a plain Enter is a line break. Every Enter stops
|
||||
// here, so the page-wide Ctrl+Enter never sends the question cards from this box.
|
||||
ta.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Enter") return;
|
||||
e.stopPropagation();
|
||||
if (!(e.ctrlKey || e.metaKey) || e.isComposing) return;
|
||||
e.preventDefault();
|
||||
if (!go.disabled) sendChat();
|
||||
});
|
||||
ta.addEventListener("paste", (e) => {
|
||||
const files = incomingFiles(e.clipboardData && e.clipboardData.files);
|
||||
if (!files.length || !ss.canType) return;
|
||||
if (!e.clipboardData.getData("text/plain")) e.preventDefault();
|
||||
attachFiles(CHAT_IMAGES, files);
|
||||
});
|
||||
const canDrop = (e) => ss.canType && e.dataTransfer && [...e.dataTransfer.types].includes("Files");
|
||||
const onOver = (e) => {
|
||||
if (!canDrop(e)) return;
|
||||
e.preventDefault();
|
||||
comp.classList.add("is-dropping");
|
||||
};
|
||||
comp.addEventListener("dragenter", onOver);
|
||||
comp.addEventListener("dragover", onOver);
|
||||
comp.addEventListener("dragleave", (e) => {
|
||||
if (!comp.contains(e.relatedTarget)) comp.classList.remove("is-dropping");
|
||||
});
|
||||
comp.addEventListener("drop", (e) => {
|
||||
comp.classList.remove("is-dropping");
|
||||
if (!canDrop(e)) return;
|
||||
e.preventDefault();
|
||||
attachFiles(CHAT_IMAGES, e.dataTransfer.files);
|
||||
});
|
||||
go.addEventListener("click", sendChat);
|
||||
return comp;
|
||||
}
|
||||
|
||||
const CONTEXT_KIND = { card: "Question", section: "Section", spec: "Spec" };
|
||||
|
||||
// + Add context: the only way a message gets an `about`. A menu of the last
|
||||
// three places visited, then This spec, built fresh on every render.
|
||||
function addContext(ss) {
|
||||
const wrap = el("span", "ask-context");
|
||||
const spec = isDashboard() ? selSpec() : page.S && page.S.specDir ? { dir: page.S.specDir } : null;
|
||||
const options = contextOptions(page.local.chat, spec);
|
||||
const btn = el("button", "btn small ghost", "+ Add context");
|
||||
btn.type = "button";
|
||||
btn.setAttribute("aria-haspopup", "menu");
|
||||
btn.setAttribute("aria-expanded", "false");
|
||||
btn.disabled = !ss.canType || !options.length;
|
||||
if (!options.length) btn.title = "Visit a question or a document section first";
|
||||
wrap.appendChild(btn);
|
||||
|
||||
let menu = null;
|
||||
const outside = (e) => {
|
||||
if (!wrap.contains(e.target)) close();
|
||||
};
|
||||
// Focus moves before the menu goes: removing the focused item fires a
|
||||
// focusout of its own, which would otherwise re-enter here.
|
||||
const close = (refocus) => {
|
||||
if (!menu) return;
|
||||
const gone = menu;
|
||||
menu = null;
|
||||
btn.setAttribute("aria-expanded", "false");
|
||||
document.removeEventListener("pointerdown", outside, true);
|
||||
if (refocus) btn.focus();
|
||||
gone.remove();
|
||||
};
|
||||
const open = () => {
|
||||
menu = el("div", "ask-context-menu");
|
||||
menu.setAttribute("role", "menu");
|
||||
menu.setAttribute("aria-label", "Add context");
|
||||
for (const option of options) {
|
||||
const item = el("button", "ask-context-item");
|
||||
item.type = "button";
|
||||
item.setAttribute("role", "menuitem");
|
||||
item.appendChild(el("span", "ask-context-label", option.label));
|
||||
item.appendChild(el("span", "ask-context-kind", CONTEXT_KIND[option.kind] || ""));
|
||||
item.addEventListener("click", () => {
|
||||
close();
|
||||
Object.assign(page.local.chat, nextAbout(page.local.chat, { type: "pick", about: option }));
|
||||
saveNow();
|
||||
redraw();
|
||||
});
|
||||
menu.appendChild(item);
|
||||
}
|
||||
// A press inside the menu never moves focus. Safari (and Firefox on
|
||||
// macOS) do not focus a clicked button, so the press would blur the
|
||||
// focused item to nowhere and the focusout below would close the menu
|
||||
// before the click landed.
|
||||
menu.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
menu.addEventListener("keydown", (e) => {
|
||||
const items = [...menu.querySelectorAll('[role="menuitem"]')];
|
||||
const at = items.indexOf(document.activeElement);
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
close(true);
|
||||
} else if (e.key === "ArrowDown" || e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
const step = e.key === "ArrowDown" ? 1 : -1;
|
||||
items[(at + step + items.length) % items.length].focus();
|
||||
} else if (e.key === "Home" || e.key === "End") {
|
||||
e.preventDefault();
|
||||
items[e.key === "Home" ? 0 : items.length - 1].focus();
|
||||
}
|
||||
});
|
||||
wrap.appendChild(menu);
|
||||
btn.setAttribute("aria-expanded", "true");
|
||||
document.addEventListener("pointerdown", outside, true);
|
||||
menu.querySelector('[role="menuitem"]').focus();
|
||||
};
|
||||
btn.addEventListener("click", () => (menu ? close() : open()));
|
||||
wrap.addEventListener("focusout", (e) => {
|
||||
if (menu && !wrap.contains(e.relatedTarget)) close();
|
||||
});
|
||||
return wrap;
|
||||
}
|
||||
|
||||
const CHAT_ERRORS = {
|
||||
stale: "A new conversation started. Your message is still here — press Send again.",
|
||||
"too-long": `That message is over ${CHAT_MAX_CHARS.toLocaleString()} characters. Shorten it and send again.`,
|
||||
image: "One of the images could not be attached. Remove it and try again.",
|
||||
file: "One of the files could not be attached. Remove it and try again.",
|
||||
};
|
||||
|
||||
async function sendChat() {
|
||||
const text = (page.local.chat.draft || "").trim();
|
||||
const { send: ss } = askState();
|
||||
if (!text || chatSending || !ss.canType || text.length > CHAT_MAX_CHARS) return;
|
||||
if (page.local.chat.images.some((img) => img.status !== "ready")) return;
|
||||
const ofKind = (kind) => page.local.chat.images.filter((a) => attachmentKind(a) === kind);
|
||||
const pend = {
|
||||
tempId: crypto.randomUUID(),
|
||||
text,
|
||||
about: page.local.chat.about,
|
||||
images: ofKind("image").map(({ key, path, name, url }) => ({ key, path, name, url })),
|
||||
files: ofKind("file").map(({ key, path, name, size }) => ({ key, path, name, size })),
|
||||
};
|
||||
page.local.chat.pending.push(pend);
|
||||
saveNow();
|
||||
await postChat(pend);
|
||||
}
|
||||
|
||||
function retryChat(tempId) {
|
||||
const pend = page.local.chat.pending.find((p) => p.tempId === tempId);
|
||||
if (!pend || chatSending) return;
|
||||
pend.failed = false;
|
||||
saveNow();
|
||||
postChat(pend);
|
||||
}
|
||||
|
||||
async function postChat(pend) {
|
||||
chatSending = true;
|
||||
page.chatError = "";
|
||||
redraw();
|
||||
let res = null;
|
||||
let body = {};
|
||||
try {
|
||||
res = await fetch("/chat", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
text: pend.text,
|
||||
about: pend.about || undefined,
|
||||
images: pend.images.length ? pend.images.map(({ path, name }) => ({ path, name })) : undefined,
|
||||
files: pend.files && pend.files.length ? pend.files.map(({ path, name }) => ({ path, name })) : undefined,
|
||||
conversation: askConversation(),
|
||||
}),
|
||||
});
|
||||
body = await res.json().catch(() => ({}));
|
||||
} catch {
|
||||
res = null;
|
||||
}
|
||||
chatSending = false;
|
||||
const still = page.local.chat.pending.find((p) => p.tempId === pend.tempId);
|
||||
if (!res) {
|
||||
if (still) still.failed = true;
|
||||
} else if (res.ok) {
|
||||
if (still) still.seq = body.seq;
|
||||
// What was sent leaves the composer, and the context leaves with it: a
|
||||
// follow-up is a general question unless it is picked again.
|
||||
Object.assign(page.local.chat, nextAbout(page.local.chat, { type: "sent" }));
|
||||
if ((page.local.chat.draft || "").trim() === pend.text) {
|
||||
page.local.chat.draft = "";
|
||||
page.local.chat.images = [];
|
||||
}
|
||||
} else {
|
||||
page.local.chat.pending = page.local.chat.pending.filter((p) => p.tempId !== pend.tempId);
|
||||
if (body.error === "stale" && typeof body.conversation === "number") page.local.chat.conversation = body.conversation;
|
||||
// A limit or offline refusal needs no words: the disabled composer says why.
|
||||
if (body.error !== "limit" && body.error !== "offline") {
|
||||
page.chatError = CHAT_ERRORS[body.error] || "That message could not be sent. Try again.";
|
||||
}
|
||||
}
|
||||
saveNow();
|
||||
redraw();
|
||||
}
|
||||
|
||||
async function newConversation() {
|
||||
// One reset at a time: a second press would only come back stale and put
|
||||
// an error under the clean conversation the first one opened.
|
||||
if (chatResetting) return;
|
||||
chatResetting = true;
|
||||
redraw();
|
||||
let res = null;
|
||||
let body = {};
|
||||
try {
|
||||
res = await fetch("/chat", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ reset: true, conversation: askConversation() }),
|
||||
});
|
||||
body = await res.json().catch(() => ({}));
|
||||
} catch {}
|
||||
if (res && res.ok) {
|
||||
// An explicit fresh start: the unsent draft and its pictures go too.
|
||||
for (const img of page.local.chat.images) if (img.id) fetch(deleteUrl(img), { method: "DELETE" }).catch(() => {});
|
||||
page.local.chat = { ...freshChat(), history: page.local.chat.history, about: null, conversation: body.conversation };
|
||||
page.chatError = "";
|
||||
page.askRowCount = 0;
|
||||
declineOpen.clear();
|
||||
} else if (body.error === "stale" && typeof body.conversation === "number") {
|
||||
page.local.chat.conversation = body.conversation;
|
||||
page.chatError = "A new conversation had already started.";
|
||||
} else if (body.error !== "offline") {
|
||||
page.chatError = "A new conversation could not be started. Try again.";
|
||||
}
|
||||
chatResetting = false;
|
||||
saveNow();
|
||||
redraw();
|
||||
}
|
||||
|
||||
async function decideChat(re, decision, text) {
|
||||
if (deciding.has(re)) return;
|
||||
deciding.add(re);
|
||||
page.chatError = "";
|
||||
redraw();
|
||||
let ok = false;
|
||||
let body = {};
|
||||
try {
|
||||
const res = await fetch("/chat/decision", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ re, decision, text: text.trim() || undefined, conversation: askConversation() }),
|
||||
});
|
||||
ok = res.ok;
|
||||
body = await res.json().catch(() => ({}));
|
||||
} catch {}
|
||||
// Kept in `deciding` on success: the buttons stay off until the frame
|
||||
// brings the decision back, rather than flashing live again in between.
|
||||
if (ok) declineOpen.delete(re);
|
||||
else {
|
||||
deciding.delete(re);
|
||||
page.chatError =
|
||||
body.error === "stale"
|
||||
? "That proposal belongs to an earlier conversation."
|
||||
: "That decision could not be sent. Try again.";
|
||||
}
|
||||
redraw();
|
||||
}
|
||||
|
||||
export function renderAside() {
|
||||
const aside = $("aside");
|
||||
// Redrawing empties the panel, which drops its scroll to the top. An image
|
||||
// upload redraws two or three times while the person watches its tray, so
|
||||
// the place is kept while the same question stays on screen.
|
||||
const place = aside.dataset.item === String(page.selected) ? aside.scrollTop : 0;
|
||||
aside.replaceChildren();
|
||||
aside.dataset.item = String(page.selected);
|
||||
// The end page is about the session, not any one question: the notes that
|
||||
// belong to a question stay on its own page.
|
||||
const item = page.view === "end" ? null : byId(page.selected);
|
||||
if (!item) {
|
||||
// The menu has no questions, so no notes either: the pane stays empty.
|
||||
if (!isDashboard()) aside.appendChild(el("p", "aside-empty", "Pick a question to see its notes."));
|
||||
return;
|
||||
}
|
||||
// Off the question's own page (a doc tab, Ask) "this" points at nothing on
|
||||
// screen, so the pane names the question a note here will go to.
|
||||
const onQuestion = page.view === "questions" || page.view === "end";
|
||||
aside.appendChild(el("h2", null, onQuestion ? "Notes on this" : `Notes on “${item.title || "this question"}”`));
|
||||
|
||||
const thread = item.thread || [];
|
||||
if (!thread.length && !(isOpen(item) && !finish() && noteAwaiting(item))) {
|
||||
aside.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"aside-empty",
|
||||
isOpen(item) && !finish()
|
||||
? "No back and forth yet. Anything you type here goes with your next send."
|
||||
: "Nothing was said about this one."
|
||||
)
|
||||
);
|
||||
}
|
||||
// A note that has been sent but not yet picked up: marked as waiting, so the
|
||||
// send is seen to have gone, until the agent replies. The server writes the
|
||||
// note into the thread as it arrives; a session from before that has only
|
||||
// `sentNote`, which gets a box of its own below.
|
||||
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
||||
let waitingShown = false;
|
||||
for (const m of thread) {
|
||||
const mine = threadWho(m) === "user";
|
||||
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
|
||||
if (pending) waitingShown = true;
|
||||
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
|
||||
const who = el("div", "msg-who");
|
||||
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
|
||||
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
|
||||
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
||||
box.appendChild(who);
|
||||
const text = threadText(m);
|
||||
if (text) box.appendChild(md(text, "md"));
|
||||
const tray = mine ? sentAttachments(m) : null;
|
||||
if (tray) box.appendChild(tray);
|
||||
aside.appendChild(box);
|
||||
}
|
||||
|
||||
if (waiting && !waitingShown) {
|
||||
const box = el("div", "msg you pending");
|
||||
const who = el("div", "msg-who");
|
||||
who.appendChild(el("span", null, "You"));
|
||||
who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
|
||||
box.appendChild(who);
|
||||
if (waiting.text) box.appendChild(md(waiting.text, "md"));
|
||||
const tray = sentAttachments(waiting);
|
||||
if (tray) box.appendChild(tray);
|
||||
aside.appendChild(box);
|
||||
}
|
||||
|
||||
// A finished session has nobody left for a note to reach, so the box would
|
||||
// be a place to type words that go nowhere.
|
||||
if (!isOpen(item) || finish()) {
|
||||
aside.scrollTop = place;
|
||||
return;
|
||||
}
|
||||
|
||||
const wrap = el("div", "field");
|
||||
const id = "thread-" + item.id;
|
||||
const label = el("label", null, "Add a note, attach a file, or ask something");
|
||||
label.htmlFor = id;
|
||||
wrap.appendChild(label);
|
||||
|
||||
const attached = noteImages(item.id);
|
||||
wrap.appendChild(attachRow(item.id, "Add files to this note"));
|
||||
|
||||
if (attached.length) wrap.appendChild(attachTray(item.id, attached));
|
||||
|
||||
const ta = el("textarea");
|
||||
ta.id = id;
|
||||
ta.placeholder = "Goes with your next send. It does not answer the question.";
|
||||
ta.value = page.local.drafts[id] || "";
|
||||
attachMentions(ta);
|
||||
ta.addEventListener("input", () => {
|
||||
setDraft(id, ta.value);
|
||||
hooks.renderFooter();
|
||||
});
|
||||
ta.addEventListener("paste", (e) => {
|
||||
const files = incomingFiles(e.clipboardData && e.clipboardData.files);
|
||||
if (!files.length) return;
|
||||
// A copy from some apps carries the picture and its text together; the
|
||||
// text still pastes as it always did.
|
||||
if (!e.clipboardData.getData("text/plain")) e.preventDefault();
|
||||
attachFiles(item.id, files);
|
||||
});
|
||||
wrap.appendChild(ta);
|
||||
aside.appendChild(wrap);
|
||||
aside.scrollTop = place;
|
||||
}
|
||||
|
||||
// The helpers the agent reported, as it last posted them. Everything here is
|
||||
// the agent's text, so it goes in as text, never as markup.
|
||||
export function renderSubagents(main) {
|
||||
const card = el("section", "card sa-card");
|
||||
card.appendChild(el("h2", null, "Subagents"));
|
||||
card.appendChild(el("p", "help", CHECKIN_LINE));
|
||||
const { alone, rows } = helperRows(page.S.helpers);
|
||||
if (alone) {
|
||||
card.appendChild(
|
||||
el("p", "sa-alone", "Working alone: your agent has no way to start helpers here, so it is doing this skill's work itself.")
|
||||
);
|
||||
main.appendChild(card);
|
||||
return;
|
||||
}
|
||||
const list = el("ul", "sa-list");
|
||||
for (const row of rows) {
|
||||
const item = el("li", "sa-row");
|
||||
const head = el("div", "sa-head");
|
||||
head.appendChild(el("strong", "sa-title", row.title));
|
||||
const pill = el("span", "pill sa-pill is-" + row.state);
|
||||
if (row.state === "running") {
|
||||
const spin = el("span", "spinner tiny");
|
||||
spin.setAttribute("aria-hidden", "true");
|
||||
pill.appendChild(spin);
|
||||
}
|
||||
pill.appendChild(document.createTextNode(row.stateLabel));
|
||||
head.appendChild(pill);
|
||||
item.appendChild(head);
|
||||
item.appendChild(el("p", "sa-ask", row.ask));
|
||||
if (row.result) item.appendChild(el("p", "sa-result", row.result));
|
||||
list.appendChild(item);
|
||||
}
|
||||
card.appendChild(list);
|
||||
main.appendChild(card);
|
||||
}
|
||||
|
||||
// Shown only where the skill opts in and the agent's console copy can deliver
|
||||
// it. Lit while helpers are on; a click opens the dialog, never toggles.
|
||||
export function renderSubagentsButton() {
|
||||
const btn = $("btn-subagents");
|
||||
const offer = showSwitch(page.subagentsFrame);
|
||||
btn.hidden = !offer;
|
||||
if (!offer) return;
|
||||
const label = switchLabel(page.subagentsFrame);
|
||||
btn.setAttribute("aria-pressed", String(Boolean(page.subagentsFrame.on)));
|
||||
btn.title = label;
|
||||
btn.setAttribute("aria-label", label);
|
||||
btn.disabled = page.gone;
|
||||
}
|
||||
|
||||
// The Subagents dialog, filled from the frame each time it opens. A null
|
||||
// instruction is the shipped default, shown as its text so it can be edited.
|
||||
export function openSubagents() {
|
||||
if (!showSwitch(page.subagentsFrame)) return;
|
||||
const on = Boolean(page.subagentsFrame.on);
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) {
|
||||
radio.checked = radio.value === (on ? "on" : "off");
|
||||
}
|
||||
$("subagents-instruction").value = page.subagentsFrame.instruction ?? defaultInstruction(page.S.workflow);
|
||||
$("subagents-max").value = String(page.subagentsFrame.max);
|
||||
$("subagents-checkin").textContent = CHECKIN_LINE;
|
||||
const research = $("subagents-research");
|
||||
research.textContent = PATHFINDER_RESEARCH_LINE;
|
||||
research.hidden = page.S.workflow !== "pathfinder";
|
||||
$("subagents-status").textContent = "";
|
||||
$("subagents-save").disabled = false;
|
||||
syncSubagentsFields();
|
||||
$("subagents-modal").showModal();
|
||||
const checked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
if (checked) checked.focus();
|
||||
}
|
||||
|
||||
// Instruction and "at most" only mean anything with helpers on, so they are
|
||||
// inert under Work alone (kept as typed, for when helpers go back on).
|
||||
export function syncSubagentsFields() {
|
||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
const off = !picked || picked.value !== "on";
|
||||
for (const id of ["subagents-instruction", "subagents-max", "subagents-default"]) $(id).disabled = off;
|
||||
}
|
||||
|
||||
const SUBAGENTS_ERRORS = {
|
||||
max: "Pick a number from 1 to 20.",
|
||||
"too-long": "The instruction is over 2,000 characters.",
|
||||
"not-offered": "This skill doesn't use helpers.",
|
||||
bad: "That didn't save. Try again.",
|
||||
};
|
||||
|
||||
const SUBAGENTS_LOST = "Lost contact with Plan2Code. Try again once it's back.";
|
||||
|
||||
export async function saveSubagents() {
|
||||
const save = $("subagents-save");
|
||||
const status = $("subagents-status");
|
||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
const text = $("subagents-instruction").value.trim();
|
||||
// The shipped default is stored as null, so a later release's wording
|
||||
// reaches everyone who never changed it.
|
||||
const instruction = text === defaultInstruction(page.S.workflow) ? null : text;
|
||||
const body = { on: Boolean(picked && picked.value === "on"), instruction, max: Number($("subagents-max").value) };
|
||||
save.disabled = true;
|
||||
status.textContent = "";
|
||||
const res = await postJson("/subagents", body);
|
||||
save.disabled = false;
|
||||
// The next state frame redraws the button.
|
||||
if (res.status === 200) return $("subagents-modal").close();
|
||||
if (res.status === 400) status.textContent = SUBAGENTS_ERRORS[res.body && res.body.error] || SUBAGENTS_ERRORS.bad;
|
||||
else if (res.status === 403 || res.status === 0) status.textContent = SUBAGENTS_LOST;
|
||||
else status.textContent = SUBAGENTS_ERRORS.bad;
|
||||
}
|
||||
|
||||
// Whether the agent coming or going has changed what the Ask pane painted,
|
||||
// with no frame to say so (the page's clock asks, once a second).
|
||||
export const askOfflineFlipped = () => (askState().send.state === "offline") !== askPaintedOffline;
|
||||
|
||||
// The Subagents dialog's buttons, and dropping files onto the notes panel.
|
||||
export function wireAsk() {
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) radio.addEventListener("change", syncSubagentsFields);
|
||||
lightDismiss($("subagents-modal"));
|
||||
$("btn-subagents").addEventListener("click", openSubagents);
|
||||
$("subagents-default").addEventListener("click", () => {
|
||||
$("subagents-instruction").value = defaultInstruction(page.S.workflow);
|
||||
});
|
||||
$("subagents-save").addEventListener("click", saveSubagents);
|
||||
$("subagents-cancel").addEventListener("click", () => $("subagents-modal").close());
|
||||
$("subagents-modal").addEventListener("close", () => $("btn-subagents").focus());
|
||||
|
||||
// Dropping files onto the notes panel attaches them to the selected
|
||||
// question's note. Bound once here: the panel's contents are redrawn on every
|
||||
// render, the panel itself is not.
|
||||
{
|
||||
const aside = $("aside");
|
||||
const canDrop = (e) => {
|
||||
const item = page.view === "end" ? null : byId(page.selected);
|
||||
return (
|
||||
Array.from((e.dataTransfer && e.dataTransfer.types) || []).includes("Files") &&
|
||||
item &&
|
||||
isOpen(item) &&
|
||||
!finish()
|
||||
);
|
||||
};
|
||||
const onOver = (e) => {
|
||||
if (!canDrop(e)) return;
|
||||
e.preventDefault();
|
||||
aside.classList.add("is-dropping");
|
||||
};
|
||||
aside.addEventListener("dragenter", onOver);
|
||||
aside.addEventListener("dragover", onOver);
|
||||
aside.addEventListener("dragleave", (e) => {
|
||||
// Moving between children fires dragleave too; only leaving the panel counts.
|
||||
if (!aside.contains(e.relatedTarget)) aside.classList.remove("is-dropping");
|
||||
});
|
||||
aside.addEventListener("drop", (e) => {
|
||||
aside.classList.remove("is-dropping");
|
||||
if (!canDrop(e)) return;
|
||||
e.preventDefault();
|
||||
attachFiles(page.selected, e.dataTransfer.files);
|
||||
});
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,126 @@
|
||||
// Plan2Code Web Console - User Preferences, Cleanup tab.
|
||||
|
||||
import { formatBytes } from "../answers.js";
|
||||
import { el } from "../render.js";
|
||||
import { postJson } from "../net.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// Cleanup: the server works out what in ~/.plan2code is not needed and
|
||||
// shows it first; Delete these sends back only the ids it was shown, and the
|
||||
// server re-checks every one before removing it.
|
||||
let cleanupFound = null;
|
||||
|
||||
// Bumped by every scan, delete and reset: a response from an older one is
|
||||
// dropped, so a scan still in flight when Preferences closes cannot refill it.
|
||||
let cleanupGen = 0;
|
||||
|
||||
const CLEANUP_SHOWN = 8;
|
||||
|
||||
function setCleanupStatus(text, isError) {
|
||||
const status = $("cleanup-status");
|
||||
status.textContent = text;
|
||||
status.classList.toggle("error", Boolean(isError));
|
||||
}
|
||||
|
||||
const CLEANUP_WHERE = { root: "~/.plan2code/", console: "~/.plan2code/console/", completed: "specs--completed/" };
|
||||
|
||||
function cleanupLabel(item) {
|
||||
if (item.where === "session") return "Session " + item.name;
|
||||
return CLEANUP_WHERE[item.where] + item.name + (item.kind === "folder" ? "/" : "");
|
||||
}
|
||||
|
||||
function cleanupSummary(items, bytes) {
|
||||
const sessions = items.filter((i) => i.where === "session").length;
|
||||
const completed = items.filter((i) => i.where === "completed").length;
|
||||
const strays = items.length - sessions - completed;
|
||||
const parts = [];
|
||||
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
|
||||
if (completed) parts.push(completed + (completed === 1 ? " old completed spec" : " old completed specs"));
|
||||
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
|
||||
return parts.join(", ") + " · " + formatBytes(bytes);
|
||||
}
|
||||
|
||||
function resetCleanup() {
|
||||
cleanupGen++;
|
||||
cleanupFound = null;
|
||||
$("cleanup-list").replaceChildren();
|
||||
$("cleanup-delete").hidden = true;
|
||||
$("cleanup-delete").disabled = false;
|
||||
$("cleanup-scan").disabled = false;
|
||||
setCleanupStatus("", false);
|
||||
}
|
||||
|
||||
function renderCleanup() {
|
||||
const list = $("cleanup-list");
|
||||
list.replaceChildren();
|
||||
const items = (cleanupFound && cleanupFound.items) || [];
|
||||
$("cleanup-delete").hidden = !items.length;
|
||||
if (!items.length) return;
|
||||
const rows = (some) => some.map((item) => {
|
||||
const row = el("div", "cleanup-row");
|
||||
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
|
||||
return row;
|
||||
});
|
||||
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
|
||||
if (items.length > CLEANUP_SHOWN) {
|
||||
const more = el("details", "cleanup-more");
|
||||
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
|
||||
list.appendChild(more);
|
||||
}
|
||||
}
|
||||
|
||||
async function scanCleanup() {
|
||||
const gen = ++cleanupGen;
|
||||
$("cleanup-scan").disabled = true;
|
||||
$("cleanup-delete").disabled = true;
|
||||
setCleanupStatus("Looking…", false);
|
||||
const { status, body } = await postJson("/cleanup", { scan: true });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-scan").disabled = false;
|
||||
$("cleanup-delete").disabled = false;
|
||||
if (status !== 200 || !body.ok) {
|
||||
cleanupFound = null;
|
||||
renderCleanup();
|
||||
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
|
||||
}
|
||||
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
|
||||
renderCleanup();
|
||||
// Left in the status line, not cleared: it is the live region, so this is
|
||||
// what a screen reader hears when the scan finishes.
|
||||
const found = cleanupFound.items.length;
|
||||
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
|
||||
}
|
||||
|
||||
async function deleteCleanup() {
|
||||
if (!cleanupFound || !cleanupFound.items.length) return;
|
||||
const gen = ++cleanupGen;
|
||||
$("cleanup-delete").disabled = true;
|
||||
$("cleanup-scan").disabled = true;
|
||||
setCleanupStatus("Deleting…", false);
|
||||
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-delete").disabled = false;
|
||||
$("cleanup-scan").disabled = false;
|
||||
if (status !== 200 || !body.ok) {
|
||||
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
|
||||
}
|
||||
const removed = (body.removed || []).length;
|
||||
const failed = (body.failed || []).length;
|
||||
// The server re-checks every id and keeps anything that changed since the
|
||||
// scan; say so, rather than let a count that came up short pass unremarked.
|
||||
const asked = cleanupFound.items.length;
|
||||
const kept = Math.max(0, asked - removed - failed);
|
||||
cleanupFound = null;
|
||||
renderCleanup();
|
||||
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
|
||||
const keptLine = kept ? ` ${kept} ${kept === 1 ? "was" : "were"} kept because ${kept === 1 ? "it" : "they"} changed since the scan.` : "";
|
||||
setCleanupStatus((failed ? done + " " + failed + " could not be removed." : done) + keptLine, Boolean(failed));
|
||||
}
|
||||
|
||||
// The Cleanup tab's buttons, and starting over whenever Preferences closes.
|
||||
export function wireCleanup() {
|
||||
$("cleanup-scan").addEventListener("click", scanCleanup);
|
||||
$("cleanup-delete").addEventListener("click", deleteCleanup);
|
||||
$("looks-modal").addEventListener("close", resetCleanup);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,987 @@
|
||||
// Plan2Code Web Console - the dashboard: cards, the spec picker, handoff chips, delete, and the first-open wake-up; defines only.
|
||||
|
||||
import {
|
||||
selHandoff,
|
||||
scan,
|
||||
selSpec,
|
||||
agentWorking,
|
||||
specList,
|
||||
handoffList,
|
||||
loadOverview,
|
||||
finish,
|
||||
} from "../selectors.js";
|
||||
import { hooks, page, redraw, saveNow } from "../state.js";
|
||||
import { el, approvalTip, mdInto, releasesLink, copyButton } from "../render.js";
|
||||
import { needsRoleNudge, ROLE_NOT_SET } from "../starters.js";
|
||||
import { looks, renderSwatches, saveLooks } from "../looks.js";
|
||||
import { RED_BANNER } from "../meter.js";
|
||||
import {
|
||||
dashNoteKind,
|
||||
defaultSpec,
|
||||
onInitialPick,
|
||||
cardPresentation,
|
||||
CATALOG_GROUPS,
|
||||
SKILL_CATALOG,
|
||||
SPEC_STATE_LABELS,
|
||||
chipDetail,
|
||||
isDeletableSpecDir,
|
||||
handoffAge,
|
||||
handoffCopyText,
|
||||
pickupAction,
|
||||
pickupReply,
|
||||
launchTarget,
|
||||
cardAvailability,
|
||||
launchReply,
|
||||
deleteSummary,
|
||||
deleteHandoffAction,
|
||||
deleteHandoffReply,
|
||||
deleteAction,
|
||||
deleteReply,
|
||||
} from "../answers.js";
|
||||
import { stateFor } from "../spec-states.js";
|
||||
import { sound, soundOn, fadeSound, dropSounds } from "../sound.js";
|
||||
import { playWake } from "../boot.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// The dashboard's first-open wake-up itself is page.wake (state.js). Once per
|
||||
// page, whatever storage allows: a re-render mid-run must never start a
|
||||
// second one.
|
||||
let wakeTried = false;
|
||||
|
||||
// True when a wake-up is waiting on the first click: the page load's opening
|
||||
// chime then gives way to the boot-up sound, played as he powers on.
|
||||
export let wakeHoldsChime = false;
|
||||
|
||||
// His snore while he sleeps (an Audio on loop), or null. Usually silent until
|
||||
// the waking click, since browsers refuse sound before one.
|
||||
let snore = null;
|
||||
|
||||
function roleNudge() {
|
||||
const nudge = el("div", "dash-nudge");
|
||||
nudge.setAttribute("role", "status");
|
||||
nudge.appendChild(el("span", "dash-nudge-text", "Pick your role to get starter templates ordered for you."));
|
||||
const actions = el("div", "dash-nudge-actions");
|
||||
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(
|
||||
"close",
|
||||
() => {
|
||||
if (looks.role === undefined) {
|
||||
looks.role = ROLE_NOT_SET;
|
||||
saveLooks();
|
||||
redraw();
|
||||
}
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
$("looks-modal").showModal();
|
||||
});
|
||||
const notNow = el("button", "btn tiny ghost", "Not now");
|
||||
notNow.type = "button";
|
||||
notNow.addEventListener("click", () => {
|
||||
looks.role = ROLE_NOT_SET;
|
||||
saveLooks();
|
||||
redraw();
|
||||
});
|
||||
actions.append(setUp, notNow);
|
||||
nudge.appendChild(actions);
|
||||
return nudge;
|
||||
}
|
||||
|
||||
// × on the update banner hides it for this console session only, and only
|
||||
// for the release it named. Blocked storage means "not dismissed".
|
||||
function updateDismissKey() {
|
||||
try {
|
||||
return "p2c-update-dismissed:" + page.S.sid;
|
||||
} catch {
|
||||
return "p2c-update-dismissed:";
|
||||
}
|
||||
}
|
||||
|
||||
function updateDismissed() {
|
||||
try {
|
||||
return sessionStorage.getItem(updateDismissKey()) === page.updateFrame.latest;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const UPDATE_COMMAND = "plan2code update";
|
||||
|
||||
// For a machine without the plan2code command: the full installer, menu and all.
|
||||
const UPDATE_FALLBACK_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
|
||||
|
||||
function openUpdateModal() {
|
||||
if (!page.updateFrame) return;
|
||||
const versions = $("update-versions");
|
||||
versions.replaceChildren(
|
||||
document.createTextNode("Version "),
|
||||
releasesLink("v" + page.updateFrame.latest),
|
||||
document.createTextNode(" is out — you have "),
|
||||
el("code", null, page.updateFrame.installed),
|
||||
document.createTextNode(".")
|
||||
);
|
||||
const row = $("update-command");
|
||||
const code = el("code", null, UPDATE_COMMAND);
|
||||
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
|
||||
const fallbackRow = $("update-fallback");
|
||||
const fallback = el("code", null, UPDATE_FALLBACK_COMMAND);
|
||||
fallbackRow.replaceChildren(fallback, copyButton(UPDATE_FALLBACK_COMMAND, "btn small ghost handoff-copy", fallback));
|
||||
$("update-modal").showModal();
|
||||
}
|
||||
|
||||
export function renderDashboard(main) {
|
||||
maybeWake();
|
||||
// First, so nothing below reads a pick whose handoff has left the scan, and
|
||||
// a delete the agent's rescan has finished stops holding the buttons.
|
||||
selHandoff();
|
||||
settleDeleting();
|
||||
const menu = (page.S && page.S.menu) || {};
|
||||
const wrap = el("div", "dash");
|
||||
if (needsRoleNudge(looks)) wrap.appendChild(roleNudge());
|
||||
// Advice only: words, never a button, and nothing is blocked.
|
||||
if (page.meterFrame && page.meterFrame.level === "red") {
|
||||
const warn = el("div", "dash-nudge meter-banner", RED_BANNER);
|
||||
warn.setAttribute("role", "status");
|
||||
wrap.appendChild(warn);
|
||||
}
|
||||
// Built here only, so no other workflow's page ever shows it.
|
||||
if (page.updateFrame && !updateDismissed()) {
|
||||
const notice = el("div", "dash-nudge update-banner");
|
||||
notice.setAttribute("role", "status");
|
||||
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + page.updateFrame.latest);
|
||||
open.type = "button";
|
||||
open.addEventListener("click", openUpdateModal);
|
||||
const dismiss = el("button", "update-banner-dismiss", "×");
|
||||
dismiss.type = "button";
|
||||
dismiss.setAttribute("aria-label", "Dismiss until next time");
|
||||
dismiss.addEventListener("click", () => {
|
||||
try {
|
||||
sessionStorage.setItem(updateDismissKey(), page.updateFrame.latest);
|
||||
} catch {}
|
||||
redraw();
|
||||
});
|
||||
notice.append(open, dismiss);
|
||||
wrap.appendChild(notice);
|
||||
}
|
||||
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
|
||||
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
|
||||
// The agent's note reads the spec the picker opened on (the same "initial"
|
||||
// test cardPresentation uses): another pick, or Start from scratch, gets
|
||||
// the neutral line rather than context about a spec no longer shown.
|
||||
const first = defaultSpec(scan() && scan().specs);
|
||||
const picked = selSpec();
|
||||
const noteKind = dashNoteKind({ menu, hasMenu: Boolean(page.S.menu), onInitial: onInitialPick(first, picked), working: agentWorking() });
|
||||
if (noteKind === "agent") {
|
||||
wrap.appendChild(el("p", "dash-note", menu.note));
|
||||
} else if (noteKind === "looking") {
|
||||
// The cards work from the first paint; the agent's read of the
|
||||
// project arrives a moment later, and this says so meanwhile.
|
||||
const note = el("p", "dash-note");
|
||||
note.appendChild(document.createTextNode("Pick what to do next. "));
|
||||
const working = el("span", "dash-working");
|
||||
working.appendChild(el("span", "spinner tiny"));
|
||||
working.appendChild(
|
||||
el(
|
||||
"span",
|
||||
null,
|
||||
"Plan2Code is still looking over the project and will flag where it would start when it is done."
|
||||
)
|
||||
);
|
||||
note.appendChild(working);
|
||||
wrap.appendChild(note);
|
||||
} else {
|
||||
wrap.appendChild(
|
||||
el("p", "dash-note", "Pick what to do next. It starts right here, and this page becomes its home.")
|
||||
);
|
||||
}
|
||||
|
||||
const specs = specList();
|
||||
if (specs.length || handoffList().length) wrap.appendChild(renderSpecPicker(specs));
|
||||
const handoff = selHandoff();
|
||||
if (handoff) {
|
||||
// A handoff is picked up, not launched: its skill and spec come from its
|
||||
// own record, so the skill cards and their toggle have nothing to say.
|
||||
if (!page.local.launching && !page.launchScoping && page.scopeMine !== "") hooks.syncWorkspaceScope();
|
||||
wrap.appendChild(renderHandoffPreview(handoff));
|
||||
main.appendChild(wrap);
|
||||
queueMicrotask(hooks.maybeWelcome);
|
||||
return;
|
||||
}
|
||||
wrap.appendChild(hideUnavailableToggle());
|
||||
// Only when this tab's own pick moved: another tab changing the scope
|
||||
// sends a frame here too, and re-asserting this tab's pick on every render
|
||||
// had two dashboards trade the workspace back and forth without end.
|
||||
const wantScope = (selSpec() && selSpec().dir) || "";
|
||||
if (!page.local.launching && !page.launchScoping && wantScope !== page.scopeMine) hooks.syncWorkspaceScope();
|
||||
|
||||
// "Unavailable" is the scan's verdict for the selected spec, not the
|
||||
// momentary greying while a launch is in flight or the server is away, so
|
||||
// cards never blink out of the menu mid-handoff.
|
||||
const hide = looks.hideUnavailable;
|
||||
const sel = selSpec();
|
||||
const available = (e) => cardPresentation(e, scan(), sel, menu).on;
|
||||
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;
|
||||
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));
|
||||
section.appendChild(grid);
|
||||
wrap.appendChild(section);
|
||||
}
|
||||
if (!shown) {
|
||||
wrap.appendChild(
|
||||
el("p", "dash-empty", "Nothing fits this pick right now. Turn off the toggle above to see every workflow.")
|
||||
);
|
||||
}
|
||||
wrap.appendChild(approvalTip());
|
||||
// Mid wake-up: the groups wait hidden until the glide lets them rise in,
|
||||
// and the note shows only as far as it has been typed. Once the entrance
|
||||
// has played, a re-render draws the menu plainly, never replaying it.
|
||||
if (page.wake && !page.wake.entered) wrap.classList.add("waking", ...(page.wake.cards ? ["is-in"] : []));
|
||||
if (page.wake && page.wake.typed != null) {
|
||||
const note = wrap.querySelector(".dash-note");
|
||||
if (note) revealNote(note, page.wake.typed);
|
||||
}
|
||||
main.appendChild(wrap);
|
||||
// Deferred: this runs inside render(), and the dialog is not part of it.
|
||||
queueMicrotask(hooks.maybeWelcome);
|
||||
}
|
||||
|
||||
const WAKE_TYPE_DELAY_MS = 350;
|
||||
|
||||
const WAKE_TYPE_EVERY_MS = 14;
|
||||
|
||||
const WAKE_ENTRANCE_MS = 900;
|
||||
|
||||
// One snore, for a nudge with no sound to time it (sounds off, or refused).
|
||||
const SNORE_MS = 2600;
|
||||
|
||||
// The longest a nudge waits on the snore ending: a hidden tab may never say.
|
||||
const SNORE_MAX_MS = 6000;
|
||||
|
||||
const BOOTUP_FADE_MS = 500;
|
||||
|
||||
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
// Only a newly opened dashboard carries `wake` (console.mjs deletes it on
|
||||
// every resume), and only the first page load in this tab plays it.
|
||||
function maybeWake() {
|
||||
if (wakeTried || page.S.wake !== true || finish()) return;
|
||||
wakeTried = true;
|
||||
const key = "p2c-console:woke:" + page.S.sid;
|
||||
try {
|
||||
if (sessionStorage.getItem(key)) return;
|
||||
sessionStorage.setItem(key, "1");
|
||||
} catch {
|
||||
// Blocked storage only costs the reload guard.
|
||||
}
|
||||
const stage = $("wake");
|
||||
const pilot = $("planny").closest(".pilot");
|
||||
page.wake = { cards: false, entered: false, typed: 0, timers: [], abort: new AbortController() };
|
||||
wakeHoldsChime = !matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
if (wakeHoldsChime && soundOn("snore")) {
|
||||
snore = new Audio("/sleeping.mp3");
|
||||
snore.loop = true;
|
||||
snore.play().catch(() => {});
|
||||
}
|
||||
pilot.classList.add("is-waking");
|
||||
playWake({
|
||||
stage,
|
||||
bot: stage.querySelector(".wake-bot"),
|
||||
skipEl: stage.querySelector(".wake-skip"),
|
||||
target: $("planny"),
|
||||
stir: stirWake,
|
||||
onStart: () => sound("bootup"),
|
||||
onGlide: wakeGlide,
|
||||
onSkip: skipWakeSounds,
|
||||
signal: page.wake.abort.signal,
|
||||
}).then(({ skipped }) => {
|
||||
stopSnore();
|
||||
fadeSound("bootup", BOOTUP_FADE_MS);
|
||||
pilot.classList.remove("is-waking");
|
||||
// An abort or reduced motion jumps straight to the finished
|
||||
// dashboard. A run that reached its end leaves the note typing on.
|
||||
if (skipped || (page.wake && !page.wake.cards)) finishWake();
|
||||
});
|
||||
}
|
||||
|
||||
// The nudge: one whole snore from the top, however far the loop had got (or
|
||||
// the first one heard, since the loop is usually refused until this click).
|
||||
// Called inside the click, so the browser lets it play. Settles when it ends,
|
||||
// and never rejects: a refused or silent snore just takes one snore's time.
|
||||
function stirWake() {
|
||||
if (!snore) return delay(SNORE_MS);
|
||||
const heard = new Promise((resolve) => snore.addEventListener("ended", resolve, { once: true }));
|
||||
snore.loop = false;
|
||||
snore.currentTime = 0;
|
||||
return snore.play().then(
|
||||
() => Promise.race([heard, delay(SNORE_MAX_MS)]),
|
||||
() => delay(SNORE_MS)
|
||||
);
|
||||
}
|
||||
|
||||
function stopSnore() {
|
||||
if (!snore) return;
|
||||
snore.pause();
|
||||
snore = null;
|
||||
}
|
||||
|
||||
// The Skip button: silence anything the intro already queued or started. The
|
||||
// promise's .then does the snore and the bootup fade; this only clears cues
|
||||
// still waiting to play.
|
||||
function skipWakeSounds() {
|
||||
dropSounds();
|
||||
}
|
||||
|
||||
// The glide: the menu rises in and the note starts typing. On a skip the run
|
||||
// is already ending and its promise settles everything, so nothing here.
|
||||
function wakeGlide({ instant }) {
|
||||
if (!page.wake) return;
|
||||
page.wake.cards = true;
|
||||
if (instant) return;
|
||||
page.wake.timers.push(
|
||||
setTimeout(() => {
|
||||
page.wake.entered = true;
|
||||
settleWake();
|
||||
}, WAKE_ENTRANCE_MS),
|
||||
setTimeout(typeNote, WAKE_TYPE_DELAY_MS)
|
||||
);
|
||||
redraw();
|
||||
}
|
||||
|
||||
// One more character of the note on the live element. Whatever the note says
|
||||
// right now is what gets typed, so a `menu` note that lands mid-way simply
|
||||
// carries on from the same count.
|
||||
function typeNote() {
|
||||
if (!page.wake || page.wake.typed == null) return;
|
||||
page.wake.typed += 1;
|
||||
const note = $("main").querySelector(":scope > .dash .dash-note");
|
||||
if (!note || page.wake.typed >= revealNote(note, page.wake.typed)) {
|
||||
page.wake.typed = null;
|
||||
if (note) revealNote(note, Infinity);
|
||||
return settleWake();
|
||||
}
|
||||
page.wake.timers.push(setTimeout(typeNote, WAKE_TYPE_EVERY_MS));
|
||||
}
|
||||
|
||||
// Done once the entrance has played and the note is all there. Nothing to
|
||||
// redraw: what is on screen already is the finished dashboard.
|
||||
function settleWake() {
|
||||
if (page.wake && page.wake.entered && page.wake.typed == null) {
|
||||
page.wake = null;
|
||||
hooks.maybeWelcome();
|
||||
}
|
||||
}
|
||||
|
||||
function finishWake() {
|
||||
if (!page.wake) return;
|
||||
for (const t of page.wake.timers) clearTimeout(t);
|
||||
page.wake = null;
|
||||
redraw();
|
||||
}
|
||||
|
||||
// Shows the first `count` characters of a note's text, across its text nodes,
|
||||
// and returns how many there are in all. The full text is kept per node the
|
||||
// first time it is cut, so later calls can grow it back. An element the
|
||||
// typing has not reached yet (the "still looking" pill and its spinner) is
|
||||
// kept out of sight, rather than showing as an empty box.
|
||||
const noteFullText = new WeakMap();
|
||||
|
||||
function revealNote(note, count) {
|
||||
const walker = document.createTreeWalker(note, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
|
||||
let total = 0;
|
||||
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
||||
if (n.nodeType === Node.ELEMENT_NODE) {
|
||||
n.classList.toggle("is-untyped", total >= count);
|
||||
continue;
|
||||
}
|
||||
if (!noteFullText.has(n)) noteFullText.set(n, n.data);
|
||||
const full = noteFullText.get(n);
|
||||
n.data = full.slice(0, Math.max(0, count - total));
|
||||
total += full.length;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
// A page-wide preference, so it rides in `looks` (looks.json) and follows the
|
||||
// person to every session and port rather than resetting per dashboard.
|
||||
function hideUnavailableToggle() {
|
||||
const label = el("label", "dash-toggle");
|
||||
const box = el("input");
|
||||
box.type = "checkbox";
|
||||
// The id is what lets withFocus hand focus back after the rebuild.
|
||||
box.id = "dash-hide-unavailable";
|
||||
box.setAttribute("role", "switch");
|
||||
box.checked = looks.hideUnavailable;
|
||||
box.addEventListener("change", () => {
|
||||
looks.hideUnavailable = box.checked;
|
||||
saveLooks();
|
||||
redraw();
|
||||
});
|
||||
label.appendChild(box);
|
||||
label.appendChild(el("span", "dash-toggle-track"));
|
||||
label.appendChild(el("span", "dash-toggle-text", "Hide unavailable workflows"));
|
||||
return label;
|
||||
}
|
||||
|
||||
/* The spec picker: every spec the server found under specs/, plus "start
|
||||
from scratch". The selection decides which cards below are lit, and rides
|
||||
along on the launch of any card that takes a spec. Picking is page-local —
|
||||
no send — so it costs nothing to change your mind. */
|
||||
function renderSpecPicker(specs) {
|
||||
const sel = selSpec();
|
||||
const handoffs = handoffList();
|
||||
const pickedHandoff = selHandoff();
|
||||
const box = el("section", "spec-pick");
|
||||
box.appendChild(
|
||||
el("h3", "dash-group-title", handoffs.length ? "Pick up a spec or a handoff, or start fresh" : "Pick up a spec, or start fresh")
|
||||
);
|
||||
const row = el("div", "spec-row");
|
||||
|
||||
const scratchOn = !sel && !pickedHandoff;
|
||||
const scratch = el("button", "spec-chip" + (scratchOn ? " is-sel" : ""));
|
||||
scratch.type = "button";
|
||||
scratch.setAttribute("aria-current", String(scratchOn));
|
||||
scratch.appendChild(el("span", "spec-chip-name", "Start from scratch"));
|
||||
scratch.appendChild(el("span", "spec-chip-state", "a new idea"));
|
||||
scratch.addEventListener("click", () => {
|
||||
page.local.specSel = null;
|
||||
saveNow();
|
||||
redraw();
|
||||
loadOverview();
|
||||
});
|
||||
row.appendChild(scratch);
|
||||
|
||||
for (const spec of specs) {
|
||||
const on = sel && sel.dir === spec.dir;
|
||||
// A finished spec (a fixed bug) is hidden while unavailable workflows
|
||||
// are, dimmed otherwise. A pick already on it stays visible, so it is
|
||||
// never lost.
|
||||
const fixed = Boolean(stateFor(spec.state)?.finished);
|
||||
if (fixed && looks.hideUnavailable && !on) continue;
|
||||
const deleting = Boolean(page.local.deleting && page.local.deleting.dir === spec.dir);
|
||||
const wrap = el("div", "spec-chip-wrap" + (deleting ? " is-deleting" : "") + (fixed ? " is-fixed" : ""));
|
||||
const b = el("button", "spec-chip" + (on ? " is-sel" : ""));
|
||||
b.type = "button";
|
||||
b.setAttribute("aria-current", String(Boolean(on)));
|
||||
b.appendChild(el("span", "spec-chip-name", spec.name));
|
||||
b.appendChild(el("span", "spec-chip-state", deleting ? "Deleting…" : SPEC_STATE_LABELS[spec.state] || spec.state));
|
||||
const detail = chipDetail(spec);
|
||||
if (detail) b.appendChild(el("span", "spec-chip-detail", detail));
|
||||
b.addEventListener("click", () => {
|
||||
page.local.specSel = spec.dir;
|
||||
saveNow();
|
||||
redraw();
|
||||
loadOverview();
|
||||
});
|
||||
wrap.appendChild(b);
|
||||
if (isDeletableSpecDir(spec.dir)) {
|
||||
// A fixed bug is done with, so its Delete is a visible button rather
|
||||
// than the hover ✕ every other spec has.
|
||||
const del = fixed ? el("button", "spec-chip-del-label", "Delete") : el("button", "spec-chip-del", "✕");
|
||||
del.type = "button";
|
||||
del.title = `Delete ${spec.dir}/`;
|
||||
del.setAttribute("aria-label", `Delete the spec ${spec.name}`);
|
||||
del.disabled = deleting || Boolean(page.local.deleting) || page.gone || page.pendingResult || Boolean(page.local.launching);
|
||||
del.addEventListener("click", () => openDeleteConfirm(spec));
|
||||
wrap.appendChild(del);
|
||||
}
|
||||
row.appendChild(wrap);
|
||||
}
|
||||
// Handoffs follow the specs: dashed chips, the state word is "Handoff".
|
||||
for (const h of handoffs) {
|
||||
const on = Boolean(pickedHandoff && pickedHandoff.id === h.id);
|
||||
const deleting = Boolean(page.local.deleting && page.local.deleting.dir === "handoff:" + h.id);
|
||||
const b = el("button", "spec-chip is-handoff" + (on ? " is-sel" : "") + (deleting ? " is-deleting" : ""));
|
||||
b.type = "button";
|
||||
b.setAttribute("aria-current", String(on));
|
||||
b.appendChild(el("span", "spec-chip-name", h.title || "Handoff"));
|
||||
b.appendChild(el("span", "spec-chip-state", deleting ? "Deleting…" : "Handoff"));
|
||||
b.appendChild(el("span", "spec-chip-detail", handoffAge(h.written)));
|
||||
b.addEventListener("click", () => {
|
||||
page.local.specSel = "handoff:" + h.id;
|
||||
saveNow();
|
||||
redraw();
|
||||
});
|
||||
row.appendChild(b);
|
||||
}
|
||||
box.appendChild(row);
|
||||
return box;
|
||||
}
|
||||
|
||||
// A delete in flight ends when the agent's rescan lands (a new scan), gone
|
||||
// or refused: either way the picker is the truth again.
|
||||
function settleDeleting() {
|
||||
const sc = scan();
|
||||
if (page.local.deleting && sc && sc.at !== page.local.deleting.scanAt) {
|
||||
page.local.deleting = null;
|
||||
saveNow();
|
||||
}
|
||||
}
|
||||
|
||||
// What a picked handoff shows: where it came from and its Next task, with the
|
||||
// four things to do with it.
|
||||
function renderHandoffPreview(h) {
|
||||
const box = el("section", "handoff-preview");
|
||||
box.appendChild(el("h3", "handoff-preview-title", h.title || "Handoff"));
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === h.skill);
|
||||
const meta = [
|
||||
"Written " + (h.written ? new Date(h.written).toLocaleString() : "at an unknown time"),
|
||||
h.spec ? "spec " + h.spec.replace(/^specs\//, "") : "no spec",
|
||||
"from " + (entry ? entry.title : h.skill),
|
||||
];
|
||||
box.appendChild(el("p", "handoff-preview-meta", meta.join(" · ")));
|
||||
if (h.next) {
|
||||
box.appendChild(el("p", "handoff-preview-label", "Next task"));
|
||||
box.appendChild(el("p", "handoff-preview-next", h.next));
|
||||
}
|
||||
const busy = Boolean(page.local.launching || page.local.deleting) || page.gone || page.pendingResult;
|
||||
const actions = el("div", "handoff-preview-actions");
|
||||
const go = el("button", "btn primary", "Pick it up here");
|
||||
go.type = "button";
|
||||
go.disabled = busy;
|
||||
go.addEventListener("click", () => pickUpHandoff(h));
|
||||
const read = el("button", "btn", "Read it all");
|
||||
read.type = "button";
|
||||
read.addEventListener("click", () => readHandoff(h));
|
||||
const copy = el("button", "btn", "Copy for a new conversation");
|
||||
copy.type = "button";
|
||||
copy.addEventListener("click", () => {
|
||||
const dir = (scan() && scan().handoffsDir) || "";
|
||||
const sep = dir.includes("\\") ? "\\" : "/";
|
||||
const file = dir ? dir.replace(/[\\/]+$/, "") + sep + h.id + ".md" : h.id + ".md";
|
||||
copyHandoffText(handoffCopyText(file), copy);
|
||||
});
|
||||
const del = el("button", "btn danger", "Delete");
|
||||
del.type = "button";
|
||||
del.disabled = busy;
|
||||
del.addEventListener("click", () => openHandoffDelete(h));
|
||||
actions.append(go, read, copy, del);
|
||||
box.appendChild(actions);
|
||||
return box;
|
||||
}
|
||||
|
||||
// The prompt that sends a new conversation to the handoff. A refused
|
||||
// clipboard gets a plain word on the button instead of a silent nothing.
|
||||
async function copyHandoffText(text, button) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
button.textContent = "Copied";
|
||||
} catch {
|
||||
button.textContent = "Copy was refused";
|
||||
}
|
||||
setTimeout(() => (button.textContent = "Copy for a new conversation"), 1500);
|
||||
}
|
||||
|
||||
// Pick it up here: a hop like a card launch. The page sends only the id; the
|
||||
// CLI reads the stored skill and spec, marks the handoff used and falls back
|
||||
// to Quick Task if either is gone.
|
||||
async function pickUpHandoff(h) {
|
||||
if (page.gone || page.pendingResult || page.local.launching || finish()) return;
|
||||
page.launchScoping = true;
|
||||
await hooks.syncWorkspaceScope(h.spec || "");
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [pickupAction(h)], reply: pickupReply(h) }),
|
||||
});
|
||||
if (res.status === 409) {
|
||||
page.launchScoping = false;
|
||||
page.pendingResult = true;
|
||||
hooks.banner("Your last pick is still being picked up. One moment.", "info");
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
sound("startSkill");
|
||||
page.local.launching = { skill: h.skill, title: h.title || "the handoff", at: Date.now() };
|
||||
page.launchScoping = false;
|
||||
page.pendingResult = true;
|
||||
saveNow();
|
||||
redraw();
|
||||
} catch {
|
||||
page.launchScoping = false;
|
||||
hooks.banner("That did not go through. Nothing was lost; try again.", "warn");
|
||||
}
|
||||
}
|
||||
|
||||
// Read it all: the document, in a dialog, from /handoff?id= (served only for
|
||||
// an id the dashboard's own scan listed).
|
||||
async function readHandoff(h) {
|
||||
$("handoff-title").textContent = h.title || "Handoff";
|
||||
const body = $("handoff-body");
|
||||
body.replaceChildren(el("p", "md-p", "Reading…"));
|
||||
$("handoff-modal").showModal();
|
||||
try {
|
||||
const res = await fetch("/handoff?id=" + encodeURIComponent(h.id), { cache: "no-store" });
|
||||
if (res.status !== 200) throw new Error(String(res.status));
|
||||
mdInto(body, await res.text());
|
||||
} catch {
|
||||
body.replaceChildren(el("p", "md-p", "This handoff could not be read."));
|
||||
}
|
||||
}
|
||||
|
||||
function dashCard(entry, menu) {
|
||||
const presentation = 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 greyed
|
||||
// recommendation also yields to the selected spec's actual next step.
|
||||
const going = page.local.launching && page.local.launching.skill === entry.skill;
|
||||
const b = el(
|
||||
"button",
|
||||
"dash-card" + (presentation.recommended ? " is-suggested" : "") + (going ? " is-going" : "")
|
||||
);
|
||||
b.type = "button";
|
||||
b.disabled = Boolean(page.local.launching) || page.gone || page.pendingResult || !presentation.on;
|
||||
if (!presentation.on && presentation.reason) b.title = presentation.reason;
|
||||
|
||||
const head = el("span", "dash-card-head");
|
||||
head.appendChild(el("span", "dash-chip", entry.chip));
|
||||
if (presentation.recommended) head.appendChild(el("span", "pill suggested", "Suggested"));
|
||||
b.appendChild(head);
|
||||
b.appendChild(el("span", "dash-card-title", entry.title));
|
||||
b.appendChild(el("span", "dash-card-blurb", entry.blurb));
|
||||
if (presentation.detail) b.appendChild(el("span", "dash-card-detail", presentation.detail));
|
||||
if (!presentation.on && presentation.reason) b.appendChild(el("span", "dash-card-off", presentation.reason));
|
||||
|
||||
const foot = el("span", "dash-card-foot");
|
||||
foot.appendChild(el("code", "dash-card-cmd", entry.command));
|
||||
foot.appendChild(el("span", "dash-card-go", going ? "…" : "→"));
|
||||
b.appendChild(foot);
|
||||
|
||||
b.addEventListener("click", () => {
|
||||
page.dashPick = entry;
|
||||
redraw();
|
||||
});
|
||||
return b;
|
||||
}
|
||||
|
||||
// The confirm pane. A card or rail click lands here rather than launching
|
||||
// straight away: picking a skill is the one irreversible-feeling click on the
|
||||
// dashboard, and it deserves a beat: what it is, what it will do, and a
|
||||
// START that means it. Planny turns up leaning (his "this way" pose) in a
|
||||
// small sky, because a bare paragraph with two buttons is a dialog, not a
|
||||
// moment. BACK returns to the menu; Escape does the same (see the global
|
||||
// keydown in core.js).
|
||||
export function renderConfirm(main, entry) {
|
||||
const menu = (page.S && page.S.menu) || {};
|
||||
const presentation = cardPresentation(entry, scan(), selSpec(), menu);
|
||||
const pane = el("div", "dash-confirm");
|
||||
|
||||
const stage = el("div", "launch-stage confirm-stage");
|
||||
const sky = el("div", "sky launch-sky");
|
||||
const r = (a, b) => a + Math.random() * (b - a);
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const star = el("i", "star" + (i % 5 === 0 ? " hot" : ""));
|
||||
const dur = r(4, 10);
|
||||
star.style.setProperty("--y", r(2, 98).toFixed(1) + "%");
|
||||
star.style.setProperty("--p", r(0, 1).toFixed(3));
|
||||
star.style.setProperty("--s", r(1.2, 2.4).toFixed(2) + "px");
|
||||
star.style.setProperty("--dur", dur.toFixed(2) + "s");
|
||||
star.style.setProperty("--delay", (-r(0, dur)).toFixed(2) + "s");
|
||||
sky.appendChild(star);
|
||||
}
|
||||
stage.appendChild(sky);
|
||||
const bot = $("planny").cloneNode(true);
|
||||
bot.removeAttribute("id");
|
||||
bot.setAttribute("class", "planny is-point v0 confirm-planny");
|
||||
stage.appendChild(bot);
|
||||
pane.appendChild(stage);
|
||||
|
||||
const head = el("div", "confirm-head");
|
||||
head.appendChild(el("span", "dash-chip", entry.chip));
|
||||
if (presentation.recommended) head.appendChild(el("span", "pill suggested", "Suggested"));
|
||||
pane.appendChild(head);
|
||||
pane.appendChild(el("h2", "dash-title", entry.title));
|
||||
pane.appendChild(el("p", "confirm-about", entry.about || entry.blurb));
|
||||
|
||||
if (presentation.detail) pane.appendChild(el("p", "confirm-detail", presentation.detail));
|
||||
|
||||
// A card that takes a spec names the one the picker is holding, so START
|
||||
// reads as "build THIS spec", not the skill in the abstract.
|
||||
const target = launchTarget(entry, selSpec());
|
||||
if (target) {
|
||||
const specLine = el("p", "confirm-spec");
|
||||
specLine.appendChild(el("span", null, "for "));
|
||||
specLine.appendChild(el("code", null, target.dir));
|
||||
specLine.appendChild(el("span", null, ` · ${SPEC_STATE_LABELS[target.state] || target.state}`));
|
||||
pane.appendChild(specLine);
|
||||
}
|
||||
|
||||
const cmd = el("p", "confirm-cmd");
|
||||
cmd.appendChild(el("code", null, entry.command));
|
||||
pane.appendChild(cmd);
|
||||
|
||||
const actions = el("div", "confirm-actions");
|
||||
const start = el("button", "btn primary", "Start " + entry.title);
|
||||
start.type = "button";
|
||||
start.disabled = page.gone || page.pendingResult;
|
||||
start.addEventListener("click", () => launchSkill(entry));
|
||||
const back = el("button", "btn ghost", "Back");
|
||||
back.type = "button";
|
||||
back.addEventListener("click", () => {
|
||||
page.dashPick = null;
|
||||
redraw();
|
||||
});
|
||||
actions.appendChild(back);
|
||||
actions.appendChild(start);
|
||||
pane.appendChild(actions);
|
||||
|
||||
main.appendChild(pane);
|
||||
// Focus lands on START after a pick (the clicked control was rebuilt away,
|
||||
// leaving focus on <body>), but never yanked back from a deliberate click
|
||||
// elsewhere: a state frame can re-render this pane at any time.
|
||||
if (document.activeElement === document.body) start.focus();
|
||||
}
|
||||
|
||||
// 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) {
|
||||
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
|
||||
// one tab could have shifted the ground under a stale render in another.
|
||||
if (!cardAvailability(entry, scan(), selSpec()).on) {
|
||||
hooks.banner("That card is not available for the spec you picked.", "warn");
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
page.dashPick = null;
|
||||
const action = {
|
||||
i: "__launch",
|
||||
type: "launch",
|
||||
skill: entry.skill,
|
||||
workflow: entry.workflow,
|
||||
title: entry.title,
|
||||
};
|
||||
// The picker's spec goes to the skill being launched, not to the card:
|
||||
// cards that take no spec (utilities, setup) launch untargeted even while
|
||||
// a spec is selected, save Quick Task on a diagnosed bug.
|
||||
if (target) action.spec = target.dir;
|
||||
// The skill opens on the folders remembered for what it was launched for.
|
||||
// Held until the launch is in flight: the swap's own frame re-renders the
|
||||
// dashboard, which would otherwise sync back to the picker's spec.
|
||||
page.launchScoping = true;
|
||||
await hooks.syncWorkspaceScope(target ? target.dir : "");
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
actions: [action],
|
||||
reply: launchReply(entry, target),
|
||||
}),
|
||||
});
|
||||
if (res.status === 409) {
|
||||
page.launchScoping = false;
|
||||
page.pendingResult = true;
|
||||
hooks.banner("Your last pick is still being picked up. One moment.", "info");
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
sound("startSkill");
|
||||
page.local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
|
||||
page.launchScoping = false;
|
||||
page.pendingResult = true;
|
||||
saveNow();
|
||||
redraw();
|
||||
} catch {
|
||||
page.launchScoping = false;
|
||||
hooks.banner("That did not go through. Nothing was lost; try again.", "warn");
|
||||
}
|
||||
}
|
||||
|
||||
// The picker's Delete: a dialog in two steps. The first says what goes and
|
||||
// that it is for good; "Delete this spec…" then reveals the second, which
|
||||
// enables the final button only once the spec's name is typed exactly. A
|
||||
// fixed bug skips the second step: its first press sends the delete.
|
||||
// Cancel, Escape or a click on Keep it at either step changes nothing.
|
||||
let deleteTarget = null;
|
||||
|
||||
// The spec warning as index.html writes it, kept so a fixed bug's wording
|
||||
// never sticks for the next spec.
|
||||
let deleteWarnDefault = null;
|
||||
|
||||
// A handoff's Delete reuses the same dialog in one step: no name to type, and
|
||||
// the warning says where the file lives instead of what git does not track.
|
||||
function openHandoffDelete(h) {
|
||||
if (page.gone || page.pendingResult || page.local.launching || page.local.deleting) return;
|
||||
deleteTarget = { handoff: h };
|
||||
$("delete-title").textContent = "Delete this handoff?";
|
||||
$("delete-blurb").textContent = "This handoff will be deleted from ~/.plan2code/handoffs/.";
|
||||
$("delete-warn").hidden = true;
|
||||
$("delete-warn-handoff").hidden = false;
|
||||
const facts = $("delete-facts");
|
||||
facts.replaceChildren();
|
||||
const fact = (term, value) => {
|
||||
if (!value) return;
|
||||
facts.appendChild(el("dt", "", term));
|
||||
facts.appendChild(el("dd", "", value));
|
||||
};
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === h.skill);
|
||||
fact("Handoff", h.title || h.id);
|
||||
fact("Written", h.written ? new Date(h.written).toLocaleString() : "");
|
||||
fact("Spec", h.spec ? h.spec.replace(/^specs\//, "") : "");
|
||||
fact("From", entry ? entry.title : h.skill);
|
||||
$("delete-confirm").hidden = true;
|
||||
const go = $("delete-go");
|
||||
go.textContent = "Delete it";
|
||||
go.classList.add("is-on");
|
||||
go.disabled = false;
|
||||
$("delete-modal").showModal();
|
||||
}
|
||||
|
||||
function openDeleteConfirm(spec) {
|
||||
if (!isDeletableSpecDir(spec.dir) || page.gone || page.pendingResult || page.local.launching || page.local.deleting) return;
|
||||
deleteTarget = spec;
|
||||
// A finished spec (a fixed bug): one confirm, and a warning that says so.
|
||||
const fixed = Boolean(stateFor(spec.state)?.finished);
|
||||
$("delete-title").textContent = "Delete this spec?";
|
||||
const warn = $("delete-warn");
|
||||
if (!deleteWarnDefault) deleteWarnDefault = [...warn.childNodes].map((n) => n.cloneNode(true));
|
||||
warn.replaceChildren(
|
||||
...(fixed
|
||||
? ["The bug is fixed, so this only clears the write-up. ", el("code", "", "specs/"), " is not tracked by git, so it cannot be brought back."]
|
||||
: deleteWarnDefault.map((n) => n.cloneNode(true)))
|
||||
);
|
||||
warn.hidden = false;
|
||||
$("delete-warn-handoff").hidden = true;
|
||||
const sum = deleteSummary(spec);
|
||||
$("delete-blurb").textContent = `Everything in ${sum.folder} will be deleted from this project.`;
|
||||
const facts = $("delete-facts");
|
||||
facts.replaceChildren();
|
||||
const fact = (term, value) => {
|
||||
if (!value) return;
|
||||
facts.appendChild(el("dt", "", term));
|
||||
facts.appendChild(el("dd", "", value));
|
||||
};
|
||||
fact("Spec", spec.name);
|
||||
fact("Folder", sum.folder);
|
||||
fact("Stage", sum.stage);
|
||||
fact("Files", sum.files);
|
||||
fact("Last changed", sum.touched ? new Date(sum.touched).toLocaleString() : "");
|
||||
$("delete-name-hint").textContent = spec.name;
|
||||
$("delete-name").value = "";
|
||||
$("delete-confirm").hidden = true;
|
||||
const go = $("delete-go");
|
||||
go.textContent = fixed ? "Delete it" : "Delete this spec…";
|
||||
go.classList.toggle("is-on", fixed);
|
||||
go.disabled = false;
|
||||
$("delete-modal").showModal();
|
||||
}
|
||||
|
||||
function deleteStep() {
|
||||
const go = $("delete-go");
|
||||
if (!deleteTarget) return;
|
||||
if (deleteTarget.handoff) return sendDeleteHandoff(deleteTarget.handoff);
|
||||
if (stateFor(deleteTarget.state)?.finished) return sendDelete(deleteTarget);
|
||||
if ($("delete-confirm").hidden) {
|
||||
$("delete-confirm").hidden = false;
|
||||
go.textContent = "Delete for good";
|
||||
go.classList.add("is-on");
|
||||
go.disabled = true;
|
||||
$("delete-name").focus();
|
||||
return;
|
||||
}
|
||||
if ($("delete-name").value.trim() !== deleteTarget.name) return;
|
||||
sendDelete(deleteTarget);
|
||||
}
|
||||
|
||||
async function sendDeleteHandoff(h) {
|
||||
const go = $("delete-go");
|
||||
go.disabled = true;
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [deleteHandoffAction(h)], reply: deleteHandoffReply(h) }),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
const sc = scan();
|
||||
page.local.deleting = { dir: "handoff:" + h.id, scanAt: sc ? sc.at : null };
|
||||
if (page.local.specSel === "handoff:" + h.id) delete page.local.specSel;
|
||||
page.pendingResult = true;
|
||||
saveNow();
|
||||
$("delete-modal").close();
|
||||
} catch (err) {
|
||||
$("delete-modal").close();
|
||||
if (err && err.pending) page.pendingResult = true;
|
||||
hooks.banner(
|
||||
err && err.pending
|
||||
? "Your last pick is still being picked up, so that could not go yet. Nothing was deleted; try again in a moment."
|
||||
: "That did not go through. Nothing was deleted; try again.",
|
||||
"warn"
|
||||
);
|
||||
} finally {
|
||||
deleteTarget = null;
|
||||
redraw();
|
||||
}
|
||||
}
|
||||
|
||||
async function sendDelete(spec) {
|
||||
const go = $("delete-go");
|
||||
go.disabled = true;
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [deleteAction(spec)], reply: deleteReply(spec) }),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
const sc = scan();
|
||||
page.local.deleting = { dir: spec.dir, scanAt: sc ? sc.at : null };
|
||||
// The selection must not outlive the folder: back to the default pick,
|
||||
// which the agent's fresh menu recommends for.
|
||||
if (page.local.specSel === spec.dir) delete page.local.specSel;
|
||||
page.pendingResult = true;
|
||||
saveNow();
|
||||
$("delete-modal").close();
|
||||
} catch (err) {
|
||||
$("delete-modal").close();
|
||||
if (err && err.pending) page.pendingResult = true;
|
||||
hooks.banner(
|
||||
err && err.pending
|
||||
? "Your last pick is still being picked up, so that could not go yet. Nothing was deleted; try again in a moment."
|
||||
: "That did not go through. Nothing was deleted; try again.",
|
||||
"warn"
|
||||
);
|
||||
} finally {
|
||||
deleteTarget = null;
|
||||
redraw();
|
||||
}
|
||||
}
|
||||
|
||||
// The dialogs' buttons, wired once at start-up: the update notice's Done, the
|
||||
// handoff preview's close, and the delete dialog's Cancel, name box and go.
|
||||
export function wireDashboard() {
|
||||
$("update-done").addEventListener("click", () => $("update-modal").close());
|
||||
$("delete-cancel").addEventListener("click", () => $("delete-modal").close());
|
||||
$("handoff-close").addEventListener("click", () => $("handoff-modal").close());
|
||||
$("delete-go").addEventListener("click", deleteStep);
|
||||
$("delete-name").addEventListener("input", () => {
|
||||
$("delete-go").disabled = !deleteTarget || $("delete-name").value.trim() !== deleteTarget.name;
|
||||
});
|
||||
$("delete-name").addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
deleteStep();
|
||||
}
|
||||
});
|
||||
$("delete-modal").addEventListener("close", () => {
|
||||
deleteTarget = null;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
// Plan2Code Web Console - documents: tabs, blocks, print and download, and the brief button; defines only.
|
||||
|
||||
import { docs, agentWorking, workingMs, patience, WORKING_GRACE_MS, finish } from "../selectors.js";
|
||||
import { el, md } from "../render.js";
|
||||
import { downloadDocHtml, docSavedNote, downloadDoc, blockBody } from "../doc-files.js";
|
||||
import { hooks, page, redraw } from "../state.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
import { sendState } from "../send-state.js";
|
||||
import { briefPhrase } from "../answers.js";
|
||||
|
||||
let docObserver = null;
|
||||
|
||||
// A brief is a Pathfinder thing: a plain-English report of the decisions made
|
||||
// in a date range, the ones still open, and what happens next. It is the
|
||||
// artifact someone takes to a meeting, and the reason a non-engineer is in this
|
||||
// session at all, so it should not need knowing that you can type "brief" at a
|
||||
// terminal to get one.
|
||||
//
|
||||
// The request travels as an ordinary send. The agent's own wait loop returns
|
||||
// it, `reply` carries the range in the grammar its playbook already parses, and
|
||||
// the finished brief comes back as a doc like any other.
|
||||
const BRIEF_RANGES = {
|
||||
today: "today",
|
||||
"this week": "this week",
|
||||
full: "full",
|
||||
};
|
||||
|
||||
function briefRange() {
|
||||
const picked = document.querySelector('input[name="brief-range"]:checked');
|
||||
const value = picked ? picked.value : "today";
|
||||
if (value !== "since") return { range: BRIEF_RANGES[value] || "today" };
|
||||
const on = $("brief-since").value;
|
||||
if (!on) return { problem: "Pick the date to count from, or choose another range." };
|
||||
if (on > localDay()) return { problem: "Pick a date that has already happened: a brief covers what was decided since then." };
|
||||
return { range: `since ${on}` };
|
||||
}
|
||||
|
||||
function openBrief() {
|
||||
const why = $("brief-why");
|
||||
why.textContent = "";
|
||||
syncBriefDate();
|
||||
$("brief-modal").showModal();
|
||||
}
|
||||
|
||||
// The date only means anything for "since", so it is dimmed and inert until
|
||||
// that is the choice, rather than sitting there inviting a value it will ignore.
|
||||
function syncBriefDate() {
|
||||
const picked = document.querySelector('input[name="brief-range"]:checked');
|
||||
const on = Boolean(picked && picked.value === "since");
|
||||
const row = document.querySelector(".since-row");
|
||||
const input = $("brief-since");
|
||||
row.classList.toggle("is-off", !on);
|
||||
input.disabled = !on;
|
||||
input.max = localDay();
|
||||
}
|
||||
|
||||
// Today as YYYY-MM-DD in the person's own time zone, the shape a date input uses.
|
||||
function localDay(d = new Date()) {
|
||||
const p = (n) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
|
||||
}
|
||||
|
||||
export async function sendBrief() {
|
||||
const choice = briefRange();
|
||||
const why = $("brief-why");
|
||||
if (choice.problem) {
|
||||
why.textContent = choice.problem;
|
||||
return;
|
||||
}
|
||||
const state = sendState();
|
||||
// The same guard the Send button uses. A brief is a turn like any other, and
|
||||
// two turns in flight is the one thing this protocol will not do.
|
||||
if (page.gone || page.pendingResult || (agentWorking() && workingMs() <= patience(WORKING_GRACE_MS))) {
|
||||
why.textContent = state.why || "Wait for Plan2Code to finish, then ask again.";
|
||||
return;
|
||||
}
|
||||
|
||||
const go = $("brief-go");
|
||||
go.disabled = true;
|
||||
go.textContent = "Asking…";
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
actions: [{ i: "__brief", type: "brief", range: choice.range }],
|
||||
reply: briefPhrase(choice.range),
|
||||
}),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
$("brief-modal").close();
|
||||
hooks.banner("Asked for a brief. It will appear as a tab when it is written.", "good");
|
||||
setTimeout(() => hooks.banner(null), 5000);
|
||||
page.pendingResult = true;
|
||||
redraw();
|
||||
} catch (err) {
|
||||
if (err && err.pending) page.pendingResult = true;
|
||||
why.textContent =
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up. Try again in a moment."
|
||||
: "That did not go through. Try again in a moment.";
|
||||
} finally {
|
||||
go.disabled = false;
|
||||
go.textContent = "Write the brief";
|
||||
}
|
||||
}
|
||||
|
||||
export function renderBriefButton() {
|
||||
const btn = $("btn-brief");
|
||||
// Only Pathfinder has a brief playbook. Offering the button anywhere else
|
||||
// would send the agent a request it has no procedure for.
|
||||
const offer = page.S && page.S.workflow === "pathfinder";
|
||||
btn.hidden = !offer;
|
||||
// A finished (or paused) session has nobody to write it: the request would
|
||||
// wait on disk for a session that may never come.
|
||||
if (offer) btn.disabled = page.gone || page.pendingResult || Boolean(finish());
|
||||
}
|
||||
|
||||
export function renderDoc(main, id) {
|
||||
const doc = docs().find((d) => d.id === id);
|
||||
if (!doc) {
|
||||
main.appendChild(el("p", "doc-empty", "That document is not ready yet."));
|
||||
return;
|
||||
}
|
||||
const head = el("div", "doc-head");
|
||||
head.appendChild(el("h2", null, doc.title || "Document"));
|
||||
head.appendChild(el("span", "doc-version", "v" + (doc.version || 1)));
|
||||
if (doc.stale) {
|
||||
head.appendChild(el("span", "pill staged", "Out of date"));
|
||||
}
|
||||
|
||||
const tools = el("div", "doc-tools");
|
||||
// A brief is handed to people who were not in the room, so it gets a copy
|
||||
// that opens in any browser, formatting and all.
|
||||
if (doc.id === "brief") {
|
||||
const html = el("button", "btn small", "Save as HTML");
|
||||
html.type = "button";
|
||||
html.addEventListener("click", () => downloadDocHtml(doc));
|
||||
tools.appendChild(html);
|
||||
}
|
||||
tools.appendChild(printButton());
|
||||
|
||||
if (doc.saved) {
|
||||
tools.appendChild(docSavedNote(doc));
|
||||
} else {
|
||||
const save = el("button", "btn small", "Download");
|
||||
save.type = "button";
|
||||
save.addEventListener("click", () => downloadDoc(doc));
|
||||
tools.appendChild(save);
|
||||
}
|
||||
head.appendChild(tools);
|
||||
|
||||
main.appendChild(head);
|
||||
if (doc.note) main.appendChild(el("p", "help", doc.note));
|
||||
|
||||
const blocks = doc.blocks || [];
|
||||
if (!blocks.length) {
|
||||
main.appendChild(el("p", "doc-empty", "Nothing written yet. It fills in as you answer."));
|
||||
return;
|
||||
}
|
||||
// The block nearest the top of the column is the section + Add context
|
||||
// offers after leaving this tab. Its label is its first heading.
|
||||
docObserver?.disconnect();
|
||||
if (page.docInView && page.docInView.docId !== doc.id) page.docInView = null;
|
||||
const boxes = [];
|
||||
const topmost = () => {
|
||||
const top = main.getBoundingClientRect().top;
|
||||
const box = boxes.find((x) => x.getBoundingClientRect().bottom > top + 1);
|
||||
if (!box) return;
|
||||
const heading = box.querySelector("h1, h2, h3, h4, h5, h6");
|
||||
page.docInView = {
|
||||
docId: doc.id,
|
||||
blockId: box.dataset.block,
|
||||
label: (heading && heading.textContent.trim()) || doc.title || "Document",
|
||||
};
|
||||
};
|
||||
docObserver = typeof IntersectionObserver === "function" ? new IntersectionObserver(topmost, { root: main, threshold: [0, 0.25, 0.5, 0.75, 1] }) : null;
|
||||
blocks.forEach((b, i) => {
|
||||
const box = el("div", "block " + (b.state || "settled"));
|
||||
box.dataset.block = b.id || String(i);
|
||||
boxes.push(box);
|
||||
docObserver?.observe(box);
|
||||
if (b.state === "assumed") {
|
||||
// Borrowed from grill-with-ui and the best idea in it: show plainly which
|
||||
// parts are still a guess, so nobody mistakes a placeholder for a decision.
|
||||
box.appendChild(el("span", "block-tag", "Assumed for now, still open"));
|
||||
}
|
||||
if (b.state === "draft") box.appendChild(el("span", "block-tag", "Draft"));
|
||||
box.appendChild(blockBody(b));
|
||||
main.appendChild(box);
|
||||
});
|
||||
}
|
||||
|
||||
function printButton() {
|
||||
const print = el("button", "btn small", "Print");
|
||||
print.type = "button";
|
||||
// The print stylesheet drops everything that steers the session, so what
|
||||
// comes out is the document alone. "Save as PDF" in that dialog is also the
|
||||
// most portable save this page can offer.
|
||||
print.addEventListener("click", () => window.print());
|
||||
return print;
|
||||
}
|
||||
|
||||
// The spec's overview.md, read-only and drawn through the same markdown path
|
||||
// as every doc. No Download: the file is already on disk.
|
||||
export function renderOverview(main) {
|
||||
const head = el("div", "doc-head");
|
||||
head.appendChild(el("h2", null, "Overview"));
|
||||
const tools = el("div", "doc-tools");
|
||||
tools.appendChild(printButton());
|
||||
head.appendChild(tools);
|
||||
main.appendChild(head);
|
||||
main.appendChild(el("p", "help", `${page.overview.key}/overview.md · read-only, straight from disk`));
|
||||
const box = el("div", "block settled");
|
||||
box.appendChild(md(page.overview.text, "md"));
|
||||
main.appendChild(box);
|
||||
}
|
||||
|
||||
// The brief dialog's buttons, wired once at start-up.
|
||||
export function wireDocs() {
|
||||
$("btn-brief").addEventListener("click", openBrief);
|
||||
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
|
||||
$("brief-go").addEventListener("click", sendBrief);
|
||||
for (const radio of document.querySelectorAll('input[name="brief-range"]')) {
|
||||
radio.addEventListener("change", syncBriefDate);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,726 @@
|
||||
// Plan2Code Web Console - how a session ends: the finished screen, its offers, Stop and the way home; defines only.
|
||||
|
||||
import { el, md, copyButton, textWithCode, SVG_NS } from "../render.js";
|
||||
import {
|
||||
finishPaused,
|
||||
reviewOffer,
|
||||
commitOffer,
|
||||
handoffShape,
|
||||
ALL_DONE_LEAD,
|
||||
ALL_DONE_REST,
|
||||
handoffText,
|
||||
DASHBOARD_COMMAND,
|
||||
resumeCommand,
|
||||
afterFinishButton,
|
||||
DASHBOARD_NOTE,
|
||||
turnGate,
|
||||
homeButtonState,
|
||||
HOME_REPLY,
|
||||
stopAction,
|
||||
STOP_HANDOFF_REPLY,
|
||||
STOP_REPLY,
|
||||
REVIEW_REPLY,
|
||||
DONE_REPLY,
|
||||
DASHBOARD_REPLY,
|
||||
COMMIT_REPLY,
|
||||
} from "../answers.js";
|
||||
import { hooks, page, saveNow, redraw } from "../state.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
import {
|
||||
dashboardLive,
|
||||
reviewPending,
|
||||
docs,
|
||||
finish,
|
||||
agentAdrift,
|
||||
agentWorking,
|
||||
awaitingReply,
|
||||
isDashboard,
|
||||
} from "../selectors.js";
|
||||
import { docSavedNote, downloadDoc } from "../doc-files.js";
|
||||
import { pendingNotes } from "../uploads.js";
|
||||
|
||||
// The end of the session, and the only screen in this page whose job is to
|
||||
// send someone somewhere else.
|
||||
//
|
||||
// It reads in three beats, because that is the order the questions arrive in:
|
||||
// what just happened, the one thing to run, and where to run it. The command
|
||||
// is the whole point, so its Copy button is always on show -- the one on a
|
||||
// fenced code block only appears on hover, which is right for a sample buried
|
||||
// in prose and useless for the single action a screen exists to offer. A
|
||||
// finish with nothing left to run skips the last two beats: it gets a quiet
|
||||
// pointer at the dashboard instead of a Next step block.
|
||||
// "Before you close this": the three things someone looking at a finished
|
||||
// screen wonders. Every finish shape gets it; a pause says where the place is
|
||||
// kept, and a session with nothing left to run points at the dashboard alone.
|
||||
const GUIDE_ICONS = {
|
||||
safe: ["M5 12.5 10 17.5 19 7"],
|
||||
fresh: ["M19.5 12a7.5 7.5 0 1 1-2.4-5.5", "M19.5 4v4.5H15"],
|
||||
carry: ["M5 12h13", "M13 6.5 18.5 12 13 17.5"],
|
||||
};
|
||||
|
||||
function guideIcon(kind) {
|
||||
const wrap = el("span", `handoff-guide-icon is-${kind}`);
|
||||
wrap.setAttribute("aria-hidden", "true");
|
||||
const svg = document.createElementNS(SVG_NS, "svg");
|
||||
svg.setAttribute("viewBox", "0 0 24 24");
|
||||
svg.setAttribute("width", "16");
|
||||
svg.setAttribute("height", "16");
|
||||
for (const d of GUIDE_ICONS[kind]) {
|
||||
const path = document.createElementNS(SVG_NS, "path");
|
||||
path.setAttribute("d", d);
|
||||
svg.appendChild(path);
|
||||
}
|
||||
wrap.appendChild(svg);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function renderCloseGuide(shape, fin = {}) {
|
||||
// A command that is not a skill (a finish's git commit) runs in a terminal,
|
||||
// not "in the new session".
|
||||
const shell = typeof fin.command === "string" && Boolean(fin.command.trim()) && !fin.command.trim().startsWith("/");
|
||||
const panel = el("section", "handoff-guide");
|
||||
panel.setAttribute("aria-labelledby", "handoff-guide-title");
|
||||
const title = el("h3", "handoff-guide-title", "Before you close this");
|
||||
title.id = "handoff-guide-title";
|
||||
panel.appendChild(title);
|
||||
const rows = [
|
||||
["safe", "Safe to close", "This tab is only a window: whatever this session wrote is on disk, and nothing here needs you."],
|
||||
[
|
||||
"fresh",
|
||||
"Start fresh",
|
||||
shape === "paused"
|
||||
? stopWarning()
|
||||
? "Restart your agent window, or close the old session and start a new one. The command above starts it again."
|
||||
: "Restart your agent window, or close the old session and start a new one. Your saved place is picked up by the resume command above."
|
||||
: "Restart your agent window, or close the old session and start a new one. A new session starts from clean context. This one is full of this step's instructions, so continuing in it is slower and can confuse the next step.",
|
||||
],
|
||||
[
|
||||
"carry",
|
||||
"Carry on",
|
||||
shape === "all-done"
|
||||
? `In the new session, start from the dashboard with \`${DASHBOARD_COMMAND}\`.`
|
||||
: shell
|
||||
? `Run the command above in your terminal, then start the next step from the dashboard with \`${DASHBOARD_COMMAND}\`.`
|
||||
: `Paste the command above in the new session, or start from the dashboard with \`${DASHBOARD_COMMAND}\`.`,
|
||||
],
|
||||
];
|
||||
const list = el("ul", "handoff-guide-rows");
|
||||
for (const [kind, label, text] of rows) {
|
||||
const row = el("li", "handoff-guide-row");
|
||||
row.appendChild(guideIcon(kind));
|
||||
const body = el("div", "handoff-guide-text");
|
||||
body.appendChild(el("strong", "handoff-guide-label", label));
|
||||
body.appendChild(document.createTextNode(" "));
|
||||
body.appendChild(textWithCode("span", "handoff-guide-line", text));
|
||||
row.appendChild(body);
|
||||
list.appendChild(row);
|
||||
}
|
||||
panel.appendChild(list);
|
||||
return panel;
|
||||
}
|
||||
|
||||
// A review, a commit in Git or the dashboard the person just asked for is starting
|
||||
// here, so the page is about to carry on rather than end.
|
||||
function closeGuideHeld() {
|
||||
if (page.gone) return false;
|
||||
return ["review", "commit", "dashboard"].includes(page.local.afterBuild) || reviewPending() === "asked";
|
||||
}
|
||||
|
||||
export function renderHandoff(fin) {
|
||||
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));
|
||||
if (fin.body) card.appendChild(md(fin.body, "md prompt"));
|
||||
|
||||
// A finished build offers its review first, above the next step, because it
|
||||
// is the one thing on this screen that has to happen before they leave.
|
||||
const offer = reviewOffer(fin);
|
||||
if (offer && !["done", "dashboard", "commit"].includes(page.local.afterBuild)) {
|
||||
card.appendChild(renderReviewOffer(offer));
|
||||
}
|
||||
|
||||
// The commit, right after the review: one press starts Git's commit flow here.
|
||||
if (commitOffer(fin) && !page.gone && page.local.afterBuild !== "done" && page.local.afterBuild !== "dashboard") {
|
||||
card.appendChild(renderCommitOffer());
|
||||
}
|
||||
|
||||
// Three shapes: a next step to run, a pause with its resume command, or a
|
||||
// session with nothing left to run, which gets a quiet pointer at the
|
||||
// dashboard instead of a Next step block.
|
||||
const shape = handoffShape(fin);
|
||||
if (shape === "all-done") {
|
||||
const done = el("div", "handoff-done");
|
||||
done.appendChild(md(`${ALL_DONE_LEAD} ${ALL_DONE_REST}`, "md handoff-done-text"));
|
||||
const text = handoffText({ command: DASHBOARD_COMMAND });
|
||||
const row = el("div", "handoff-command");
|
||||
const code = el("code", "handoff-code", text);
|
||||
row.appendChild(code);
|
||||
row.appendChild(copyButton(text, "btn small ghost handoff-copy", code));
|
||||
done.appendChild(row);
|
||||
// Once the server is gone, the row above already is the offer's fallback.
|
||||
if (dashboardLive(fin) && !page.gone) done.appendChild(renderDashboardOffer(true));
|
||||
card.appendChild(done);
|
||||
} else {
|
||||
// A pause always offers its resume command, even when the agent left it out.
|
||||
const command =
|
||||
String(fin.command || "").trim() || resumeCommand({ workflow: page.S.workflow, specDir: page.S.specDir });
|
||||
const step = el("div", "handoff-step");
|
||||
step.appendChild(el("p", "handoff-label", "Next step"));
|
||||
step.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"handoff-where",
|
||||
fin.where ||
|
||||
(command.startsWith("/")
|
||||
? "Run this in the terminal where you started Plan2Code, in a new conversation:"
|
||||
: "Run this in your terminal:")
|
||||
)
|
||||
);
|
||||
|
||||
// Shown exactly as copied. Nothing goes on the clipboard that they cannot
|
||||
// read first: it is about to be pasted into a program with their files.
|
||||
const text = handoffText({ ...fin, command });
|
||||
const row = el("div", "handoff-command");
|
||||
const code = el("code", "handoff-code", text);
|
||||
row.appendChild(code);
|
||||
row.appendChild(copyButton(text, "btn small handoff-copy", code));
|
||||
step.appendChild(row);
|
||||
if (text !== command) {
|
||||
step.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"handoff-note",
|
||||
"The --web at the end asks Plan2Code to open this page again, so you carry on here rather than in the terminal."
|
||||
)
|
||||
);
|
||||
}
|
||||
card.appendChild(step);
|
||||
|
||||
// A finished (never paused) screen always names the way to the dashboard
|
||||
// from a new conversation, unless the offer's own fallback already does.
|
||||
if (shape === "next") {
|
||||
const offerDash = dashboardLive(fin);
|
||||
if (offerDash) card.appendChild(renderDashboardOffer(false));
|
||||
if (!(offerDash && page.gone)) {
|
||||
card.appendChild(
|
||||
textWithCode(
|
||||
"p",
|
||||
"handoff-fresh",
|
||||
`To start something else, run \`${DASHBOARD_COMMAND}\` in a new conversation.`
|
||||
)
|
||||
);
|
||||
const freshText = handoffText({ command: DASHBOARD_COMMAND });
|
||||
const freshRow = el("div", "handoff-command handoff-fresh-row");
|
||||
const freshCode = el("code", "handoff-code", freshText);
|
||||
freshRow.appendChild(freshCode);
|
||||
freshRow.appendChild(copyButton(freshText, "btn small ghost handoff-copy", freshCode));
|
||||
card.appendChild(freshRow);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Not while a hand-off they just asked for is starting on this page: "Safe
|
||||
// to close" and "start a new one" would contradict the line above it. The
|
||||
// press re-renders the page, and so does the agent taking it up.
|
||||
if (!closeGuideHeld()) card.appendChild(renderCloseGuide(shape, fin));
|
||||
|
||||
card.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"handoff-close",
|
||||
reviewPending() === "open"
|
||||
? "The review is optional. Skip it and nothing else here needs you."
|
||||
: "That is everything on this page."
|
||||
)
|
||||
);
|
||||
|
||||
// What they were working on is on disk, but only the agent's copy is. This
|
||||
// is the last moment anyone is looking at this page, so the way to take the
|
||||
// document with them belongs here and not only behind a tab they may never
|
||||
// open again — unless the doc is `saved`, in which case the file itself is
|
||||
// already on disk and a download would be a second copy of it.
|
||||
const keep = docs().find((d) => d.id === fin.doc) || docs()[0];
|
||||
if (keep && (keep.blocks || []).length) {
|
||||
const tools = el("div", "handoff-tools");
|
||||
if (keep.saved) {
|
||||
tools.appendChild(docSavedNote(keep));
|
||||
} else {
|
||||
const save = el("button", "btn small", `Download ${keep.title || "the document"}`);
|
||||
save.type = "button";
|
||||
save.addEventListener("click", () => downloadDoc(keep));
|
||||
tools.appendChild(save);
|
||||
}
|
||||
card.appendChild(tools);
|
||||
}
|
||||
|
||||
// Answers staged and never sent are lost the moment this page closes, and
|
||||
// this page's one promise is that nothing gets lost. Say so plainly rather
|
||||
// than letting them walk away from work they thought was safe.
|
||||
const stuck = Object.keys(page.local.staged).length;
|
||||
if (stuck) {
|
||||
card.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"handoff-unsent",
|
||||
`${stuck} answer${stuck === 1 ? "" : "s"} here ${stuck === 1 ? "was" : "were"} never sent, ` +
|
||||
`and Plan2Code has finished. If ${stuck === 1 ? "it" : "they"} still matter, say so in the ` +
|
||||
`next session: nothing on this page will reach it now.`
|
||||
)
|
||||
);
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
// The review button, on the hand-off of a finished build (a finished quick
|
||||
// task; an implementation phase gets its review offer earlier, as a verdict
|
||||
// on the sign-off card).
|
||||
//
|
||||
// It is a request, not a command: the page cannot run a review, it asks the
|
||||
// agent that is still sitting in its wait loop, the same way "Write a brief"
|
||||
// does. So it is only offered while there is a server to carry the press, and
|
||||
// once there is not, it turns into the command that does the same thing from
|
||||
// the terminal instead of a button that would go nowhere.
|
||||
function renderReviewOffer(offer) {
|
||||
const box = el("section", "review-offer");
|
||||
box.appendChild(el("p", "handoff-label", "Before you go"));
|
||||
box.appendChild(el("h3", "review-offer-title", offer.label));
|
||||
const { asked, disabled } = afterFinishButton(page.local.afterBuild, "review", page.pendingResult);
|
||||
|
||||
if (page.gone) {
|
||||
box.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"review-offer-text",
|
||||
asked
|
||||
? "The session closed before the review could start. To run it now, use this in the terminal, in a new conversation:"
|
||||
: "This session has closed, so the review cannot start from here any more. To run it, use this in the terminal, in a new conversation:"
|
||||
)
|
||||
);
|
||||
const text = "/plan2code-review";
|
||||
const row = el("div", "handoff-command");
|
||||
const code = el("code", "handoff-code", text);
|
||||
row.appendChild(code);
|
||||
row.appendChild(copyButton(text, "btn small handoff-copy", code));
|
||||
box.appendChild(row);
|
||||
return box;
|
||||
}
|
||||
|
||||
box.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"review-offer-text",
|
||||
"A careful review of the files this session changed: bugs, gaps against what was asked for, and anything risky. " +
|
||||
"The findings come back on this page and you choose which ones get fixed. Nothing changes until you do."
|
||||
)
|
||||
);
|
||||
const row = el("div", "btn-row");
|
||||
const go = el("button", "btn primary review-go", asked ? "Review requested…" : "Review it now");
|
||||
go.type = "button";
|
||||
go.disabled = disabled;
|
||||
go.addEventListener("click", () => sendAfterBuild("review"));
|
||||
row.appendChild(go);
|
||||
if (!asked) {
|
||||
const no = el("button", "btn ghost", "No thanks, I am done");
|
||||
no.type = "button";
|
||||
no.disabled = disabled;
|
||||
no.addEventListener("click", () => sendAfterBuild("done"));
|
||||
row.appendChild(no);
|
||||
}
|
||||
box.appendChild(row);
|
||||
return box;
|
||||
}
|
||||
|
||||
// Commit what was just built without leaving the page. Like the review button
|
||||
// it is a request to an agent still in its wait loop, so it is only drawn
|
||||
// while the server is there; the command printed below stays for the terminal.
|
||||
function renderCommitOffer() {
|
||||
const box = el("section", "review-offer");
|
||||
box.appendChild(el("p", "handoff-label", "Commit it"));
|
||||
box.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"review-offer-text",
|
||||
"Git reads what changed, drafts the message and asks before it commits. It opens right here, on the git board."
|
||||
)
|
||||
);
|
||||
const { asked, disabled } = afterFinishButton(page.local.afterBuild, "commit", page.pendingResult);
|
||||
const row = el("div", "btn-row");
|
||||
const go = el("button", "btn primary", asked ? "Opening Git…" : "Commit it now");
|
||||
go.type = "button";
|
||||
go.disabled = disabled;
|
||||
go.addEventListener("click", () => sendAfterBuild("commit"));
|
||||
row.appendChild(go);
|
||||
box.appendChild(row);
|
||||
return box;
|
||||
}
|
||||
|
||||
// The way back to the dashboard, on a finished screen whose agent opted in
|
||||
// with `finish.dashboard`. Like the review button it is a request to an agent
|
||||
// still in its wait loop, so once the server is gone it turns into the
|
||||
// command that opens the dashboard from a new conversation instead.
|
||||
function renderDashboardOffer(primary) {
|
||||
const box = el("section", "dashboard-offer");
|
||||
if (page.gone) {
|
||||
box.appendChild(
|
||||
el(
|
||||
"p",
|
||||
null,
|
||||
"This session has closed, so the button cannot reach Plan2Code any more. To open the dashboard, run this in a new conversation:"
|
||||
)
|
||||
);
|
||||
const text = handoffText({ command: DASHBOARD_COMMAND });
|
||||
const row = el("div", "handoff-command");
|
||||
const code = el("code", "handoff-code", text);
|
||||
row.appendChild(code);
|
||||
row.appendChild(copyButton(text, "btn small handoff-copy", code));
|
||||
box.appendChild(row);
|
||||
return box;
|
||||
}
|
||||
const { asked, disabled } = afterFinishButton(page.local.afterBuild, "dashboard", page.pendingResult);
|
||||
const go = el(
|
||||
"button",
|
||||
primary ? "btn primary" : "btn",
|
||||
asked ? "Opening the dashboard…" : "Back to the dashboard"
|
||||
);
|
||||
go.type = "button";
|
||||
go.disabled = disabled;
|
||||
go.addEventListener("click", () => sendAfterBuild("dashboard"));
|
||||
box.appendChild(go);
|
||||
box.appendChild(textWithCode("p", "dashboard-note", DASHBOARD_NOTE));
|
||||
return box;
|
||||
}
|
||||
|
||||
// Any answer to a finished session's offers, as one send through the ordinary
|
||||
// submit. Like a brief, it names no question: `__review`, `__commit`, `__done`
|
||||
// and `__dashboard` are about the session.
|
||||
const AFTER_FINISH_REPLIES = { review: REVIEW_REPLY, done: DONE_REPLY, dashboard: DASHBOARD_REPLY, commit: COMMIT_REPLY };
|
||||
|
||||
async function sendAfterBuild(kind) {
|
||||
if (page.gone || page.pendingResult || page.local.afterBuild) return;
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
actions: [{ i: `__${kind}`, type: kind }],
|
||||
reply: AFTER_FINISH_REPLIES[kind],
|
||||
}),
|
||||
});
|
||||
if (res.status === 409) {
|
||||
page.pendingResult = true;
|
||||
hooks.banner("Your last answers are still being picked up. Try again in a moment.", "info");
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
page.local.afterBuild = kind;
|
||||
page.pendingResult = true;
|
||||
saveNow();
|
||||
const started = {
|
||||
review: "Review requested. It starts here in a moment.",
|
||||
dashboard: "Opening the dashboard. It appears here in a moment.",
|
||||
commit: "Opening Git. It appears here in a moment.",
|
||||
}[kind];
|
||||
if (started) {
|
||||
hooks.banner(started, "good");
|
||||
setTimeout(() => hooks.banner(null), 5000);
|
||||
}
|
||||
} catch {
|
||||
hooks.banner("That did not go through. Nothing was lost; try again.", "warn");
|
||||
} finally {
|
||||
redraw();
|
||||
}
|
||||
}
|
||||
|
||||
let stoppingHidden = false;
|
||||
|
||||
// A stop is under way if this browser sent one, or if the server is holding
|
||||
// one nobody has collected: the second covers a reload on a resumed session,
|
||||
// a second tab, another machine.
|
||||
export function stopInProgress() {
|
||||
return page.local.stopping || (page.pendingStop ? { at: 0, answers: 0 } : null);
|
||||
}
|
||||
|
||||
export function renderStopButton() {
|
||||
const b = $("btn-stop");
|
||||
if (!page.S || finish()) {
|
||||
b.hidden = true;
|
||||
return;
|
||||
}
|
||||
b.hidden = false;
|
||||
if (stopInProgress()) {
|
||||
b.textContent = "Stopping…";
|
||||
b.disabled = false;
|
||||
b.title = "Show how the stop is going";
|
||||
return;
|
||||
}
|
||||
b.textContent = "Stop session";
|
||||
// Only on the person's turn, unless nothing is coming (see turnGate).
|
||||
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 = {
|
||||
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.",
|
||||
}[gate] || (stopWarning() ? "End this session. Work since the last save is not kept." : "Save your place and end this session. You get a command to pick it up later.");
|
||||
}
|
||||
|
||||
// Plan2Code has the ball: it is working, or owes a reply to a send, and has
|
||||
// not gone quiet. What both session buttons wait out.
|
||||
function agentHasTheBall() {
|
||||
return (agentWorking() || awaitingReply().length > 0) && !agentAdrift();
|
||||
}
|
||||
|
||||
// The triangle left of Stop session. Mid-workflow it is a stop that lands on
|
||||
// the menu instead of a finish: the same staged answers ride along, the agent
|
||||
// saves its place the same way, then resumes the session as the dashboard.
|
||||
export function renderHomeButton() {
|
||||
const b = $("btn-home");
|
||||
const st = homeButtonState({
|
||||
workflow: page.S && page.S.workflow,
|
||||
finished: Boolean(page.S && finish()),
|
||||
stopping: Boolean(page.S && stopInProgress()),
|
||||
homeward: Boolean(page.local.homeward),
|
||||
adrift: Boolean(page.S) && agentAdrift(),
|
||||
gone: page.gone,
|
||||
pendingResult: page.pendingResult,
|
||||
waiting: Boolean(page.S) && agentHasTheBall(),
|
||||
warned: Boolean(page.S) && Boolean(stopWarning()),
|
||||
});
|
||||
b.hidden = st.hidden;
|
||||
b.disabled = st.disabled;
|
||||
b.title = st.title;
|
||||
}
|
||||
|
||||
function openHomeConfirm() {
|
||||
const n = Object.keys(page.local.staged).length + pendingNotes().length;
|
||||
const warn = stopWarning();
|
||||
// With a warning, "your place is saved" is the one thing not true: the
|
||||
// warning says what is lost, and the button says the choice is theirs.
|
||||
$("home-blurb").textContent =
|
||||
(n === 1 ? "The answer you have ready goes with it. " : n ? `The ${n} answers you have ready go with it. ` : "") +
|
||||
(warn ? "Plan2Code takes you back to the dashboard." : "Your place is saved; you can resume it from the dashboard.");
|
||||
$("home-go").textContent = warn ? "Leave anyway" : "Back to the dashboard";
|
||||
$("home-warn").hidden = !warn;
|
||||
$("home-warn").textContent = warn;
|
||||
$("home-modal").showModal();
|
||||
}
|
||||
|
||||
async function goHome() {
|
||||
const go = $("home-go");
|
||||
go.disabled = true;
|
||||
const payload = hooks.stagedPayload();
|
||||
payload.actions.push({ i: "__dashboard", type: "dashboard" });
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, HOME_REPLY].join("\n") }),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
hooks.markSent(payload);
|
||||
page.local.homeward = { at: Date.now() };
|
||||
saveNow();
|
||||
$("home-modal").close();
|
||||
} catch (err) {
|
||||
$("home-modal").close();
|
||||
// The server is holding an uncollected result: Send, Home and Stop all
|
||||
// need to read as busy until the frame or the ping says otherwise, same
|
||||
// as send() and sendAfterBuild() do on a 409.
|
||||
if (err && err.pending) page.pendingResult = true;
|
||||
hooks.banner(
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
|
||||
: "That did not go through. Nothing was lost; try again.",
|
||||
"warn"
|
||||
);
|
||||
} finally {
|
||||
go.disabled = false;
|
||||
redraw();
|
||||
}
|
||||
}
|
||||
|
||||
// Stopping now can lose answers: Planning writes nothing until its plan is
|
||||
// done, and Pathfinder nothing until its map exists. The agent knows where it
|
||||
// is and says so in `stopWarning`; Planning is assumed to lose answers unless
|
||||
// the agent says otherwise, because that is true of most of it.
|
||||
export function stopWarning() {
|
||||
if (typeof page.S.stopWarning === "string") return page.S.stopWarning.trim();
|
||||
if (page.S.workflow === "plan") {
|
||||
return "Planning only saves at set points along the way. Answers since the last save will not be kept, though you can go over them again next time.";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function openStopConfirm() {
|
||||
if (stopInProgress()) {
|
||||
stoppingHidden = false;
|
||||
return renderStopping();
|
||||
}
|
||||
const n = Object.keys(page.local.staged).length + pendingNotes().length;
|
||||
const warn = stopWarning();
|
||||
const dash = isDashboard();
|
||||
$("stop-blurb").textContent =
|
||||
(n === 1 ? "The answer you have ready goes with it. " : n ? `The ${n} answers you have ready go with it. ` : "") +
|
||||
(dash ? "Nothing has started yet, so there is nothing to save: this just ends the console session." : "");
|
||||
$("stop-blurb").hidden = !$("stop-blurb").textContent;
|
||||
$("stop-warn").hidden = !warn;
|
||||
$("stop-warn").textContent = warn;
|
||||
// The dashboard has nothing to hand off: one plain Stop. Elsewhere both
|
||||
// choices show, and "Just stop and save" turns into "Stop anyway" where
|
||||
// nothing is saved yet.
|
||||
$("stop-handoff").hidden = dash;
|
||||
const title = $("stop-go").querySelector(".stop-choice-title");
|
||||
const detail = $("stop-go").querySelector(".stop-choice-detail");
|
||||
if (dash) {
|
||||
title.textContent = "Stop";
|
||||
detail.textContent = "Ends the console session.";
|
||||
} else if (warn) {
|
||||
title.textContent = "Stop anyway";
|
||||
detail.textContent = "Ends the session now. What the warning above names is not kept.";
|
||||
} else {
|
||||
title.textContent = "Just stop and save";
|
||||
detail.textContent = "Saves what this step keeps on disk and gives you a command to resume. What we talked about is not kept.";
|
||||
}
|
||||
$("stop-modal").showModal();
|
||||
}
|
||||
|
||||
async function stopSession(handoff = false) {
|
||||
const buttons = [$("stop-handoff"), $("stop-go")];
|
||||
for (const b of buttons) b.disabled = true;
|
||||
const payload = hooks.stagedPayload();
|
||||
payload.actions.push(stopAction({ handoff }));
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, handoff ? STOP_HANDOFF_REPLY : STOP_REPLY].join("\n") }),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
hooks.markSent(payload);
|
||||
page.local.stopping = { at: Date.now(), answers: payload.sentIds.size };
|
||||
saveNow();
|
||||
$("stop-modal").close();
|
||||
stoppingHidden = false;
|
||||
} catch (err) {
|
||||
$("stop-modal").close();
|
||||
if (err && err.pending) page.pendingResult = true;
|
||||
hooks.banner(
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
|
||||
: "The stop did not go through. Nothing was lost; try again.",
|
||||
"warn"
|
||||
);
|
||||
} finally {
|
||||
for (const b of buttons) b.disabled = false;
|
||||
redraw();
|
||||
}
|
||||
}
|
||||
|
||||
// The wrapping-up screen, derived every render from what the page already
|
||||
// tracks: whether the request is collected, whether anyone is listening, and
|
||||
// whether the finish has landed.
|
||||
export function renderStopping() {
|
||||
const dlg = $("stopping-modal");
|
||||
const stopping = page.S && stopInProgress();
|
||||
if (!stopping) {
|
||||
if (dlg.open) dlg.close();
|
||||
return;
|
||||
}
|
||||
// The finish is the end of it: the hand-off card on the page says the rest.
|
||||
if (finish()) {
|
||||
page.local.stopping = null;
|
||||
saveNow();
|
||||
if (dlg.open) dlg.close();
|
||||
return;
|
||||
}
|
||||
|
||||
const sent = stopping.answers;
|
||||
const collected = !page.pendingResult;
|
||||
// Nobody is coming: the server stopped with no finish, or the agent has not
|
||||
// checked in for minutes. The request and any answers are on disk either
|
||||
// way, and the next session collects them.
|
||||
const stuck = page.gone || agentAdrift();
|
||||
const steps = [
|
||||
{ text: sent ? `Sent your ${sent === 1 ? "answer" : sent + " answers"} and the stop` : "Sent the stop", state: "done" },
|
||||
{
|
||||
text: collected ? "Plan2Code picked it up" : stuck ? "Plan2Code has not picked it up" : "Waiting for Plan2Code to pick it up",
|
||||
state: collected ? "done" : stuck ? "stuck" : "now",
|
||||
},
|
||||
{ text: "Saving your place and writing the command to pick it up", state: collected ? (stuck ? "stuck" : "now") : "later" },
|
||||
];
|
||||
const list = $("stop-steps");
|
||||
list.replaceChildren(
|
||||
...steps.map((s) => {
|
||||
const li = el("li", "is-" + s.state);
|
||||
li.appendChild(
|
||||
s.state === "now"
|
||||
? el("span", "spinner tiny")
|
||||
: el("span", "stop-mark", s.state === "done" ? "✓" : s.state === "stuck" ? "!" : "·")
|
||||
);
|
||||
li.appendChild(el("span", null, s.text));
|
||||
return li;
|
||||
})
|
||||
);
|
||||
|
||||
const extra = $("stop-extra");
|
||||
extra.replaceChildren();
|
||||
if (stuck) {
|
||||
extra.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"stop-note",
|
||||
page.gone
|
||||
? "The session closed without saying how to pick it up. Your answers and the stop are saved, and the next session collects them. To carry on, run this in the terminal, in a new conversation (or alternatively run `/plan2code` to relaunch the dashboard):"
|
||||
: "Plan2Code is not running right now, so nothing new has been saved yet. Your answers and the stop are held, and the next session collects them. To carry on, run this in the terminal, in a new conversation (or alternatively run `/plan2code` to relaunch the dashboard):"
|
||||
)
|
||||
);
|
||||
const text = handoffText({ command: resumeCommand(page.S) });
|
||||
const row = el("div", "handoff-command");
|
||||
const code = el("code", "handoff-code", text);
|
||||
row.appendChild(code);
|
||||
row.appendChild(copyButton(text, "btn small handoff-copy", code));
|
||||
extra.appendChild(row);
|
||||
} else {
|
||||
extra.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"stop-note",
|
||||
agentWorking() && !collected
|
||||
? "Plan2Code is in the middle of something. It stops as soon as that is done."
|
||||
: "This usually takes a moment. You can close the tab if you need to: the command also appears in the terminal."
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!stoppingHidden && !dlg.open) dlg.showModal();
|
||||
}
|
||||
|
||||
// The top bar's way home and Stop, wired once at start-up.
|
||||
export function wireEnding() {
|
||||
$("btn-home").addEventListener("click", openHomeConfirm);
|
||||
$("home-cancel").addEventListener("click", () => $("home-modal").close());
|
||||
$("home-go").addEventListener("click", goHome);
|
||||
$("btn-stop").addEventListener("click", openStopConfirm);
|
||||
$("stop-cancel").addEventListener("click", () => $("stop-modal").close());
|
||||
$("stop-handoff").addEventListener("click", () => stopSession(true));
|
||||
$("stop-go").addEventListener("click", () => stopSession(false));
|
||||
$("stopping-hide").addEventListener("click", () => {
|
||||
stoppingHidden = true;
|
||||
$("stopping-modal").close();
|
||||
});
|
||||
// Esc on a native dialog closes it without our say; count that as hiding, or
|
||||
// the next render would open it straight back up.
|
||||
$("stopping-modal").addEventListener("cancel", () => (stoppingHidden = true));
|
||||
}
|
||||
|
||||
// The three stop-related controls, drawn again when the agent comes or goes.
|
||||
export function renderStopControls() {
|
||||
renderStopButton();
|
||||
renderHomeButton();
|
||||
renderStopping();
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
// Plan2Code Web Console - hosts the git board: tabs, panels and what each click sends.
|
||||
|
||||
import { hooks, page, saveNow, redraw } from "../state.js";
|
||||
import { GIT_TABS, busyMode, gitReply, pickTab, nextStep, tabBadges, createSources, BRANCH_TYPES, commitTicks, cleanupGroups } from "../git-board.js";
|
||||
import { finish, agentWorking, agentAdrift, gitAwaiting, myTurn, byId, activity } from "../selectors.js";
|
||||
import { drawGitBoard, activeTab } from "../git-board-view.js";
|
||||
import { el, md, copyButton } from "../render.js";
|
||||
import { helpKeyTarget } from "../help.js";
|
||||
import { postJson } from "../net.js";
|
||||
|
||||
// The git board: drawn from state.git, which only console.mjs writes. A click
|
||||
// never runs git here. It sends one `__git` action through /submit, and the
|
||||
// agent confirms by card, runs the command and posts a `reread`, whose frame
|
||||
// redraws the board. The rules live in git-board.js and the drawing in
|
||||
// git-board-view.js; this is the host: the busy mode, the tab, the scroll,
|
||||
// the keys, and the panels' state.
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// What the person has typed or ticked on the board. Every state frame redraws
|
||||
// the board from state.git, so this is what carries their place across it.
|
||||
// panel the open panel: "create", "commit" or "cleanup", or null
|
||||
// create the Create prompt's fields, while it is open
|
||||
// ticks the commit table's ticked paths; ignore, its .gitignore toggles
|
||||
// sweep the cleanup list's ticked branches
|
||||
// base the pull-request base the picker chose
|
||||
// settled cards the agent settled since the last click on the board
|
||||
// tab the tab on show: "changes", "branches" or "sync", or null before the first draw
|
||||
// scroll how far the column was scrolled on each tab, put back after each redraw
|
||||
// repickAt when their last board click went out (ms): the first agent post
|
||||
// after it moves the board to the new next step's tab
|
||||
export const board = {
|
||||
tab: null,
|
||||
scroll: { changes: 0, branches: 0, sync: 0 },
|
||||
repickAt: null,
|
||||
query: "",
|
||||
showAll: false,
|
||||
remoteOpen: null,
|
||||
panel: null,
|
||||
create: null,
|
||||
ticks: null,
|
||||
ignore: new Set(),
|
||||
sweep: null,
|
||||
base: null,
|
||||
settled: new Set(),
|
||||
};
|
||||
|
||||
// The search, ticks and open panel are also kept in `local`, so a reload (and
|
||||
// a skill hop back) restores them the way card drafts already do. Stale picks
|
||||
// are harmless: the next send re-checks every path against the snapshot. The
|
||||
// restore waits for the first draw: load() has not run when this module does.
|
||||
const boardBlank = {
|
||||
tab: null,
|
||||
scroll: { changes: 0, branches: 0, sync: 0 },
|
||||
repickAt: null,
|
||||
query: "",
|
||||
showAll: false,
|
||||
remoteOpen: null,
|
||||
panel: null,
|
||||
create: null,
|
||||
ticks: null,
|
||||
sweep: null,
|
||||
base: null,
|
||||
};
|
||||
|
||||
// Each reset gets its own scroll memory: boardBlank's must never be the one written to.
|
||||
export const resetBoard = () => {
|
||||
Object.assign(board, boardBlank, { scroll: { ...boardBlank.scroll } });
|
||||
board.ignore.clear();
|
||||
};
|
||||
|
||||
let boardHydrated = false;
|
||||
|
||||
// True from hydration until the first draw has picked its tab: that draw is a reload.
|
||||
let boardReloaded = false;
|
||||
|
||||
const hydrateBoard = () => {
|
||||
boardHydrated = true;
|
||||
const g = page.local.gitBoard;
|
||||
if (!g) return;
|
||||
boardReloaded = true;
|
||||
Object.assign(board, boardBlank, {
|
||||
tab: GIT_TABS.some((t) => t.id === g.tab) ? g.tab : null,
|
||||
scroll: { changes: 0, branches: 0, sync: 0, ...(g.scroll || {}) },
|
||||
repickAt: typeof g.repickAt === "number" ? g.repickAt : null,
|
||||
query: g.query || "",
|
||||
showAll: Boolean(g.showAll),
|
||||
remoteOpen: g.remoteOpen ?? null,
|
||||
panel: g.panel || null,
|
||||
create: g.create || null,
|
||||
ticks: g.ticks ? new Set(g.ticks) : null,
|
||||
sweep: g.sweep ? new Set(g.sweep) : null,
|
||||
base: g.base || null,
|
||||
ignore: new Set(g.ignore || []),
|
||||
});
|
||||
};
|
||||
|
||||
const persistBoard = () => {
|
||||
page.local.gitBoard = {
|
||||
tab: board.tab,
|
||||
scroll: { ...board.scroll },
|
||||
repickAt: board.repickAt,
|
||||
query: board.query,
|
||||
showAll: board.showAll,
|
||||
remoteOpen: board.remoteOpen,
|
||||
panel: board.panel,
|
||||
create: board.create,
|
||||
ticks: board.ticks ? [...board.ticks] : null,
|
||||
sweep: board.sweep ? [...board.sweep] : null,
|
||||
base: board.base,
|
||||
ignore: [...board.ignore],
|
||||
};
|
||||
saveNow();
|
||||
};
|
||||
|
||||
// How busy the board is (busyMode in git-board.js). Running while a send is
|
||||
// uncollected or the agent is mid-turn, and nothing queues. A "working" agent
|
||||
// that has gone adrift lets go, as gitAwaiting() does: collecting a click
|
||||
// marks it working, and an agent that died there must not leave the board
|
||||
// locked for good. A question card of the agent's open in the card slot holds
|
||||
// the board too: the card is the turn, and a board click sent beside it went
|
||||
// alone while the staged answer waited for some later, unrelated send.
|
||||
const gitMode = () =>
|
||||
busyMode({
|
||||
gone: page.gone,
|
||||
pending: page.pendingResult,
|
||||
running: Boolean(finish()) || (agentWorking() && !agentAdrift()) || gitAwaiting(),
|
||||
cardWaiting: myTurn().some((i) => i.kind !== "notice"),
|
||||
});
|
||||
|
||||
const gitLocked = () => gitMode() !== "idle";
|
||||
|
||||
// `wording` only shapes the sentence (the operation an Abort names, say); it
|
||||
// is not part of the action.
|
||||
async function sendGit(op, fields = {}, wording = {}) {
|
||||
if (page.gone || finish()) return;
|
||||
if (page.pendingResult) {
|
||||
hooks.banner("Your last click is still being picked up. One moment.", "info");
|
||||
page.pendingBannerUp = true;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
actions: [{ i: "__git", type: "git", op, ...fields }],
|
||||
reply: gitReply(op, { ...fields, ...wording }),
|
||||
}),
|
||||
});
|
||||
if (res.status === 409) {
|
||||
page.pendingResult = true;
|
||||
hooks.banner("Your last click is still being picked up. One moment.", "info");
|
||||
page.pendingBannerUp = true;
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
board.settled.clear();
|
||||
board.panel = null;
|
||||
board.create = null;
|
||||
board.sweep = null;
|
||||
// The commit table is always on show: a click drops its picks, and the
|
||||
// redraw that follows re-seeds them from the snapshot the page already has.
|
||||
board.ticks = null;
|
||||
board.ignore = new Set();
|
||||
page.pendingResult = true;
|
||||
page.local.gitSentAt = Date.now();
|
||||
saveNow();
|
||||
// The draw after this persists it with the rest of the board.
|
||||
board.repickAt = page.local.gitSentAt;
|
||||
redraw();
|
||||
} catch {
|
||||
hooks.banner("That did not go through. Nothing was lost; try again.", "warn");
|
||||
}
|
||||
}
|
||||
|
||||
// What the view may ask of the page. Built once: every handler reads the
|
||||
// board and state.git at the moment of the click, not at the draw.
|
||||
const gitOn = {
|
||||
send: sendGit,
|
||||
redraw: () => redraw(),
|
||||
pickTab: (id) => {
|
||||
board.tab = id;
|
||||
persistBoard();
|
||||
redraw();
|
||||
},
|
||||
openPanel: (name, opts) => openPanel(name, opts),
|
||||
closePanel: () => closePanel(),
|
||||
pickPrHost: (host, kind) => pickPrHost(host, kind),
|
||||
persist: () => persistBoard(),
|
||||
};
|
||||
|
||||
// The tab drawn last, which the scroll listener files the column's place under.
|
||||
let gitTabDrawn = null;
|
||||
|
||||
// FR-9: their own click that landed (an agent post after it went out) and
|
||||
// arriving at the board go to the next step's tab; a reload and a change they
|
||||
// did not click for keep the tab they had. A frame with no updatedAt has not
|
||||
// landed: never re-pick on a guess.
|
||||
function resolveGitTab(step) {
|
||||
const before = board.tab;
|
||||
let reason = "background";
|
||||
if (board.repickAt && page.S.updatedAt && Date.parse(page.S.updatedAt) > board.repickAt) {
|
||||
reason = "landed";
|
||||
board.repickAt = null;
|
||||
} else if (board.tab == null) reason = "arrival";
|
||||
else if (boardReloaded) reason = "reload";
|
||||
boardReloaded = false;
|
||||
board.tab = pickTab({ current: board.tab, stepTab: step.tab, reason });
|
||||
if (board.tab !== before || reason === "landed") persistBoard();
|
||||
}
|
||||
|
||||
export function renderGitBoard(main, card = null, pager = null) {
|
||||
if (!boardHydrated) hydrateBoard();
|
||||
const git = page.S.git;
|
||||
const step = nextStep(git);
|
||||
resolveGitTab(step);
|
||||
const result = byId("git-result");
|
||||
const { node, cardSlot } = drawGitBoard({
|
||||
git,
|
||||
board,
|
||||
now: Date.now(),
|
||||
mode: gitMode(),
|
||||
offlineReason: page.gone ? "gone" : page.pendingResult ? "pending" : null,
|
||||
step,
|
||||
badges: tabBadges(git, { stepTab: step.tab }),
|
||||
notice: result && result.kind === "notice" ? result : null,
|
||||
activity: activity(),
|
||||
hasCard: Boolean(card),
|
||||
h: { el, md, copyButton },
|
||||
on: gitOn,
|
||||
});
|
||||
if (card) cardSlot.appendChild(card);
|
||||
if (pager) cardSlot.appendChild(pager);
|
||||
const tabs = node.querySelector(".git-tabs");
|
||||
if (tabs) tabs.addEventListener("keydown", gitTabKeys);
|
||||
// The column scrolls, not the board, and every redraw rebuilds the board,
|
||||
// so the column would land back at the top. Each tab keeps its own place,
|
||||
// so a tab switch opens where that tab was left.
|
||||
const tab = activeTab({ board, step });
|
||||
gitTabDrawn = tab;
|
||||
main.addEventListener("scroll", rememberGitTabScroll, { passive: true });
|
||||
main.appendChild(node);
|
||||
main.scrollTop = board.scroll[tab] || 0;
|
||||
persistBoard();
|
||||
}
|
||||
|
||||
// The scroll listener on `main` for each tab's place, kept as a named function
|
||||
// because renderGitBoard re-adds it on every redraw: adding the same listener
|
||||
// twice is a no-op, where a fresh closure would pile up.
|
||||
function rememberGitTabScroll() {
|
||||
const main = $("main");
|
||||
if (!gitTabDrawn || !main || !main.querySelector(":scope > .git-board")) return;
|
||||
board.scroll[gitTabDrawn] = main.scrollTop;
|
||||
}
|
||||
|
||||
// Arrow keys, Home and End move between the tabs, as in the Help dialog. The
|
||||
// board is redrawn, so focus goes to the new tab after the render.
|
||||
function gitTabKeys(e) {
|
||||
const index = GIT_TABS.findIndex((t) => t.id === gitTabDrawn);
|
||||
const to = helpKeyTarget(e.key, Math.max(0, index), GIT_TABS.length);
|
||||
if (to < 0) return;
|
||||
e.preventDefault();
|
||||
board.tab = GIT_TABS[to].id;
|
||||
persistBoard();
|
||||
redraw();
|
||||
$(`git-tab-${board.tab}`)?.focus();
|
||||
}
|
||||
|
||||
// The host is remembered for every project by the server (pr-hosts.json);
|
||||
// the action that follows has the agent re-read, which rebuilds the link.
|
||||
async function pickPrHost(host, kind) {
|
||||
if (gitLocked()) return;
|
||||
const res = await postJson("/pr-host", { host, kind });
|
||||
if (res.status !== 200) {
|
||||
hooks.banner("That could not be saved. Try again in a moment.", "warn");
|
||||
return;
|
||||
}
|
||||
// The save is durable; a state frame that landed mid-POST still wins.
|
||||
if (gitLocked()) return;
|
||||
sendGit("pr-host", { host, kind });
|
||||
}
|
||||
|
||||
// Opening a panel moves to the tab that draws it, so a panel is never open
|
||||
// on a hidden tab. `opts.ticks` / `opts.ignore` set the commit panel's picks
|
||||
// (the held-back .gitignore offer opens it with nothing ticked).
|
||||
function openPanel(name, opts = {}) {
|
||||
if (gitLocked()) return;
|
||||
const git = page.S.git;
|
||||
if (name === "commit") {
|
||||
board.tab = "changes";
|
||||
if (opts.ticks) board.ticks = new Set(opts.ticks);
|
||||
if (opts.ignore) board.ignore = new Set(opts.ignore);
|
||||
if (board.panel !== "commit") return openCommit(git);
|
||||
persistBoard();
|
||||
return redraw();
|
||||
}
|
||||
if (name === "create") {
|
||||
board.tab = opts.commit ? "changes" : "branches";
|
||||
// A branch for the commit takes what the commit table has ticked, not a fresh default.
|
||||
if (opts.commit && !opts.files) return openCreate(git, { ...opts, ...tablePicks(git) });
|
||||
return openCreate(git, opts);
|
||||
}
|
||||
if (name === "cleanup") {
|
||||
board.tab = "branches";
|
||||
return openCleanup(git);
|
||||
}
|
||||
}
|
||||
|
||||
const closePanel = () => {
|
||||
board.panel = null;
|
||||
board.create = null;
|
||||
redraw();
|
||||
};
|
||||
|
||||
// In commit mode the commit panel hands over what it would have sent (its
|
||||
// ticked files and .gitignore picks, already checked against the snapshot);
|
||||
// a detached commit, which never shows the panel, starts from commitTicks().
|
||||
function openCreate(git, { commit = false, files = null, ignore = [] } = {}) {
|
||||
if (gitLocked()) return;
|
||||
// The agent's description is of the changes waiting: with none left (they
|
||||
// were committed since), it describes nothing on this tree.
|
||||
const pending = Number(page.S.git && page.S.git.changes && page.S.git.changes.count) || 0;
|
||||
const describe = pending && page.S.board && typeof page.S.board.describe === "string" ? page.S.board.describe : "";
|
||||
board.create = {
|
||||
from: createSources(git, commit).preset,
|
||||
type: BRANCH_TYPES[0],
|
||||
description: describe,
|
||||
name: null,
|
||||
commit,
|
||||
files: commit ? files || [...commitTicks(git.changes)] : null,
|
||||
ignore: commit ? ignore : [],
|
||||
};
|
||||
board.panel = "create";
|
||||
redraw();
|
||||
$("git-new-desc")?.focus();
|
||||
}
|
||||
|
||||
// The commit table's picks, checked against the snapshot: `{ files, ignore }`.
|
||||
// Seeded from commitTicks() when the table has not been drawn yet.
|
||||
function tablePicks(git) {
|
||||
const ch = git.changes || {};
|
||||
const known = new Set([...(ch.files || []), ...(ch.untrackedDirs || [])].map((f) => f.path));
|
||||
const ticks = board.ticks || (board.ticks = commitTicks(ch));
|
||||
return { files: [...ticks].filter((p) => known.has(p)), ignore: [...board.ignore].filter((p) => known.has(p)) };
|
||||
}
|
||||
|
||||
// The commit table is always on show, so opening its panel keeps what the
|
||||
// person has already ticked; sendGit() re-seeds the picks after each click.
|
||||
function openCommit(git) {
|
||||
if (gitLocked()) return;
|
||||
if (board.panel === "commit") return closePanel();
|
||||
const picks = tablePicks(git);
|
||||
// Detached: there is no branch to commit on, so the commit makes one.
|
||||
if (git.hasCommits !== false && !(git.head || {}).branch) return openCreate(git, { commit: true, ...picks });
|
||||
board.panel = "commit";
|
||||
board.create = null;
|
||||
redraw();
|
||||
}
|
||||
|
||||
function openCleanup(git) {
|
||||
if (gitLocked()) return;
|
||||
if (board.panel === "cleanup") return closePanel();
|
||||
const { merged, gone } = cleanupGroups(git);
|
||||
board.sweep = new Set([...merged, ...gone].map((b) => b.name));
|
||||
board.panel = "cleanup";
|
||||
board.create = null;
|
||||
redraw();
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
// Plan2Code Web Console - the Help dialog and the first-run Welcome (named so it is never confused with the pure help.js).
|
||||
|
||||
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";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// The first dashboard a person ever sees gets a Welcome dialog. Closing it by
|
||||
// any route (button, Esc, backdrop) saves looks.welcomeSeen, which rides in
|
||||
// looks.json like every other preference. Waits out the wake-up animation and
|
||||
// never lands on top of another open dialog.
|
||||
export function maybeWelcome() {
|
||||
if (!looksReady || looks.welcomeSeen === true || !page.S || !isDashboard() || finish() || page.wake) return;
|
||||
if (document.querySelector("dialog[open]")) return;
|
||||
openWelcome();
|
||||
}
|
||||
|
||||
export function openWelcome() {
|
||||
if ($("help-modal").open) $("help-modal").close();
|
||||
const slot = $("welcome-bot");
|
||||
if (!slot.firstElementChild) {
|
||||
const bot = $("planny").cloneNode(true);
|
||||
bot.removeAttribute("id");
|
||||
bot.setAttribute("class", "planny is-point v1");
|
||||
slot.appendChild(bot);
|
||||
}
|
||||
const dlg = $("welcome-modal");
|
||||
if (!dlg.open) dlg.showModal();
|
||||
$("welcome-done").focus();
|
||||
}
|
||||
|
||||
// Whether the two halves are actually talking, in the one place someone goes
|
||||
// when they are asking that question. Written on open rather than kept live,
|
||||
// because a line that rewrites itself under a reader is worse than a stale one
|
||||
// they can close and reopen.
|
||||
function renderAbout() {
|
||||
const line = $("about-live");
|
||||
line.className = "about-live";
|
||||
if (finish()) {
|
||||
line.textContent = "Right now: the session is finished, and the command above is all that is left to do.";
|
||||
} else if (page.gone) {
|
||||
line.classList.add("is-bad");
|
||||
line.textContent =
|
||||
"Right now: this page cannot reach that program. Either it has stopped, or the machine went to sleep. The link from the terminal will bring it back.";
|
||||
} else if (agentAdrift()) {
|
||||
line.classList.add("is-bad");
|
||||
line.textContent =
|
||||
"Right now: this page is fine, but Plan2Code has not checked in for a few minutes. Have a look at the terminal; it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type continue there to wake it.";
|
||||
} else {
|
||||
line.classList.add("is-good");
|
||||
line.textContent = "Right now: both halves are talking to each other.";
|
||||
}
|
||||
}
|
||||
|
||||
let helpBuilt = false;
|
||||
|
||||
async function renderHelpVersion() {
|
||||
const slot = $("help-version");
|
||||
try {
|
||||
const res = await fetch("/version", { cache: "no-store" });
|
||||
const { version } = res.ok ? await res.json() : {};
|
||||
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
|
||||
slot.hidden = !version;
|
||||
} catch {
|
||||
slot.hidden = true;
|
||||
}
|
||||
}
|
||||
|
||||
const HELP_MOODS = [
|
||||
["point", "Your turn"],
|
||||
["work", "Working"],
|
||||
["happy", "All caught up"],
|
||||
["done", "Done"],
|
||||
["adrift", "Not running"],
|
||||
["gone", "Not connected"],
|
||||
];
|
||||
|
||||
// The help content waits in its <template> until the first time ? is pressed,
|
||||
// so none of it costs the first paint. The tab buttons come from HELP_TABS.
|
||||
function buildHelp() {
|
||||
const content = $("help-content").content.cloneNode(true);
|
||||
const modal = $("help-modal");
|
||||
const tabs = $("help-tabs");
|
||||
const panels = $("help-panels");
|
||||
// In the dialog itself, so every <use href="#hi-..."> resolves.
|
||||
modal.appendChild(content.querySelector(".help-icons"));
|
||||
for (const panel of content.querySelectorAll("section.help-panel")) panels.appendChild(panel);
|
||||
// Tab 3 shows the real Planny in each mood, cloned the way the dashboard's
|
||||
// confirm pane does, so the moods can never drift from the drawing.
|
||||
const moods = panels.querySelector(".help-moods-row");
|
||||
for (const [mood, label] of HELP_MOODS) {
|
||||
const bot = $("planny").cloneNode(true);
|
||||
bot.removeAttribute("id");
|
||||
bot.setAttribute("class", `planny is-${mood} v0 help-mood-bot`);
|
||||
bot.setAttribute("aria-hidden", "true");
|
||||
const cell = el("div", "help-mood");
|
||||
cell.appendChild(bot);
|
||||
cell.appendChild(el("span", null, label));
|
||||
moods.appendChild(cell);
|
||||
}
|
||||
for (const row of panels.querySelectorAll("[data-copy]")) {
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
export function openHelp() {
|
||||
if (!helpBuilt) buildHelp();
|
||||
const id = helpTabFor({
|
||||
view: page.view,
|
||||
dashboard: isDashboard(),
|
||||
gone: page.gone,
|
||||
adrift: agentAdrift(),
|
||||
finished: !!finish(),
|
||||
workflow: page.S && page.S.workflow,
|
||||
workspace: $("workspace-modal").open,
|
||||
meterRed: page.meterFrame?.level === "red",
|
||||
});
|
||||
selectHelpTab(id);
|
||||
renderAbout();
|
||||
renderHelpVersion();
|
||||
$("help-modal").showModal();
|
||||
$("help-tab-" + id).focus();
|
||||
}
|
||||
|
||||
// Help opened straight on one topic, when Help has that topic; otherwise it
|
||||
// stays wherever openHelp() landed.
|
||||
export function openHelpOn(id) {
|
||||
openHelp();
|
||||
if (!HELP_TABS.some((t) => t.id === id)) return;
|
||||
selectHelpTab(id);
|
||||
$("help-tab-" + id).focus();
|
||||
}
|
||||
|
||||
// Help's and Welcome's buttons and keys, and the Workspace dialog's link to Help.
|
||||
export function wireHelp() {
|
||||
$("workspace-help").addEventListener("click", openHelp);
|
||||
lightDismiss($("help-modal"));
|
||||
lightDismiss($("welcome-modal"));
|
||||
|
||||
$("welcome-done").addEventListener("click", () => $("welcome-modal").close());
|
||||
$("welcome-modal").addEventListener("close", () => {
|
||||
if (looks.welcomeSeen !== true) {
|
||||
looks.welcomeSeen = true;
|
||||
saveLooks();
|
||||
}
|
||||
$("btn-about").focus();
|
||||
});
|
||||
$("help-panels").addEventListener("click", (e) => {
|
||||
if (e.target.closest && e.target.closest('[data-action="welcome"]')) openWelcome();
|
||||
});
|
||||
|
||||
$("btn-about").addEventListener("click", () => {
|
||||
openHelp();
|
||||
});
|
||||
$("help-done").addEventListener("click", () => $("help-modal").close());
|
||||
// Opened from inside the Workspace dialog, focus goes back there.
|
||||
$("help-modal").addEventListener("close", () =>
|
||||
($("workspace-modal").open ? $("workspace-help") : $("btn-about")).focus()
|
||||
);
|
||||
$("help-modal").addEventListener("keydown", (e) => {
|
||||
// The page-wide Ctrl/Cmd+Enter already stands down while any dialog is open;
|
||||
// this keeps the key inside Help as well.
|
||||
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();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
// Plan2Code Web Console - User Preferences: looks, sounds and the launcher's model menus.
|
||||
|
||||
import { adoptLooks, applyLooks, loadLooks, looks, renderSwatches, resetLooks, saveLooks, syncLooks } from "../looks.js";
|
||||
import { dropHeldSound, releaseHeldSound, sound, soundOn } from "../sound.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";
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// Following the system means following it as it changes, including the accent,
|
||||
// whose light and dark shades are different colors.
|
||||
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
|
||||
if (looks.theme === "system") {
|
||||
applyLooks();
|
||||
renderSwatches();
|
||||
}
|
||||
});
|
||||
|
||||
loadLooks();
|
||||
if (boot && boot.looks && typeof boot.looks === "object") adoptLooks(boot.looks);
|
||||
applyLooks();
|
||||
syncLooks();
|
||||
|
||||
for (const evt of ["pointerdown", "keydown"]) {
|
||||
window.addEventListener(evt, releaseHeldSound);
|
||||
}
|
||||
}
|
||||
|
||||
// Preferences' buttons and fields.
|
||||
export function wireLooks() {
|
||||
lightDismiss($("looks-modal"));
|
||||
$("btn-looks").addEventListener("click", () => {
|
||||
renderSwatches();
|
||||
setModelsStatus("", false);
|
||||
loadModelsData();
|
||||
$("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;
|
||||
$("looks-role").appendChild(option);
|
||||
}
|
||||
$("looks-role").addEventListener("change", (e) => {
|
||||
looks.role = normalizeRole(e.target.value);
|
||||
saveLooks();
|
||||
// The dashboard banner, and the starter templates and Ask starters on any
|
||||
// page, all order themselves by the role.
|
||||
if (page.S) redraw();
|
||||
});
|
||||
for (const radio of document.querySelectorAll('input[name="looks-theme"]')) {
|
||||
radio.addEventListener("change", () => {
|
||||
looks.theme = radio.value;
|
||||
saveLooks();
|
||||
});
|
||||
}
|
||||
for (const radio of document.querySelectorAll('input[name="looks-width"]')) {
|
||||
radio.addEventListener("change", () => {
|
||||
looks.width = radio.value;
|
||||
saveLooks();
|
||||
});
|
||||
}
|
||||
$("looks-sound").addEventListener("change", (e) => {
|
||||
looks.sound = e.target.checked;
|
||||
// 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();
|
||||
// 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);
|
||||
});
|
||||
for (const box of document.querySelectorAll("input[data-sound]")) {
|
||||
box.addEventListener("change", () => {
|
||||
const event = box.dataset.sound;
|
||||
looks[soundKey(event)] = box.checked;
|
||||
if (!box.checked) dropHeldSound(event);
|
||||
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();
|
||||
});
|
||||
$("models-reset").addEventListener("click", () => {
|
||||
if (!modelsData) return;
|
||||
modelsData.user = Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
|
||||
saveModels();
|
||||
renderModels();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
// Plan2Code Web Console - the launching, starting and waiting screens, with Planny's poses; defines only.
|
||||
|
||||
import { page, redraw } from "../state.js";
|
||||
import { el, approvalTip } from "../render.js";
|
||||
import { startPose, startingHint, SKILL_CATALOG, staleLaunchFeedback, workflowTitle } from "../answers.js";
|
||||
import { agentAdrift, doingNow, docs } from "../selectors.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
const LAUNCH_QUIPS = [
|
||||
"Passing Planny the baton…",
|
||||
"Reading the manual…",
|
||||
"Polishing the star…",
|
||||
"Warming up the engines…",
|
||||
"Laying out the good pens…",
|
||||
"Consulting the map…",
|
||||
"Putting the kettle on…",
|
||||
"Rolling out the checklist…",
|
||||
];
|
||||
|
||||
let launchTicker = null;
|
||||
|
||||
// Planny flies centre stage: the same drawing as the dock's, cloned so the
|
||||
// markup stays the single source of him, and the same sky the dock fills.
|
||||
function flightStage() {
|
||||
const stage = el("div", "launch-stage");
|
||||
const sky = el("div", "sky launch-sky");
|
||||
const r = (a, b) => a + Math.random() * (b - a);
|
||||
for (let i = 0; i < 30; i++) {
|
||||
const star = el("i", "star" + (i % 6 === 0 ? " hot" : ""));
|
||||
const dur = r(3, 9);
|
||||
star.style.setProperty("--y", r(2, 98).toFixed(1) + "%");
|
||||
star.style.setProperty("--p", r(0, 1).toFixed(3));
|
||||
star.style.setProperty("--s", r(1.2, 2.6).toFixed(2) + "px");
|
||||
star.style.setProperty("--dur", dur.toFixed(2) + "s");
|
||||
star.style.setProperty("--delay", (-r(0, dur)).toFixed(2) + "s");
|
||||
sky.appendChild(star);
|
||||
}
|
||||
stage.appendChild(sky);
|
||||
const bot = $("planny").cloneNode(true);
|
||||
bot.removeAttribute("id");
|
||||
bot.setAttribute("class", "planny is-work v1 launch-planny");
|
||||
stage.appendChild(bot);
|
||||
return stage;
|
||||
}
|
||||
|
||||
// A skill's own Planny, acting out the skill while it starts and works: the
|
||||
// pose is cloned from its <template> in index.html, so the drawing stays
|
||||
// markup and the motion stays in app.css. A skill with none keeps the flight.
|
||||
function startStage(workflow) {
|
||||
const pose = startPose(workflow);
|
||||
const art = pose && $("start-poses")?.content.querySelector(`[data-pose="${pose}"]`);
|
||||
if (!art) return flightStage();
|
||||
const stage = el("div", "launch-stage pose-stage");
|
||||
stage.appendChild(art.cloneNode(true));
|
||||
return stage;
|
||||
}
|
||||
|
||||
// The pane Planny's stage sits in, for the launching, starting and waiting
|
||||
// screens alike. A render empties the column, and a stage taken off the page
|
||||
// restarts every animation in it, which a build posting every few seconds
|
||||
// (and the heartbeat pulling what it missed) would turn into a stutter. So
|
||||
// the pane already on screen is reused when the next screen shows the same
|
||||
// pose: its words are rebuilt around a stage that never leaves the page.
|
||||
// That is also what carries him from "Starting…" into the work unbroken.
|
||||
function posePane(main, cls, workflow) {
|
||||
const pose = startPose(workflow) || "flight";
|
||||
const held = page.heldPose;
|
||||
page.heldPose = null;
|
||||
if (held && held.dataset.pose === pose) {
|
||||
held.className = cls;
|
||||
for (const child of [...held.children]) if (!child.classList.contains("launch-stage")) child.remove();
|
||||
return held;
|
||||
}
|
||||
const pane = el("div", cls);
|
||||
pane.dataset.pose = pose;
|
||||
pane.appendChild(startStage(workflow));
|
||||
if (held) main.insertBefore(pane, held);
|
||||
else main.appendChild(pane);
|
||||
return pane;
|
||||
}
|
||||
|
||||
// The getting-ready screen. The pick is sent and the dashboard agent is
|
||||
// turning it into a live skill: it resumes this session under the skill's
|
||||
// workflow, which flips `S.workflow` off "dashboard" and ends this screen
|
||||
// (adopt() clears `local.launching` on exactly that change).
|
||||
//
|
||||
// It is deliberately fun rather than a spinner with a shrug: a launch takes
|
||||
// a few honest seconds (the skill file is read, the session resumed, the
|
||||
// first payload composed) and a dead-quiet wait is when people wonder
|
||||
// whether the click worked. Planny flies, the quips rotate, and after a
|
||||
// while the hint points at the terminal, which narrates the same hand-off.
|
||||
export function renderLaunching(main) {
|
||||
const l = page.local.launching || {};
|
||||
const pane = posePane(main, "launching", l.skill && SKILL_CATALOG.find((e) => e.skill === l.skill)?.workflow);
|
||||
|
||||
const stale = staleLaunchFeedback(l.title, agentAdrift());
|
||||
pane.appendChild(el("p", "card-kicker", stale ? stale.kicker : "On it"));
|
||||
pane.appendChild(el("h2", "launch-title", stale ? stale.title : `Waking up ${l.title || "the next mode"}`));
|
||||
pane.appendChild(el("p", "launch-quip", stale ? stale.quip : LAUNCH_QUIPS[0]));
|
||||
pane.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"launch-hint",
|
||||
stale ? stale.hint : "This page turns into its home the moment it answers. No need to touch anything."
|
||||
)
|
||||
);
|
||||
startLaunchTicker();
|
||||
}
|
||||
|
||||
/* The starting screen: a session is open but the agent has not put anything
|
||||
on it yet. It is what the person looks at while the skill reads the
|
||||
project, finds its files and composes the first questions, so it gets the
|
||||
same flight as a launch rather than a bare spinner, and says which skill
|
||||
is on its way. */
|
||||
const START_QUIPS = [
|
||||
"Reading the project…",
|
||||
"Checking what is already written down…",
|
||||
"Lining up the first questions…",
|
||||
"Polishing the star…",
|
||||
"Laying out the good pens…",
|
||||
"Consulting the map…",
|
||||
];
|
||||
|
||||
function startingElapsed() {
|
||||
const since = page.S && page.S.agent ? Date.parse(page.S.agent.since) : NaN;
|
||||
return Number.isFinite(since) ? Date.now() - since : 0;
|
||||
}
|
||||
|
||||
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)}`));
|
||||
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());
|
||||
startLaunchTicker();
|
||||
}
|
||||
|
||||
// The quips rotate on their own clock rather than on render: state frames
|
||||
// arrive whenever the agent posts, and a waiting screen pinned to them
|
||||
// would sit on one line for most of the wait. The interval looks the
|
||||
// elements up fresh each tick, so it survives the screen being rebuilt,
|
||||
// and it stops itself when neither screen is up any more.
|
||||
function startLaunchTicker() {
|
||||
if (!launchTicker) {
|
||||
launchTicker = setInterval(() => {
|
||||
const kicker = document.querySelector(".launching .card-kicker");
|
||||
const title = document.querySelector(".launch-title");
|
||||
const q = document.querySelector(".launch-quip");
|
||||
const hint = document.querySelector(".launch-hint");
|
||||
const cur = page.local.launching;
|
||||
const starting = !cur && document.querySelector(".launching.starting");
|
||||
if ((!cur && !starting) || !q) {
|
||||
clearInterval(launchTicker);
|
||||
launchTicker = null;
|
||||
return;
|
||||
}
|
||||
if (starting) {
|
||||
const elapsed = startingElapsed();
|
||||
q.textContent = START_QUIPS[Math.floor(elapsed / 2600) % START_QUIPS.length];
|
||||
if (hint) hint.textContent = startingHint(elapsed);
|
||||
return;
|
||||
}
|
||||
const elapsed = Date.now() - cur.at;
|
||||
const stale = staleLaunchFeedback(cur.title, agentAdrift());
|
||||
if (kicker) kicker.textContent = stale ? stale.kicker : "On it";
|
||||
if (title) title.textContent = stale ? stale.title : `Waking up ${cur.title || "the next mode"}`;
|
||||
q.textContent = stale ? stale.quip : LAUNCH_QUIPS[Math.floor(elapsed / 2600) % LAUNCH_QUIPS.length];
|
||||
if (hint) {
|
||||
hint.textContent = stale
|
||||
? stale.hint
|
||||
: elapsed > 90000
|
||||
? "Still getting ready. Your terminal has the play-by-play if you want to watch it there."
|
||||
: "This page turns into its home the moment it answers. No need to touch anything.";
|
||||
}
|
||||
}, 900);
|
||||
}
|
||||
}
|
||||
|
||||
export function renderWaiting(main) {
|
||||
const doing = doingNow();
|
||||
// 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
|
||||
// stood here said less about what was going on than he does.
|
||||
const pane = posePane(main, "waiting-pane", page.S.workflow);
|
||||
// A build with nothing to ask yet. Say what is happening and where to
|
||||
// watch it, instead of promising questions that may not come for a while.
|
||||
const title = el("h2", null, (page.S.headline && page.S.headline.stage) || "Working on it");
|
||||
// Once the agent stops answering nothing is turning, so neither is the ring
|
||||
// (the adrift watcher redraws this pane on the flip).
|
||||
if (!agentAdrift()) {
|
||||
const spin = el("span", "spinner tiny waiting-spin");
|
||||
spin.setAttribute("aria-hidden", "true");
|
||||
title.prepend(spin);
|
||||
}
|
||||
pane.appendChild(title);
|
||||
pane.appendChild(el("p", null, doing));
|
||||
const ask = "If Plan2Code needs you, the question appears here on its own.";
|
||||
if (!docs().length) {
|
||||
pane.appendChild(el("p", null, ask));
|
||||
return;
|
||||
}
|
||||
// "Task" and the tasks tab's own name both open that tab, so the pointer is
|
||||
// one click from what it points at. A build posts it as `phase` ("Phase N
|
||||
// tasks"); a quick task ticks the steps of its `plan` in place (an older
|
||||
// agent may still post a separate `tasks` tab). A skill with no task list
|
||||
// (Document, Plan) has nothing live to follow, so it gets no pointer at all.
|
||||
const list =
|
||||
docs().find((d) => d.id === "phase") ||
|
||||
docs().find((d) => d.id === "tasks") ||
|
||||
(page.S.workflow === "quick-task" && docs().find((d) => d.id === "plan")) ||
|
||||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
|
||||
if (!list) {
|
||||
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
|
||||
return;
|
||||
}
|
||||
const jump = (word) => {
|
||||
const b = el("button", "waiting-jump", word);
|
||||
b.type = "button";
|
||||
b.addEventListener("click", () => {
|
||||
page.view = "doc:" + list.id;
|
||||
redraw();
|
||||
});
|
||||
return b;
|
||||
};
|
||||
const p = el("p");
|
||||
p.append(
|
||||
"The tabs above fill in as it goes. You can follow along with live ",
|
||||
jump("Task"),
|
||||
" updates in the ",
|
||||
jump(list.title || "Phase tasks"),
|
||||
" tab. " + ask
|
||||
);
|
||||
pane.appendChild(p);
|
||||
}
|
||||
|
||||
// The stars for Planny's flight, made once. Each gets its place and pace as
|
||||
// custom properties set through the CSSOM: the CSP forbids style attributes
|
||||
// in markup, and the stylesheet cannot roll dice. They sit still, invisible,
|
||||
// until the dock is `is-flying`.
|
||||
export function fillSky() {
|
||||
const sky = $("dock-sky");
|
||||
const r = (a, b) => a + Math.random() * (b - a);
|
||||
for (let i = 0; i < 34; i++) {
|
||||
const star = document.createElement("i");
|
||||
star.className = "star" + (i % 7 === 0 ? " hot" : "");
|
||||
const dur = r(4, 12);
|
||||
star.style.setProperty("--y", r(3, 97).toFixed(1) + "%");
|
||||
star.style.setProperty("--p", r(0, 1).toFixed(3));
|
||||
star.style.setProperty("--s", r(1, 2.2).toFixed(2) + "px");
|
||||
star.style.setProperty("--dur", dur.toFixed(2) + "s");
|
||||
// Negative, so the field starts full rather than every star at the edge.
|
||||
star.style.setProperty("--delay", (-r(0, dur)).toFixed(2) + "s");
|
||||
sky.appendChild(star);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
// Plan2Code Web Console - the read-only Workspace of extra folders, and @mentions.
|
||||
|
||||
import { hooks, page } from "../state.js";
|
||||
import { copyButton, el, lightDismiss, selectContents } from "../render.js";
|
||||
import { selSpec, specList, workspaceFolders } from "../selectors.js";
|
||||
import { postJson } from "../net.js";
|
||||
import { nameProblem } from "../workspace.js";
|
||||
|
||||
// The Workspace dialog. The server is the only writer of workspace.json: the
|
||||
// page asks through /workspace/*, and the new list comes back on the next
|
||||
// frame, which redraws the dialog while it is open.
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// Folders the agent reported it cannot read, each told once per page load
|
||||
// and launch. The server keeps only the current launch's reports, so a name
|
||||
// that drops out of the list may be told again after the next launch.
|
||||
const issuesTold = new Set();
|
||||
|
||||
let issueBannerTimer = null;
|
||||
|
||||
export function tellFolderIssues() {
|
||||
const issues = (page.wsFrame && page.wsFrame.issues) || [];
|
||||
const names = new Set(issues.map((i) => i.name));
|
||||
for (const name of [...issuesTold]) if (!names.has(name)) issuesTold.delete(name);
|
||||
const fresh = issues.find((i) => !issuesTold.has(i.name));
|
||||
if (!fresh) return;
|
||||
issuesTold.add(fresh.name);
|
||||
const extras = [];
|
||||
if (fresh.hint) {
|
||||
extras.push(document.createTextNode(" "));
|
||||
extras.push(el("code", "banner-hint", fresh.hint));
|
||||
}
|
||||
const open = el("button", "btn tiny banner-action", "Open workspace");
|
||||
open.type = "button";
|
||||
open.addEventListener("click", () => {
|
||||
hooks.banner(null);
|
||||
openWorkspace();
|
||||
});
|
||||
extras.push(open);
|
||||
hooks.banner(`The agent can't read @${fresh.name}: ${fresh.reason}`, "warn", extras);
|
||||
clearTimeout(issueBannerTimer);
|
||||
// Then the next folder waiting to be told, if several came at once.
|
||||
issueBannerTimer = setTimeout(() => {
|
||||
if (page.gone) return;
|
||||
hooks.banner(null);
|
||||
tellFolderIssues();
|
||||
}, 15000);
|
||||
}
|
||||
|
||||
export async function syncWorkspaceScope(spec) {
|
||||
if (!page.S || page.S.workflow !== "dashboard" || page.gone || !page.wsFrame) return;
|
||||
const want = spec === undefined ? (selSpec() && selSpec().dir) || "" : spec;
|
||||
page.scopeMine = want;
|
||||
if ((page.wsFrame.scope || "") === want || scopeAsked === want) return;
|
||||
scopeAsked = want;
|
||||
const { status, body } = await postJson("/workspace/scope", { spec: want });
|
||||
if (status === 200 && body && Array.isArray(body.folders)) page.wsFrame = { ...page.wsFrame, ...body };
|
||||
scopeAsked = null;
|
||||
if ($("workspace-modal").open) renderWorkspace();
|
||||
}
|
||||
|
||||
let scopeAsked = null;
|
||||
|
||||
// The dialog's "Remembered for" line: whose list this is.
|
||||
function workspaceScopeText() {
|
||||
const scope = (page.wsFrame && page.wsFrame.scope) || "";
|
||||
if (!scope) return "Remembered for this project, so your next console session here starts with these folders.";
|
||||
const spec = specList().find((s) => s.dir === scope);
|
||||
const name = spec ? spec.name : scope.split("/").pop();
|
||||
return `Remembered for the ${name} spec, and loaded again whenever it is picked.`;
|
||||
}
|
||||
|
||||
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
|
||||
|
||||
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
|
||||
|
||||
// The folder whose Remove is waiting on its inline confirm, by id.
|
||||
let wsConfirm = null;
|
||||
|
||||
let wsBusy = false;
|
||||
|
||||
export async function openWorkspace() {
|
||||
const dlg = $("workspace-modal");
|
||||
try {
|
||||
const res = await fetch("/workspace?check=1", { cache: "no-store" });
|
||||
if (res.ok) page.wsFrame = await res.json();
|
||||
} catch {}
|
||||
wsConfirm = null;
|
||||
setAddMsg("");
|
||||
renderWorkspace();
|
||||
if (!dlg.open) dlg.showModal();
|
||||
$("workspace-path").focus();
|
||||
}
|
||||
|
||||
function setAddMsg(text, kind, action) {
|
||||
const p = $("workspace-add-msg");
|
||||
p.className = "workspace-add-msg" + (kind ? " is-" + kind : "");
|
||||
p.textContent = text;
|
||||
if (action) p.appendChild(action);
|
||||
}
|
||||
|
||||
// One <li> per folder, original first. A frame that keeps the same folders in
|
||||
// the same order is painted into the rows already there, so a box someone is
|
||||
// typing in keeps its text, caret and focus; any other change rebuilds.
|
||||
export function renderWorkspace() {
|
||||
const list = $("workspace-list");
|
||||
const folders = workspaceFolders();
|
||||
const ids = folders.map((f) => f.id).join("\n");
|
||||
if (list.dataset.ids !== ids) {
|
||||
list.dataset.ids = ids;
|
||||
list.replaceChildren(...folders.map(workspaceRow));
|
||||
}
|
||||
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
|
||||
$("workspace-browse").hidden = Boolean(page.wsFrame && page.wsFrame.remote);
|
||||
$("workspace-scope").textContent = workspaceScopeText();
|
||||
}
|
||||
|
||||
function workspaceRow(f) {
|
||||
const li = el("li", "ws-entry");
|
||||
li.dataset.fid = f.id;
|
||||
|
||||
const head = el("div", "ws-head");
|
||||
head.appendChild(el("span", "ws-chip"));
|
||||
if (f.original) head.appendChild(el("span", "ws-original", "started here — can't be removed"));
|
||||
li.appendChild(head);
|
||||
|
||||
const pathRow = el("div", "ws-path-row");
|
||||
const code = el("code", "ws-path");
|
||||
pathRow.appendChild(code);
|
||||
const copy = el("button", "btn small", "Copy path");
|
||||
copy.type = "button";
|
||||
copy.addEventListener("click", async () => {
|
||||
const folder = workspaceFolders().find((x) => x.id === f.id);
|
||||
if (!folder) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(folder.path);
|
||||
copy.textContent = "Copied";
|
||||
setTimeout(() => (copy.textContent = "Copy path"), 1500);
|
||||
} catch {
|
||||
// Refused: the path is selected instead, ready for Ctrl+C.
|
||||
selectContents(code);
|
||||
copy.textContent = "Press Ctrl+C";
|
||||
}
|
||||
});
|
||||
pathRow.appendChild(copy);
|
||||
if (!f.original) {
|
||||
const remove = el("button", "btn small danger ws-remove", "Remove");
|
||||
remove.type = "button";
|
||||
remove.addEventListener("click", () => {
|
||||
wsConfirm = f.id;
|
||||
renderWorkspace();
|
||||
li.querySelector(".ws-confirm .btn.danger")?.focus();
|
||||
});
|
||||
pathRow.appendChild(remove);
|
||||
}
|
||||
li.appendChild(pathRow);
|
||||
|
||||
li.appendChild(el("div", "ws-marks"));
|
||||
li.appendChild(workspaceField(f, "name", "Name"));
|
||||
li.appendChild(workspaceField(f, "description", "What is it?"));
|
||||
return li;
|
||||
}
|
||||
|
||||
// The Name and What-is-it boxes. Each saves on blur or Enter through
|
||||
// /workspace/edit, and only when it holds something new.
|
||||
function workspaceField(f, field, labelText) {
|
||||
const wrap = el("div", "ws-field");
|
||||
const id = `ws-${field}-${f.id}`;
|
||||
const label = el("label", null, labelText);
|
||||
label.htmlFor = id;
|
||||
const input = el("input");
|
||||
input.type = "text";
|
||||
input.id = id;
|
||||
input.dataset.field = field;
|
||||
input.autocomplete = "off";
|
||||
input.spellcheck = false;
|
||||
if (field === "description") input.maxLength = 200;
|
||||
const err = el("p", "field-error");
|
||||
err.hidden = true;
|
||||
const current = () => workspaceFolders().find((x) => x.id === f.id);
|
||||
const saved = () => (current() ? current()[field] || "" : "");
|
||||
const showError = (text) => {
|
||||
err.textContent = text || "";
|
||||
err.hidden = !text;
|
||||
input.classList.toggle("invalid", Boolean(text));
|
||||
};
|
||||
|
||||
if (field === "name") {
|
||||
input.addEventListener("input", () => showError(nameProblem(input.value.trim()) ? NAME_RULE : ""));
|
||||
}
|
||||
const save = async (leaving) => {
|
||||
const value = input.value.trim();
|
||||
if (value === saved()) return showError("");
|
||||
if (field === "name" && nameProblem(value)) {
|
||||
if (!leaving) return showError(NAME_RULE);
|
||||
input.value = saved();
|
||||
return showError("");
|
||||
}
|
||||
const { status, body } = await postJson("/workspace/edit", { id: f.id, [field]: value });
|
||||
// An earlier "Added as @x" is out of date once the list moves on.
|
||||
if (status === 200) {
|
||||
setAddMsg("");
|
||||
return showError("");
|
||||
}
|
||||
if (body.reason === "name-taken") showError(`@${value} is taken — try @${body.suggest}.`);
|
||||
else if (body.reason === "bad-name") showError(NAME_RULE);
|
||||
else showError("That did not save. Try again.");
|
||||
if (leaving) input.value = saved();
|
||||
};
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Enter") return;
|
||||
e.preventDefault();
|
||||
save(false);
|
||||
});
|
||||
input.addEventListener("blur", () => save(true));
|
||||
wrap.append(label, input, err);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
// Everything in a row that follows the frame. A box with focus is left as
|
||||
// the person has it; every other box shows what is saved.
|
||||
function paintWorkspaceRow(li, f) {
|
||||
if (!li) return;
|
||||
const missing = (page.wsFrame.missing || []).includes(f.id);
|
||||
const issue = (page.wsFrame.issues || []).find((x) => x.name === f.name);
|
||||
li.classList.toggle("is-missing", missing);
|
||||
li.querySelector(".ws-chip").textContent = "@" + f.name;
|
||||
li.querySelector(".ws-path").textContent = f.path;
|
||||
for (const input of li.querySelectorAll("input[data-field]")) {
|
||||
if (document.activeElement !== input) input.value = f[input.dataset.field] || "";
|
||||
}
|
||||
|
||||
const marks = li.querySelector(".ws-marks");
|
||||
marks.replaceChildren();
|
||||
if (missing) marks.appendChild(el("p", "ws-mark is-missing", "This folder no longer exists"));
|
||||
if (issue) {
|
||||
marks.appendChild(el("p", "ws-mark is-issue", "The agent can't read this yet: " + issue.reason));
|
||||
if (issue.hint) {
|
||||
const row = el("div", "ws-hint-row");
|
||||
const code = el("code", "ws-hint", issue.hint);
|
||||
row.append(code, copyButton(issue.hint, "btn tiny", code));
|
||||
marks.appendChild(row);
|
||||
}
|
||||
}
|
||||
if (f.nested) marks.appendChild(el("p", "ws-mark is-nested", "Inside another folder in the list"));
|
||||
marks.hidden = !marks.children.length;
|
||||
|
||||
// Built once per confirm, so a frame landing meanwhile keeps its focus.
|
||||
const open = li.querySelector(".ws-confirm");
|
||||
if (wsConfirm !== f.id) open?.remove();
|
||||
else if (open) open.querySelector("span").textContent = `Remove @${f.name}? The agent is told.`;
|
||||
else {
|
||||
const box = el("div", "ws-confirm");
|
||||
box.setAttribute("role", "alert");
|
||||
box.appendChild(el("span", null, `Remove @${f.name}? The agent is told.`));
|
||||
const keep = el("button", "btn small ghost", "Keep it");
|
||||
keep.type = "button";
|
||||
keep.addEventListener("click", () => {
|
||||
wsConfirm = null;
|
||||
renderWorkspace();
|
||||
li.querySelector(".ws-remove")?.focus();
|
||||
});
|
||||
const go = el("button", "btn small danger", "Remove");
|
||||
go.type = "button";
|
||||
go.addEventListener("click", async () => {
|
||||
go.disabled = true;
|
||||
const { status } = await postJson("/workspace/remove", { id: f.id });
|
||||
wsConfirm = null;
|
||||
if (status === 200) setAddMsg("");
|
||||
if (status !== 200) setAddMsg(`@${f.name} could not be removed. Try again.`, "error");
|
||||
renderWorkspace();
|
||||
$("workspace-path").focus();
|
||||
});
|
||||
box.append(keep, go);
|
||||
li.appendChild(box);
|
||||
}
|
||||
}
|
||||
|
||||
// Add by typed path, or by a path Browse… came back with. `name` is only
|
||||
// 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;
|
||||
wsBusy = true;
|
||||
$("workspace-add").disabled = true;
|
||||
const { status, body } = await postJson("/workspace/add", name ? { path: trimmed, name } : { path: trimmed });
|
||||
wsBusy = false;
|
||||
$("workspace-add").disabled = false;
|
||||
if (status === 200) {
|
||||
$("workspace-path").value = "";
|
||||
setAddMsg(`Added as @${body.name}.` + (body.nested ? " It's inside another folder in the list." : ""), "good");
|
||||
if (body.name && page.wsFrame && !workspaceFolders().some((f) => f.id === body.id)) {
|
||||
page.wsFrame = { ...page.wsFrame, folders: [...workspaceFolders(), body] };
|
||||
}
|
||||
renderWorkspace();
|
||||
hooks.renderWhere();
|
||||
return;
|
||||
}
|
||||
switch (body.reason) {
|
||||
case "not-a-folder":
|
||||
return setAddMsg("That isn't a folder on this machine.", "error");
|
||||
case "duplicate":
|
||||
return setAddMsg(`Already in the workspace as @${body.name}.`, "error");
|
||||
case "name-taken": {
|
||||
const taken = name || String(body.suggest || "").replace(/-\d+$/, "");
|
||||
const use = el("button", "btn tiny", `Use @${body.suggest}`);
|
||||
use.type = "button";
|
||||
use.addEventListener("click", () => addWorkspaceFolder(trimmed, body.suggest));
|
||||
return setAddMsg(`@${taken} is taken — try @${body.suggest}.`, "error", use);
|
||||
}
|
||||
case "bad-name":
|
||||
return setAddMsg(NAME_RULE, "error");
|
||||
default:
|
||||
return setAddMsg("That folder could not be added. Try again.", "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function browseWorkspace() {
|
||||
const b = $("workspace-browse");
|
||||
if (b.disabled) return;
|
||||
b.disabled = true;
|
||||
setAddMsg("Waiting for the folder picker…");
|
||||
const { status, body } = await postJson("/workspace/browse", {});
|
||||
b.disabled = false;
|
||||
if (status === 200 && body.path) {
|
||||
setAddMsg("");
|
||||
return addWorkspaceFolder(body.path);
|
||||
}
|
||||
if (status === 200 && body.cancelled) return setAddMsg("");
|
||||
setAddMsg(BROWSE_UNAVAILABLE, "error");
|
||||
}
|
||||
|
||||
// The dialog's buttons, and the footer label that opens it.
|
||||
export function wireWorkspace() {
|
||||
lightDismiss($("workspace-modal"));
|
||||
$("workspace-add").addEventListener("click", () => addWorkspaceFolder($("workspace-path").value));
|
||||
$("workspace-path").addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Enter") return;
|
||||
e.preventDefault();
|
||||
addWorkspaceFolder(e.currentTarget.value);
|
||||
});
|
||||
$("workspace-browse").addEventListener("click", browseWorkspace);
|
||||
$("workspace-done").addEventListener("click", () => $("workspace-modal").close());
|
||||
$("workspace-modal").addEventListener("close", () => {
|
||||
wsConfirm = null;
|
||||
$("footer-where").focus();
|
||||
});
|
||||
// As on Help: the page-wide Ctrl/Cmd+Enter stands down while a dialog is open,
|
||||
// and this keeps the key inside the Workspace dialog as well.
|
||||
$("workspace-modal").addEventListener("keydown", (e) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}
|
||||
});
|
||||
// The workspace label opens the Workspace dialog; each folder's Copy path
|
||||
// lives in there now.
|
||||
$("footer-where").addEventListener("click", openWorkspace);
|
||||
}
|
||||
Reference in new issue
Block a user