Harden the shared console install, launcher, Loop staging, spec state and prompts

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-08 13:48:28 -08:00
1 parent 120c259d9c
commit 3ee96834bf
130 files changed
+5988 -1434

No files matched your search

+3
View File
@@ -700,6 +700,9 @@ export function cardAvailability(entry, scan, sel, lookup = stateFor) {
// Always on; a diagnosed bug is the one spec Quick Task is the next step for.
if (rule.states === "any") return next ? { ...ON, next } : ON;
// A building spec whose only unfinished tasks are blocked, each with a
// written reason (the scan's finalizeReady), is ready for Finalize too.
if (entry.skill === "plan2code-4-finalize" && state === "building" && sel.finalizeReady === true) return ON;
// A state the table does not know is treated like files on disk.
const taken = !sel || !sel.state ? "none" : lookup(sel.state) ? sel.state : "unrecognized";
if (rule.states.includes(taken)) return rule.marksNext ? { ...ON, next } : ON;
+8 -7
View File
@@ -1095,7 +1095,7 @@
it shuts itself down <span data-fact="closedTabMinutes">2</span> minutes
later. It also stops after <span data-fact="idleMinutes">30</span>
minutes without hearing from anyone, and after
<span data-fact="maxLifeHours">4</span> hours regardless. Reopening the same link brings everything back: nothing you
<span data-fact="maxLifeHours">4</span> hours unless answers you sent are still waiting for the agent. Reopening the same link brings everything back: nothing you
typed is kept in the browser alone.
</p>
<p class="for-app">
@@ -1103,7 +1103,7 @@
window and it shuts itself down <span data-fact="closedTabMinutes">2</span>
minutes later. It also stops after <span data-fact="idleMinutes">30</span>
minutes without hearing from anyone, and after
<span data-fact="maxLifeHours">4</span> hours regardless. When it
<span data-fact="maxLifeHours">4</span> hours unless answers you sent are still waiting for the agent. When it
stops, the app's own bar notices and brings it back on the same
session, or offers <strong>Reconnect the console</strong>: nothing you
typed is kept in the window alone.
@@ -1287,8 +1287,8 @@
from anyone, or
</li>
<li>
after <span data-fact="maxLifeHours">4</span> hours, whatever is
happening.
after <span data-fact="maxLifeHours">4</span> hours, unless answers
you sent are still waiting for the agent.
</li>
</ul>
<p id="help-stuck-reconnect-text">
@@ -3374,8 +3374,9 @@
<code>~/.plan2code</code> folder: sessions nobody has opened for
30 days, and files or folders that ended up there by mistake. It
also lists this project's <code>specs--completed/</code> folders
nobody has touched for 30 days; deleting one is permanent, since
that folder is usually gitignored and git can't restore it. It
nobody has touched for 30 days, and deletes one only when git
tracks it, so git can restore it; one git does not track (the
folder is usually gitignored) is kept, with the reason shown. It
shows each one with its size, and <strong>Delete these</strong>
removes exactly that list. Your preferences, saved folders, models,
the launcher and the session you are in always stay, and the
@@ -3641,7 +3642,7 @@
<section class="prefs-panel" data-tab="system">
<fieldset data-section="cleanup" class="modal-ranges">
<legend>Cleanup</legend>
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. It also lists this project's <code>specs--completed/</code> folders nobody has touched for 30 days; deleting one is permanent, since that folder is usually gitignored and git can't restore it. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. It also lists this project's <code>specs--completed/</code> folders nobody has touched for 30 days, and deletes one only when git tracks it, so git can restore it; one git does not track (the folder is usually gitignored) is kept, with the reason shown. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
<div class="models-actions">
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
+126 -61
View File
@@ -18,27 +18,44 @@
// editable surface, everything else on the host. field.el is the host div to
// append; host.field is the facade itself, so a page test or a helper can
// drive it.
import {
Compartment,
EditorState,
EditorView,
defaultKeymap,
history,
historyKeymap,
keymap,
markdown,
markdownLanguage,
placeholder,
redo,
} from "./vendor/codemirror.esm.js";
import { livePreview } from "./notepad-editor.js";
//
// CodeMirror (half a megabyte) is not part of the page's start: it is
// imported the first time a field is made, and every field after that gets
// its editor at once. A field made before the import lands keeps what is set
// on it (value, caret, disabled, aria-*, a focus asked for) and hands it to
// its editor when it arrives. destroy() ends the editor; renderMain() calls
// it, through destroyFields(), on every field it takes off the page.
// These listeners run as the editor's own DOM handlers, before its keymaps:
// a preventDefault there (the mention popover's keys, a pure-image paste)
// still beats CodeMirror's own handling.
const HANDLED = ["keydown", "keyup", "paste", "blur", "focus"];
// CodeMirror's exports plus the live preview, once loaded; the import itself
// while it is on its way. A failed import is forgotten, so the next field
// asks again.
let cm = null;
let loading = null;
function loadEditor() {
loading ??= Promise.all([import("./vendor/codemirror.esm.js"), import("./notepad-editor.js")]).then(
([lib, editor]) => (cm = { ...lib, livePreview: editor.livePreview }),
(err) => {
loading = null;
throw err;
}
);
return loading;
}
// Ends the editor of every Markdown field inside `root` (root included), for
// a caller about to drop that part of the page.
export function destroyFields(root) {
if (!root || typeof root.querySelectorAll !== "function") return;
if (root.field && typeof root.field.destroy === "function") root.field.destroy();
for (const host of root.querySelectorAll(".md-host")) if (host.field) host.field.destroy();
}
export function makeMdField({ id, className, value = "", placeholder: hint, label, disabled = false, maxLength = 0 } = {}) {
const host = document.createElement("div");
host.className = "md-host" + (className ? " " + className : "");
@@ -61,76 +78,110 @@ export function makeMdField({ id, className, value = "", placeholder: hint, labe
};
let off = Boolean(disabled);
const access = new Compartment();
// editable, not only readOnly: a disabled field cannot take the focus,
// which is the difference a textarea's own disabled attribute shows.
let view = null;
let gone = false;
// What the field holds until its editor arrives.
let text = String(value ?? "");
let sel = null;
let wantFocus = false;
const aria = new Map();
let access = null;
let stateOf = null;
const accessOf = (on) =>
on
? [
EditorState.readOnly.of(true),
EditorView.editable.of(false),
EditorView.contentAttributes.of({ "aria-disabled": "true" }),
cm.EditorState.readOnly.of(true),
cm.EditorView.editable.of(false),
cm.EditorView.contentAttributes.of({ "aria-disabled": "true" }),
]
: [];
const extensions = [
history(),
keymap.of([{ key: "Mod-Shift-z", run: redo, preventDefault: true }, ...defaultKeymap, ...historyKeymap]),
markdown({ base: markdownLanguage }),
livePreview,
EditorView.lineWrapping,
EditorView.contentAttributes.of({ "aria-label": label || "Markdown text", "aria-multiline": "true", spellcheck: "true" }),
EditorView.domEventHandlers(Object.fromEntries(HANDLED.map((type) => [type, (event) => fire(type, event)]))),
EditorView.updateListener.of((update) => {
if (update.docChanged) fire("input");
}),
...(hint ? [placeholder(hint)] : []),
...(maxLength
? [
EditorState.transactionFilter.of((tr) => {
if (!tr.docChanged || tr.newDoc.length <= maxLength) return tr;
return {
changes: { from: 0, to: tr.startState.doc.length, insert: tr.newDoc.sliceString(0, maxLength) },
selection: { anchor: Math.min(tr.newSelection.main.head, maxLength) },
};
}),
]
: []),
];
const stateOf = (text) => EditorState.create({ doc: text, extensions: [...extensions, access.of(accessOf(off))] });
const view = new EditorView({ state: stateOf(String(value ?? "")), parent: mount, root });
// The stylesheets arrive after the first measure: measure again once they
// have, or the lines would keep their unstyled height until the next edit.
for (const sheet of sheets) sheet.addEventListener("load", () => view.requestMeasure());
const build = () => {
const { Compartment, EditorState, EditorView, defaultKeymap, history, historyKeymap, keymap, markdown, markdownLanguage, placeholder, redo, livePreview } = cm;
access = new Compartment();
// editable, not only readOnly: a disabled field cannot take the focus,
// which is the difference a textarea's own disabled attribute shows.
const extensions = [
history(),
keymap.of([{ key: "Mod-Shift-z", run: redo, preventDefault: true }, ...defaultKeymap, ...historyKeymap]),
markdown({ base: markdownLanguage }),
livePreview,
EditorView.lineWrapping,
EditorView.contentAttributes.of({ "aria-label": label || "Markdown text", "aria-multiline": "true", spellcheck: "true" }),
EditorView.domEventHandlers(Object.fromEntries(HANDLED.map((type) => [type, (event) => fire(type, event)]))),
EditorView.updateListener.of((update) => {
if (update.docChanged) fire("input");
}),
...(hint ? [placeholder(hint)] : []),
...(maxLength
? [
EditorState.transactionFilter.of((tr) => {
if (!tr.docChanged || tr.newDoc.length <= maxLength) return tr;
return {
changes: { from: 0, to: tr.startState.doc.length, insert: tr.newDoc.sliceString(0, maxLength) },
selection: { anchor: Math.min(tr.newSelection.main.head, maxLength) },
};
}),
]
: []),
];
stateOf = (t) => EditorState.create({ doc: t, extensions: [...extensions, access.of(accessOf(off))] });
view = new EditorView({ state: stateOf(text), parent: mount, root });
// The stylesheets arrive after the first measure: measure again once they
// have, or the lines would keep their unstyled height until the next edit.
for (const sheet of sheets) sheet.addEventListener("load", () => view.requestMeasure());
if (sel) {
const end = view.state.doc.length;
view.dispatch({ selection: { anchor: Math.min(sel[0], end), head: Math.min(sel[1], end) } });
}
for (const [name, val] of aria) {
if (val == null) view.contentDOM.removeAttribute(name);
else view.contentDOM.setAttribute(name, val);
}
aria.clear();
if (wantFocus && host.isConnected) view.focus();
};
const field = {
el: host,
view,
get value() {
return view.state.doc.toString();
get view() {
return view;
},
set value(text) {
get value() {
return view ? view.state.doc.toString() : text;
},
set value(t) {
// setState neither reports a change nor keeps the undo steps, exactly
// the swap a textarea's value assignment makes. A fresh state parks its
// caret at 0; a textarea's collapses to the end, so callers that fill
// and focus (Autofill, quick answers, Reset to default) append as they
// used to.
view.setState(stateOf(String(text ?? "")));
if (!view) {
text = String(t ?? "");
sel = [text.length, text.length];
return;
}
view.setState(stateOf(String(t ?? "")));
view.dispatch({ selection: { anchor: view.state.doc.length } });
},
get selectionStart() {
if (!view) return sel ? Math.min(sel[0], sel[1]) : 0;
const m = view.state.selection.main;
return Math.min(m.anchor, m.head);
},
get selectionEnd() {
if (!view) return sel ? Math.max(sel[0], sel[1]) : 0;
const m = view.state.selection.main;
return Math.max(m.anchor, m.head);
},
setSelectionRange(a, b) {
view.dispatch({ selection: { anchor: a, head: b } });
if (!view) sel = [a, b ?? a];
else view.dispatch({ selection: { anchor: a, head: b } });
},
focus() {
view.focus();
if (view) view.focus();
else wantFocus = true;
},
get disabled() {
return off;
@@ -138,7 +189,7 @@ export function makeMdField({ id, className, value = "", placeholder: hint, labe
set disabled(on) {
off = Boolean(on);
host.classList.toggle("is-disabled", off);
view.dispatch({ effects: access.reconfigure(accessOf(off)) });
if (view) view.dispatch({ effects: access.reconfigure(accessOf(off)) });
},
get classList() {
return host.classList;
@@ -150,10 +201,14 @@ export function makeMdField({ id, className, value = "", placeholder: hint, labe
return host.getBoundingClientRect();
},
setAttribute(name, val) {
(name.startsWith("aria-") ? view.contentDOM : host).setAttribute(name, val);
if (!name.startsWith("aria-")) host.setAttribute(name, val);
else if (view) view.contentDOM.setAttribute(name, val);
else aria.set(name, String(val));
},
removeAttribute(name) {
(name.startsWith("aria-") ? view.contentDOM : host).removeAttribute(name);
if (!name.startsWith("aria-")) host.removeAttribute(name);
else if (view) view.contentDOM.removeAttribute(name);
else aria.set(name, null);
},
addEventListener(type, fn) {
if (!listeners.has(type)) listeners.set(type, new Set());
@@ -172,11 +227,21 @@ export function makeMdField({ id, className, value = "", placeholder: hint, labe
fire("input");
},
destroy() {
if (gone) return;
gone = true;
listeners.clear();
view.destroy();
if (view) view.destroy();
},
};
if (off) host.classList.add("is-disabled");
host.field = field;
if (cm) build();
else
loadEditor().then(
() => {
if (!gone) build();
},
() => {}
);
return field;
}
+34 -1
View File
@@ -305,13 +305,46 @@ function blockInto(parent, tokens) {
}
}
// The token trees of recent md() sources, newest last, so a redraw that draws
// the same Markdown again (every agent post redraws every card) skips the
// lexer. Only the tokens are kept, never the DOM: md() still builds fresh
// nodes with their own listeners each call, so a caller may change what it
// gets back. Bounded by count and by total source length; a source over the
// length cap on its own is never kept.
const MD_CACHE_ENTRIES = 200;
const MD_CACHE_CHARS = 2_000_000;
const mdCache = new Map();
let mdCacheChars = 0;
function lexed(text) {
const hit = mdCache.get(text);
if (hit) {
mdCache.delete(text);
mdCache.set(text, hit);
// A copy: drawing takes a task marker off its token (takeMarker), and the
// kept tree must stay as the lexer made it.
return structuredClone(hit);
}
const tokens = marked.lexer(text);
if (text.length <= MD_CACHE_CHARS) {
mdCache.set(text, structuredClone(tokens));
mdCacheChars += text.length;
for (const [key] of mdCache) {
if (mdCache.size <= MD_CACHE_ENTRIES && mdCacheChars <= MD_CACHE_CHARS) break;
mdCache.delete(key);
mdCacheChars -= key.length;
}
}
return tokens;
}
/** Render markdown into a fresh element. Returns the element. */
export function md(source, className = "md", options = {}) {
const host = el("div", className);
if (!source) return host;
let tokens;
try {
tokens = marked.lexer(String(source));
tokens = lexed(String(source));
} catch {
host.appendChild(el("p", "md-p", String(source)));
return host;
+89 -20
View File
@@ -8,7 +8,7 @@ import { startersFor } from "../starters.js";
import { looks } from "../looks.js";
import { thumbs, uploadUrl, docChip, attachTray, CHAT_IMAGES, attachFiles, incomingFiles, deleteUrl, sentAttachments, noteImages, attachRow, openPicview, refocusThumb } from "../uploads.js";
import { attachMentions } from "../mention-box.js";
import { makeMdField } from "../md-field.js";
import { destroyFields, makeMdField } from "../md-field.js";
import { pickerAccept, attachmentKind, noteAwaiting, threadWho, threadText } from "../answers.js";
import { postJson } from "../net.js";
import { reconnectOffer } from "../continue-button.js";
@@ -29,10 +29,19 @@ export const declineOpen = new Map();
const deciding = new Set();
// The Subagents dialog's instruction box, a Markdown field made once in
// wireAsk into its #subagents-instruction mount.
// The Subagents dialog's instruction box, a Markdown field made the first
// time the dialog needs it, into its #subagents-instruction mount: made at
// start-up, it would pull CodeMirror into every page load (md-field.js).
let instrField = null;
function instr() {
if (!instrField) {
instrField = makeMdField({ className: "subagents-instruction", label: "Instruction", maxLength: 2000 });
$("subagents-instruction").appendChild(instrField.el);
}
return instrField;
}
// 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.
@@ -66,7 +75,7 @@ export function askState() {
// 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) {
export function renderAsk(main, held = null) {
const { frame, view: v, send: ss } = askState();
// Anything drawn here has been seen: no dot for it later.
const newest = newestReplyId(frame);
@@ -77,7 +86,6 @@ export function renderAsk(main) {
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));
@@ -86,17 +94,42 @@ export function renderAsk(main) {
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));
// The list is a live region (role="log"): one taken up from the last render
// keeps every row that would draw the same, so a redraw announces nothing
// and a new message is one appended row, the only thing read out.
const kept = held && held.querySelector(":scope > .ask-list");
const list = kept || el("div", "ask-list");
if (!kept) {
list.setAttribute("role", "log");
list.setAttribute("aria-live", "polite");
}
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);
const wanted = v.rows.length
? v.rows.map((r) => [askRowKey(r, ss, notes), () => askRow(r, ss, notes)])
: [[askStartersKey(ss), () => askStarters(ss)]];
syncRows(list, wanted);
const composer = askComposer(ss);
if (kept) {
const oldHead = held.querySelector(":scope > .ask-head");
const oldComposer = held.querySelector(":scope > .ask-composer");
if (oldHead) oldHead.replaceWith(head);
else held.insertBefore(head, list);
if (oldComposer) {
destroyFields(oldComposer);
oldComposer.replaceWith(composer);
} else held.appendChild(composer);
if (held.parentNode !== main) main.appendChild(held);
} else {
if (held) {
destroyFields(held);
held.remove();
}
const pane = el("section", "ask-pane");
pane.append(head, list, composer);
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.
@@ -106,6 +139,44 @@ export function renderAsk(main) {
list.scrollTop = !saved || grew ? list.scrollHeight : saved.top;
}
// What a row draws from: the row itself and every outside fact askRow() reads,
// so two equal keys draw the same row and the one on the page can stay.
// Each outside fact counts only on the rows that read it, or a send in flight
// (chatSending) would redraw every row in the log.
function askRowKey(r, ss, notes) {
const offline = ss.state === "offline";
if (r.kind === "decision") return JSON.stringify([r]);
if (r.kind === "agent") {
const open = Boolean(r.proposal && !r.decided);
return JSON.stringify([r, notes.get(r.id) ?? null, open && [offline, deciding.has(r.id), declineOpen.has(r.id)]]);
}
return JSON.stringify([
r,
r.pending && r.failed ? [offline, chatSending] : null,
!r.pending && r.waiting && r.working ? [offline, agentAdrift()] : null,
(r.images || []).map((img) => thumbs.get(img.key) || ""),
]);
}
const askStartersKey = (ss) =>
JSON.stringify(["starters", ss.canType, page.S.workflow, looks.role, Boolean(page.local.chat.about)]);
// Brings the live list's children in line with `wanted` ([key, make] pairs,
// in order): a child whose key matches stays untouched, a changed one is
// redrawn in its place, new ones are appended and leftovers removed.
function syncRows(list, wanted) {
const have = [...list.children];
wanted.forEach(([key, make], i) => {
const cur = have[i];
if (cur && cur.dataset.rowKey === key) return;
const node = make();
node.dataset.rowKey = key;
if (cur) cur.replaceWith(node);
else list.appendChild(node);
});
for (const extra of have.slice(wanted.length)) extra.remove();
}
// 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) {
@@ -867,7 +938,7 @@ export function openSubagents() {
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) {
radio.checked = radio.value === (on ? "on" : "off");
}
instrField.value = page.subagentsFrame.instruction ?? defaultInstruction(page.S.workflow);
instr().value = page.subagentsFrame.instruction ?? defaultInstruction(page.S.workflow);
$("subagents-max").value = String(page.subagentsFrame.max);
const strength = STRENGTHS.includes(page.subagentsFrame.strength) ? page.subagentsFrame.strength : DEFAULT_STRENGTH;
for (const radio of document.querySelectorAll('input[name="subagents-strength"]')) radio.checked = radio.value === strength;
@@ -889,7 +960,7 @@ export function openSubagents() {
export function syncSubagentsFields() {
const picked = document.querySelector('input[name="subagents-on"]:checked');
const off = !picked || picked.value !== "on";
instrField.disabled = off;
instr().disabled = off;
for (const id of ["subagents-max", "subagents-default"]) $(id).disabled = off;
for (const radio of document.querySelectorAll('input[name="subagents-strength"]')) radio.disabled = off;
}
@@ -914,7 +985,7 @@ export async function saveSubagents() {
const save = $("subagents-save");
const status = $("subagents-status");
const picked = document.querySelector('input[name="subagents-on"]:checked');
const text = instrField.value.trim();
const text = instr().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;
@@ -942,14 +1013,12 @@ export const askOfflineFlipped = () => (askState().send.state === "offline") !==
// The Subagents dialog's buttons, and dropping files onto the notes panel.
export function wireAsk() {
instrField = makeMdField({ className: "subagents-instruction", label: "Instruction", maxLength: 2000 });
$("subagents-instruction").appendChild(instrField.el);
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) radio.addEventListener("change", syncSubagentsFields);
for (const radio of document.querySelectorAll('input[name="subagents-strength"]')) radio.addEventListener("change", syncStrengthHelp);
lightDismiss($("subagents-modal"));
$("btn-subagents").addEventListener("click", openSubagents);
$("subagents-default").addEventListener("click", () => {
instrField.value = defaultInstruction(page.S.workflow);
instr().value = defaultInstruction(page.S.workflow);
});
$("subagents-save").addEventListener("click", saveSubagents);
$("subagents-cancel").addEventListener("click", () => $("subagents-modal").close());
+30 -4
View File
@@ -880,6 +880,23 @@ function buildChoice(card, item, staged) {
clearRow(card, item);
}
// A small eraser-style mark: a cross in a circle, drawn inline so it takes the
// button's text color in both themes. Hidden from readers; the aria-label names it.
function clearIcon() {
const ns = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(ns, "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("width", "14");
svg.setAttribute("height", "14");
svg.setAttribute("aria-hidden", "true");
for (const d of ["M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z", "M9 9l6 6M15 9l-6 6"]) {
const path = document.createElementNS(ns, "path");
path.setAttribute("d", d);
svg.appendChild(path);
}
return svg;
}
// Takes a one-answer question back to how it arrived: no pick, and nothing in
// "Something else" (its draft too, or the render would put the words straight
// back). A radio group cannot be unticked by clicking it again, so without
@@ -887,8 +904,10 @@ function buildChoice(card, item, staged) {
// call it, and they only run for a form that has not been sent.
function clearRow(card, item) {
const row = el("div", "btn-row options-clear");
const b = el("button", "btn small ghost", "Clear");
const b = el("button", "btn small ghost clear-btn");
b.type = "button";
b.appendChild(clearIcon());
b.appendChild(el("span", null, "Clear answer"));
// An id so focus survives the render the click sets off (see withFocus).
b.id = "clear-" + item.id;
b.setAttribute("aria-label", "Clear your answer to this question");
@@ -1307,9 +1326,16 @@ function buildReview(card, item, staged) {
verdictText(v)
);
b.type = "button";
b.addEventListener("click", () =>
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "review", verdict: v.id }))
);
// A toggle: a screen reader hears which verdict is picked, not only sees
// it in the fill. Set on the row at once, ahead of the redraw the stage
// sets off, so the state never lags the click.
b.setAttribute("aria-pressed", String(Boolean(on)));
b.addEventListener("click", () => {
for (const other of row.querySelectorAll("button[aria-pressed]")) {
other.setAttribute("aria-pressed", String(other === b && !on));
}
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "review", verdict: v.id }));
});
row.appendChild(b);
}
card.appendChild(row);
+35 -14
View File
@@ -46,6 +46,12 @@ function cleanupSummary(items, bytes) {
return parts.join(", ") + " · " + formatBytes(bytes);
}
// A completed spec git does not track as it stands is never deleted (the
// server refuses it), so it is listed apart as kept, out of the total and out
// of what Delete these sends.
const keptBack = (item) => item.where === "completed" && item.tracked === false;
const deletable = () => ((cleanupFound && cleanupFound.items) || []).filter((i) => !keptBack(i));
function resetCleanup() {
cleanupGen++;
cleanupFound = null;
@@ -59,19 +65,28 @@ function resetCleanup() {
function renderCleanup() {
const list = $("cleanup-list");
list.replaceChildren();
const items = (cleanupFound && cleanupFound.items) || [];
const all = (cleanupFound && cleanupFound.items) || [];
const items = deletable();
const kept = all.filter(keptBack);
$("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);
if (items.length) {
const bytes = Math.max(0, cleanupFound.bytes - kept.reduce((n, i) => n + (i.bytes || 0), 0));
list.append(el("p", "cleanup-summary", cleanupSummary(items, 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);
}
}
for (const item of kept) {
const row = el("div", "cleanup-row cleanup-kept");
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", "kept: git does not track it as it stands"));
list.appendChild(row);
}
}
@@ -93,17 +108,20 @@ async function scanCleanup() {
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);
const found = deletable().length;
const keptCount = cleanupFound.items.length - found;
const keptNote = keptCount ? ` ${keptCount} old completed ${keptCount === 1 ? "spec is" : "specs are"} kept: git does not track ${keptCount === 1 ? "it" : "them"} as ${keptCount === 1 ? "it stands" : "they stand"}.` : "";
setCleanupStatus((found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.") + keptNote, false);
}
async function deleteCleanup() {
if (!cleanupFound || !cleanupFound.items.length) return;
const ids = deletable().map((i) => i.id);
if (!ids.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) });
const { status, body } = await postJson("/cleanup", { delete: ids });
if (gen !== cleanupGen) return;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
@@ -112,15 +130,18 @@ async function deleteCleanup() {
}
const removed = (body.removed || []).length;
const failed = (body.failed || []).length;
// A completed spec git does not track is refused, and the server says why.
const refused = (body.refused || []).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);
const asked = ids.length;
const kept = Math.max(0, asked - removed - failed - refused);
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));
const refusalLine = refused && body.refusal ? " " + body.refusal : "";
setCleanupStatus((failed ? done + " " + failed + " could not be removed." : done) + keptLine + refusalLine, Boolean(failed || refused));
}
// The Cleanup section's buttons, and starting over whenever Preferences closes.
+36 -12
View File
@@ -65,6 +65,7 @@ import { renderLoopSetup } from "./loop-setup.js";
import { renderLaunching, renderWaiting } from "./starting.js";
import { attachFiles, heldNotes, noteImages, pendingNotes, removeImage } from "../uploads.js";
import { closeMentions } from "../mention-box.js";
import { destroyFields } from "../md-field.js";
import { buildPager, fitGrowBox, markFor, markMore, renderCard, renderEndItem, renderNotice } from "./cards.js";
import { sendState, suggestState } from "../send-state.js";
import { renderAgentsDoc, renderBriefButton, renderDoc, renderOverview } from "./docs.js";
@@ -1608,16 +1609,31 @@ export function renderSidebar() {
}
}
// The Ask pane on screen when a render of the Ask tab began, held back from
// the clear like the pose pane, so renderAsk() can take it up again: its list
// is a live region, and a list rebuilt on every redraw would be announced
// over and over instead of only its new rows.
let heldAsk = null;
// Takes `node` off the page, ending the editor of every Markdown field in it.
function discard(node) {
destroyFields(node);
node.remove();
}
function renderMain() {
const main = $("main");
page.heldPose = main.querySelector(":scope > [data-pose]");
for (const child of [...main.children]) if (child !== page.heldPose) child.remove();
heldAsk = page.view === "ask" ? main.querySelector(":scope > .ask-pane") : null;
for (const child of [...main.children]) if (child !== page.heldPose && child !== heldAsk) discard(child);
try {
paintMain(main);
} finally {
// Nothing took it up: this screen is not the same pose.
page.heldPose?.remove();
if (page.heldPose) discard(page.heldPose);
page.heldPose = null;
if (heldAsk) discard(heldAsk);
heldAsk = null;
}
// Inside the render pass, before withFocus restores the card's scroll, so
// the restore is measured against the box's final height.
@@ -1636,7 +1652,11 @@ function paintMain(main) {
if (page.view.startsWith("doc:")) return renderDoc(main, page.view.slice(4));
if (isSpecFileView(page.view)) return renderOverview(main, page.view);
if (page.view === AGENTS_VIEW) return renderAgentsDoc(main);
if (page.view === "ask") return renderAsk(main);
if (page.view === "ask") {
const held = heldAsk;
heldAsk = null;
return renderAsk(main, held);
}
if (page.view === "subagents") return renderSubagents(main);
// The session's own page, reached from the PAUSED / SESSION ENDED item at
@@ -1771,20 +1791,23 @@ export function renderFooter() {
const summary = $("footer-summary");
const notes = pendingNotes();
const n = stagedCount();
summary.replaceChildren();
// Built off the page and swapped in only when it reads differently: the
// summary is a live region and the footer renders on every tick, so a
// rewrite with the same words would be announced again each time.
const next = document.createElement("div");
const sent = awaitingReply();
if (!n && !notes.length && sent.length) {
// "Answer a question above" is nonsense when everything answerable has
// already gone. Say what is actually outstanding instead: their own send.
summary.appendChild(el("strong", null, stranded() ? `${sent.length} saved, not picked up yet` : `${sent.length} with Plan2Code`));
summary.appendChild(document.createTextNode(" · " + sent.map((i) => i.title).join(" · ")));
next.appendChild(el("strong", null, stranded() ? `${sent.length} saved, not picked up yet` : `${sent.length} with Plan2Code`));
next.appendChild(document.createTextNode(" · " + sent.map((i) => i.title).join(" · ")));
} else if (finish()) {
// Not "nothing to send yet". There is no yet.
const fin = finish();
summary.appendChild(el("strong", null, finishPaused(fin) ? "Paused." : "All done."));
summary.appendChild(
next.appendChild(el("strong", null, finishPaused(fin) ? "Paused." : "All done."));
next.appendChild(
document.createTextNode(
n || notes.length
? " Anything still waiting here was never sent."
@@ -1796,7 +1819,7 @@ export function renderFooter() {
)
);
} else if (!n && !notes.length) {
summary.appendChild(
next.appendChild(
document.createTextNode(
myTurn().length
? "Nothing to send yet. Answer a question above, then press Send."
@@ -1805,7 +1828,7 @@ export function renderFooter() {
);
} else {
const strong = el("strong", null, `${n + notes.length} ready`);
summary.appendChild(strong);
next.appendChild(strong);
const bits = [];
for (const [id, v] of Object.entries(page.local.staged)) {
const item = byId(id);
@@ -1819,12 +1842,12 @@ export function renderFooter() {
const item = byId(note.id);
bits.push(`note on ${item ? item.title : "a question"}`);
}
summary.appendChild(document.createTextNode(" · " + bits.join(" · ")));
next.appendChild(document.createTextNode(" · " + bits.join(" · ")));
}
const held = finish() ? 0 : heldNotes().length;
if (held) {
summary.appendChild(
next.appendChild(
el(
"div",
"footer-held",
@@ -1834,6 +1857,7 @@ export function renderFooter() {
)
);
}
if (summary.innerHTML !== next.innerHTML) summary.replaceChildren(...next.childNodes);
const state = sendState();
const btn = $("btn-send");
+11 -2
View File
@@ -6,7 +6,8 @@
background: var(--panel);
border: 1px solid var(--rule);
border-radius: var(--radius);
padding: 24px 26px;
--card-pad-b: 24px;
padding: 24px 26px var(--card-pad-b);
max-width: min(var(--card-width), 100%);
box-shadow: var(--shadow);
margin: 0 auto 18px;
@@ -74,7 +75,15 @@
/* ------------------------------------------------------------ options */
.options { list-style: none; margin: 20px 0 0; padding: 0; display: grid; gap: 9px; }
.options-clear { margin-top: 10px; }
/* Pinned to the foot of the card's scroll area, so a question taller than the
window keeps its Clear in reach; it settles under the options at the end. */
.options-clear {
position: sticky; bottom: calc(var(--card-pad-b) * -1); z-index: 1;
margin: 10px 0 calc(var(--card-pad-b) * -1); padding: 8px 0 var(--card-pad-b);
background: linear-gradient(to bottom, transparent, var(--panel) 8px);
}
.clear-btn { display: inline-flex; align-items: center; gap: 6px; }
.clear-btn svg { flex: none; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.option {
display: flex;
+1 -1
View File
@@ -30,7 +30,7 @@
.rail { border-right: 0; border-bottom: 1px solid var(--rule); }
.sidebar, .aside { border: 0; border-bottom: 1px solid var(--rule); max-height: 30vh; }
.main { padding: 18px 16px 30px; }
.card { padding: 18px 16px; border-radius: 8px; }
.card { --card-pad-b: 18px; padding: 18px 16px var(--card-pad-b); border-radius: 8px; }
.main > .card { padding-right: 22px; }
.card h2 { font-size: 21px; }
/* Back to a wrapping row: the summary and Send take two lines here and fill
+2 -1
View File
@@ -10,7 +10,8 @@
--panel-2: #fbf9f6;
--ink: #1d1a17;
--ink-2: #5d564d;
--ink-3: #8f8779;
/* Same hue as before, darkened to 4.56:1 on --bg (WCAG AA for body text). */
--ink-3: #756e62;
--rule: #e4ddd1;
--rule-2: #cfc6b6;
--accent: #206cc3;