Add the Review Loop: unattended review-and-fix rounds in the desktop app and in loop phases

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-28 21:09:02 -08:00
1 parent d6a28b5dc8
commit 57567d7a0b
71 files changed
+11331 -443

No files matched your search

+12 -2
View File
@@ -68,6 +68,7 @@ import {
import { sound } from "../sound.js";
import { renderConfirm, renderDashboard } from "./dashboard.js";
import { renderLoopSetup } from "./loop-setup.js";
import { renderReviewLoopSetup } from "./review-loop-setup.js";
import { renderLaunching, renderWaiting } from "./starting.js";
import { attachFiles, findSetAside, heldNotes, noteImages, pendingNotes, purgeImages } from "../uploads.js";
import { closeMentions } from "../mention-box.js";
@@ -82,6 +83,7 @@ import { framed, linkLeavesPage, onAppMessage, shortcutIdFor, startNewSession, t
import { openPrefs as openPrefsDialog } from "./prefs-dialog.js";
import { continueButton } from "../continue-button.js";
import { askOfflineFlipped, askState, declineOpen, renderAside, renderAsk, renderSubagents, renderSubagentsButton } from "./ask.js";
import { forgetReviewEnd } from "../review-loop-end.js";
import { renderHandoff, renderLoopEnd, renderHomeButton, renderStopButton, renderStopControls, renderStopping, renderFooterDashboard, stopInProgress, stopWarning } from "./ending.js";
import { renderNotepadButton } from "./notepad.js";
import { renderActivities } from "./activities.js";
@@ -107,6 +109,7 @@ export { wireEnding } from "./ending.js";
export { wireNotepad } from "./notepad.js";
export { wireActivities } from "./activities.js";
export { openLoopSetup, wireLoopSetup } from "./loop-setup.js";
export { openReviewLoopSetup } from "./review-loop-setup.js";
const $ = (id) => document.getElementById(id);
@@ -450,6 +453,7 @@ export function adopt(body) {
if (!isDashboard() || finish()) {
page.dashPick = null;
page.loopSetup = null;
page.reviewLoopSetup = null;
}
// A launch (or an ending) mid wake-up: cut it short rather than play on
// over a page that is no longer the menu.
@@ -1419,6 +1423,9 @@ export function renderStatus() {
// still has presses on offer the move is theirs; with none, it is done.
if (page.S.loopEnd) {
const end = page.S.loopEnd;
if (end.kind === "review") {
return end.signedOff ? say("point", "Signed off. Pick what happens next.") : say("point", "The Review Loop ended. Sign off when you are ready.");
}
const moves = Array.isArray(end.can) ? end.can.length : 0;
if (!moves) return say("done", "The loop is done.");
return say(
@@ -1805,6 +1812,7 @@ function paintMain(main) {
if (isDashboard() && !finish()) {
if (page.local.launching) renderLaunching(main);
else if (page.loopSetup) renderLoopSetup(main);
else if (page.reviewLoopSetup) renderReviewLoopSetup(main);
else if (page.dashPick) {
// A spec-switch under an open confirm can gray the pick out. Rather
// than offer START on a card that cannot launch, drop back to the
@@ -1816,7 +1824,7 @@ function paintMain(main) {
}
} else renderDashboard(main);
// Review from the Learning banner: the lessons card, over the menu.
renderLessonsDialog(!page.local.launching && !page.loopSetup && !page.dashPick);
renderLessonsDialog(!page.local.launching && !page.loopSetup && !page.reviewLoopSetup && !page.dashPick);
return;
}
renderLessonsDialog(false);
@@ -1849,6 +1857,7 @@ function paintMain(main) {
// How the Implementation Loop ended, from the app's `loopEnd`: its own
// screen, ahead of any card the last phase left behind.
if (!page.S.loopEnd) forgetReviewEnd();
if (page.S.loopEnd && !finish()) {
const card = renderLoopEnd(page.S.loopEnd);
card.classList.add("is-primary");
@@ -2601,9 +2610,10 @@ export function wireChrome() {
// Escape is the confirm pane's Back — but not while a dialog has it. Native
// dialogs close themselves on the same key; backing out of the pick at the
// same time would be two undos for one press.
if (e.key === "Escape" && (page.dashPick || page.loopSetup) && isDashboard() && !finish() && !document.querySelector("dialog[open]")) {
if (e.key === "Escape" && (page.dashPick || page.loopSetup || page.reviewLoopSetup) && isDashboard() && !finish() && !document.querySelector("dialog[open]")) {
page.dashPick = null;
page.loopSetup = null;
page.reviewLoopSetup = null;
redraw();
}
});
+21 -11
View File
@@ -30,6 +30,7 @@ import {
SKILL_CATALOG,
catalogEntry,
LOOP_ENTRY,
APP_ONLY_ENTRIES,
OUTSIDE_APP_LINE,
launchVariant,
SPEC_STATE_LABELS,
@@ -296,16 +297,17 @@ export function renderDashboard(main) {
let shown = 0;
for (const g of CATALOG_GROUPS) {
const entries = SKILL_CATALOG.filter((e) => e.group === g.id && (!hide || available(e)));
// The desktop app's Implementation Loop card closes its group. Outside the
// app it is always drawn, grayed, so the feature can be found.
const loopCard = LOOP_ENTRY && LOOP_ENTRY.group === g.id && (!page.inApp || !hide || available(LOOP_ENTRY));
if (!entries.length && !loopCard) continue;
shown += entries.length + (loopCard ? 1 : 0);
// The desktop app's Implementation Loop and Review Loop cards close their
// group. Outside the app they are always drawn, grayed, so the features can
// be found.
const loopCards = APP_ONLY_ENTRIES.filter((e) => e.group === g.id && (!page.inApp || !hide || available(e)));
if (!entries.length && !loopCards.length) continue;
shown += entries.length + loopCards.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));
if (loopCard) grid.appendChild(dashCard(LOOP_ENTRY, menu));
for (const e of loopCards) grid.appendChild(dashCard(e, menu));
section.appendChild(grid);
wrap.appendChild(section);
}
@@ -752,6 +754,8 @@ async function readHandoff(h) {
}
}
const REVIEW_LOOP_SKILL = "plan2code-review-loop";
function dashCard(entry, menu) {
const presentation = entry.appOnly ? loopPresentation(entry, menu) : cardPresentation(entry, scan(), selSpec(), menu);
// The agent's `recommend` and detail describe the initially selected spec.
@@ -784,6 +788,8 @@ function dashCard(entry, menu) {
title.appendChild(document.createTextNode(entry.title));
b.appendChild(title);
b.appendChild(el("span", "dash-card-blurb", entry.blurb));
// A line only the desktop app shows (the Review card's pointer to the Review Loop).
if (entry.appNote && page.inApp) b.appendChild(el("span", "dash-card-detail", entry.appNote));
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));
@@ -793,8 +799,8 @@ function dashCard(entry, menu) {
b.appendChild(foot);
b.addEventListener("click", () => {
// The loop card opens its own setup screen instead of a confirm pane.
if (entry.appOnly) return hooks.openLoopSetup(selSpec());
// A loop card opens its own setup screen instead of a confirm pane.
if (entry.appOnly) return entry.skill === REVIEW_LOOP_SKILL ? hooks.openReviewLoopSetup(selSpec()) : hooks.openLoopSetup(selSpec());
page.dashPick = entry;
redraw();
});
@@ -803,7 +809,7 @@ function dashCard(entry, menu) {
if (entry.appOnly) {
const wrap = el("div", "dash-card-wrap");
wrap.appendChild(b);
wrap.appendChild(loopHelpLink());
wrap.appendChild(loopHelpLink(entry));
return wrap;
}
return b;
@@ -814,13 +820,17 @@ function dashCard(entry, menu) {
// pre-selected: a person opts into running unattended.
function loopPresentation(entry, menu) {
if (!page.inApp) return { on: false, reason: OUTSIDE_APP_LINE, recommended: false, detail: "" };
if (entry.skill === REVIEW_LOOP_SKILL && loopDriving()) {
return { on: false, reason: "A loop is running. Stop it from the banner at the top of the window first.", recommended: false, detail: "" };
}
return { ...cardPresentation(entry, scan(), selSpec(), menu), recommended: false };
}
// "How the loop works" under the card: a real button styled as a link, a
// sibling of the card button inside its wrapper.
function loopHelpLink() {
const a = el("button", "dash-card-link", "How the loop works");
function loopHelpLink(entry) {
const review = entry && entry.skill === REVIEW_LOOP_SKILL;
const a = el("button", "dash-card-link", review ? "How the Review Loop works" : "How the loop works");
a.type = "button";
a.addEventListener("click", () => hooks.openHelpOn("loop"));
return a;
+2
View File
@@ -55,6 +55,7 @@ const LOOP_LOCK_TITLE = "The loop is building. Stop it from the banner at the to
import { docSavedNote, downloadDoc } from "../doc-files.js";
import { startNewSession, tellApp } from "../app-bridge.js";
import { pendingNotes } from "../uploads.js";
import { renderReviewLoopEnd } from "../review-loop-end.js";
// The end of the session, and the only screen in this page whose job is to
// send someone somewhere else.
@@ -239,6 +240,7 @@ function loopEndKey(end) {
* its agent made; the report behind the button holds them all).
*/
export function renderLoopEnd(end) {
if (end.kind === "review") return renderReviewLoopEnd(end);
const card = el("article", "card handoff loop-end");
const finished = end.kind === "finished";
card.appendChild(el("p", "card-kicker", finished ? "Loop finished" : "Loop stopped"));
@@ -272,6 +272,8 @@ function buildHelp() {
}
li.appendChild(strong);
li.appendChild(document.createTextNode(" " + (e.help || e.blurb)));
// The app-only pointer (Review's line about the Review Loop), shown in the app.
if (e.appNote && page.inApp) li.appendChild(el("span", "help-app-note", " " + e.appNote));
list.appendChild(li);
}
cards.append(head, list);
+30 -230
View File
@@ -11,6 +11,7 @@ import { hooks, page, redraw, saveNow } from "../state.js";
import { SKILL_CATALOG } from "../answers.js";
import { postJson } from "../net.js";
import { tellApp, wireLoopMessages } from "../app-bridge.js";
import { DEFAULT_NOTIFY_PARAM, MATCH_SESSION, NOTIFY_KINDS, STRENGTH_WORDS, field, hasMapping, notifyFields, notifyProblem, radios, select, silenceField, toggle } from "../loop-parts.js";
let justPicked = ""; // the strength node picked a moment ago, which alone plays its grow
// Suggest for me was pressed and has just come back (answer, time-out or failed
@@ -34,26 +35,9 @@ const AFTER_LAST = [
["run-finalize", "Run Finalize automatically", "Finalize starts by itself once every phase is built."],
];
const STRENGTH_WORDS = [
["thrifty", "Thrifty"],
["balanced", "Balanced"],
["best", "Best"],
];
const MATCH_SESSION = "Match my session";
// How long Suggest for me waits on the dashboard agent before it gives the field back.
export const SUGGEST_WAIT_MS = 120000;
const DEFAULT_NOTIFY_PARAM = "message";
// What the setup can send a notification to. `name` is the label for the field
// the person names, on the kinds that have one.
const NOTIFY_KINDS = [
{ id: "query", label: "A web address, with the message in its query string", placeholder: "https://example.com/hook", hint: "The app calls this address with a GET.", name: "Query string name for the message" },
{ id: "discord", label: "Discord webhook", placeholder: "https://discord.com/api/webhooks/...", hint: "In Discord: Edit Channel, Integrations, Webhooks, then Copy Webhook URL." },
{ id: "slack", label: "Slack webhook", placeholder: "https://hooks.slack.com/services/...", hint: "An Incoming Webhook URL from your Slack app's settings." },
{ id: "teams", label: "Microsoft Teams webhook", placeholder: "https://...", hint: 'In Teams: Workflows, the template "Post to a channel when a webhook request is received", then copy its URL.' },
{ id: "google-chat", label: "Google Chat webhook", placeholder: "https://chat.googleapis.com/v1/spaces/...", hint: "In the space: Apps & integrations, Webhooks, then copy the URL." },
{ id: "json", label: "A web address, with the message in a JSON body", placeholder: "https://example.com/hook", hint: "The app sends a POST with a JSON object holding the message, for any other service.", name: "JSON field name for the message" },
];
const SMART_DETAIL = "A fresh agent reads the review's findings and fixes the ones worth fixing. A skipped Critical stops the phase.";
/** Called by the page's start-up: hear the app's answers to the loop's requests. */
@@ -97,6 +81,7 @@ export async function openLoopSetup(spec) {
const { phasesLeft, branch, pending, suggestedQuickCheck, remembered, saved, picks, resolved, ...setup } = answer;
mine.form = {
review: setup.review !== false,
reviewRounds: Number.isInteger(setup.reviewRounds) && setup.reviewRounds >= 0 && setup.reviewRounds <= 6 ? setup.reviewRounds : 2,
fixMode: setup.fixMode === "levels" ? "levels" : "smart",
fix: Array.isArray(setup.fix) ? [...setup.fix] : LEVELS.map(([k]) => k),
commit: setup.commit !== false,
@@ -154,8 +139,6 @@ function ensureResolved(s) {
});
}
const hasMapping = (resolved) => Boolean(resolved) && Object.keys(resolved).length > 0;
/** This spec's saved word for a phase, or "" for Match my session. */
function pickOf(form, spec, phase) {
const list = form.strengths && form.strengths[spec];
@@ -220,87 +203,6 @@ export function startBlock(form, facts, appFacts) {
return "";
}
/**
* What is wrong with the web address fields as typed, or "". The server checks
* again on save; this is the line that shows while typing.
*/
export function notifyProblem(url, param, kind = "query") {
const address = url.trim();
if (!address) return "";
if (!/^https?:\/\//i.test(address)) return "The web address must start with http:// or https://.";
let good = /^https?:\/\/[^/?#@]+([/?#][!-~]*)?$/i.test(address) && !/[^!-~]/.test(address);
if (good) {
try {
good = Boolean(new URL(address).hostname);
} catch {
good = false;
}
}
if (!good) return "That is not a web address the app can call. Leave out any user name or password, and percent-encode spaces and accents.";
const named = NOTIFY_KINDS.some((k) => k.id === kind && k.name);
if (named && !/^[A-Za-z0-9._~-]{1,64}$/.test(param.trim() || DEFAULT_NOTIFY_PARAM)) return "The name can only use letters, digits, and - _ . ~";
return "";
}
/**
* The chat service a pasted address belongs to, or "". A webhook needs a POST:
* a GET to a Discord webhook answers 200 and posts nothing, so staying on the
* query string kind would look like it worked.
*/
export function kindForUrl(url) {
let parsed;
try {
parsed = new URL(url.trim());
} catch {
return "";
}
const host = parsed.hostname.toLowerCase();
const under = (domain) => host === domain || host.endsWith(`.${domain}`);
if ((under("discord.com") || under("discordapp.com")) && parsed.pathname.startsWith("/api/webhooks/")) return "discord";
if (host === "hooks.slack.com") return "slack";
if (host === "chat.googleapis.com") return "google-chat";
if (under("logic.azure.com") || under("powerplatform.com") || under("powerautomate.com")) return "teams";
return "";
}
function field(label, hint) {
const box = el("div", "loop-field");
box.appendChild(el("p", "loop-label", label));
if (hint) box.appendChild(el("p", "loop-hint", hint));
return box;
}
function toggle(id, text, checked, onChange) {
const label = el("label", "loop-switch");
const input = el("input");
input.type = "checkbox";
input.id = id;
input.checked = checked;
input.addEventListener("change", () => onChange(input.checked));
label.append(input, el("span", null, text));
return label;
}
function radios(name, options, current, onChange) {
const group = el("div", "loop-radios");
group.setAttribute("role", "radiogroup");
for (const [value, text, detail] of options) {
const label = el("label", "loop-radio");
const input = el("input");
input.type = "radio";
input.name = name;
input.id = `loop-${name}-${value}`;
input.checked = current === value;
input.addEventListener("change", () => input.checked && onChange(value));
const body = el("span", "loop-radio-body");
body.appendChild(el("span", "loop-radio-text", text));
if (detail) body.appendChild(el("span", "loop-radio-detail", detail));
label.append(input, body);
group.appendChild(label);
}
return group;
}
function factRow(list, label, value) {
const row = el("div", "loop-fact");
row.appendChild(el("dt", null, label));
@@ -348,22 +250,6 @@ export function renderLoopSetup(main) {
main.appendChild(pane);
}
/** A plain select: [value, text, disabled?] options, the chosen value, a change handler. */
function select(id, label, options, value, onChange) {
const box = el("select", "loop-select");
box.id = id;
box.setAttribute("aria-label", label);
for (const [v, text, disabled] of options) {
const o = el("option", null, text);
o.value = v;
o.disabled = Boolean(disabled);
box.appendChild(o);
}
box.value = value;
box.addEventListener("change", () => onChange(box.value));
return box;
}
/**
* The rising-bar badge of the Subagents tab for a strength level: bars up to
* `level` (1 to 3) are on. Level 0 (Match my session) has no rank, so it draws
@@ -521,7 +407,7 @@ function applySuggestion(s, answer, resolved) {
}
/** The "Strength per phase" field: the toggle, Set all to, and one row per phase left. */
function strengthField(s, redo) {
export function strengthField(s, redo) {
stopWatchingLine();
const f = s.form;
const resolved = s.facts.resolved;
@@ -697,6 +583,7 @@ function drawBody(pane, s) {
const review = field("Review");
review.appendChild(toggle("loop-review", "Review each phase with a fresh agent before it counts", f.review, (v) => ((f.review = v), redo())));
review.appendChild(roundsField(f));
form.appendChild(review);
if (f.review) {
@@ -735,95 +622,7 @@ function drawBody(pane, s) {
after.appendChild(radios("afterlast", AFTER_LAST, f.afterLast, (v) => ((f.afterLast = v), redo())));
form.appendChild(after);
const notify = field(
"Send a notification",
"When the loop waits on your answer or ends, except when you stop it yourself, the app sends a short message saying which, with the project, the phase, what it built and how long it took. Leave the address empty to send nothing."
);
const kindLabel = el("label", "loop-number");
kindLabel.appendChild(el("span", null, "Send to"));
const kindSelect = el("select", "is-compact loop-text");
kindSelect.id = "loop-notify-kind";
for (const kind of NOTIFY_KINDS) {
const option = el("option", null, kind.label);
option.value = kind.id;
kindSelect.appendChild(option);
}
kindSelect.value = f.notifyKind;
kindLabel.appendChild(kindSelect);
const kindHint = el("p", "loop-hint");
const notifyInput = el("input", "is-compact loop-text");
notifyInput.type = "text";
notifyInput.inputMode = "url";
notifyInput.id = "loop-notify-url";
notifyInput.value = f.notifyUrl;
notifyInput.maxLength = 2000;
notifyInput.setAttribute("aria-label", "Web address to call");
const paramRow = el("div");
const paramLabel = el("label", "loop-number");
const paramText = el("span");
paramLabel.appendChild(paramText);
const paramInput = el("input", "is-compact loop-text loop-param");
paramInput.type = "text";
paramInput.id = "loop-notify-param";
paramInput.value = f.notifyParam;
paramInput.placeholder = DEFAULT_NOTIFY_PARAM;
paramInput.maxLength = 64;
paramLabel.appendChild(paramInput);
paramRow.appendChild(paramLabel);
const phasesRow = toggle("loop-notify-phases", "Also tell me when each phase is complete", f.notifyPhases, (v) => {
f.notifyPhases = v;
});
const notifyWarn = el("p", "loop-warn");
const testRow = el("div", "loop-test");
const testButton = el("button", "btn", "Send a test");
testButton.type = "button";
testButton.id = "loop-notify-test";
testButton.addEventListener("click", () => sendTest(s));
testRow.appendChild(testButton);
const testLine = notifyTestLine();
if (testLine) testRow.appendChild(testLine);
const showNotify = () => {
const kind = NOTIFY_KINDS.find((k) => k.id === f.notifyKind);
kindSelect.value = kind.id;
kindHint.textContent = kind.hint;
notifyInput.placeholder = kind.placeholder;
paramText.textContent = kind.name || "";
paramRow.hidden = !kind.name || f.notifyUrl.trim() === "";
phasesRow.hidden = f.notifyUrl.trim() === "";
const problem = notifyProblem(f.notifyUrl, f.notifyParam, kind.id);
notifyWarn.textContent = problem;
notifyWarn.hidden = !problem;
testButton.disabled = Boolean(problem) || f.notifyUrl.trim() === "" || Boolean(page.loopNotifyTest && page.loopNotifyTest.waiting) || s.starting;
};
// What a test said was about the address as it was.
const forgetTest = () => {
if (page.loopNotifyTest && !page.loopNotifyTest.waiting) {
page.loopNotifyTest = null;
testRow.querySelector("p")?.remove();
}
};
notifyInput.addEventListener("input", () => {
f.notifyUrl = notifyInput.value;
forgetTest();
// A pasted webhook picks its own kind, unless the person chose one here.
const service = kindForUrl(f.notifyUrl);
if (service && f.notifyKind === "query" && !s.notifyKindChosen) f.notifyKind = service;
showNotify();
});
kindSelect.addEventListener("change", () => {
f.notifyKind = kindSelect.value;
forgetTest();
s.notifyKindChosen = true;
showNotify();
});
paramInput.addEventListener("input", () => {
f.notifyParam = paramInput.value;
forgetTest();
showNotify();
});
showNotify();
notify.append(kindLabel, notifyInput, kindHint, paramRow, phasesRow, notifyWarn, testRow);
form.appendChild(notify);
form.appendChild(notifyFields(s, f, { onTest: () => sendTest(s) }));
const check = field("Quick check", "A command the app runs after each phase, such as npm run build. The page never runs it.");
const checkInput = el("input", "is-compact loop-text");
@@ -844,20 +643,7 @@ function drawBody(pane, s) {
const retry = field("If a phase crashes or goes quiet");
retry.appendChild(toggle("loop-retry", "Retry it once", f.retryOnce, (v) => ((f.retryOnce = v), redo())));
const silence = el("label", "loop-number");
silence.appendChild(el("span", null, "Count the agent as stuck after this many minutes with no activity"));
const silenceInput = el("input", "is-compact loop-text loop-narrow");
silenceInput.type = "number";
silenceInput.id = "loop-silence";
silenceInput.min = "1";
silenceInput.max = "60";
silenceInput.step = "1";
silenceInput.value = String(f.silenceMinutes);
silenceInput.addEventListener("input", () => {
f.silenceMinutes = Number(silenceInput.value);
});
silence.appendChild(silenceInput);
retry.appendChild(silence);
retry.appendChild(silenceField(f));
retry.appendChild(el("p", "loop-hint", "No activity means no file changes, in the project or the agent's session, so allow for your slowest build or test run. Waiting on your answer does not count."));
form.appendChild(retry);
@@ -895,16 +681,6 @@ function drawBody(pane, s) {
pane.appendChild(foot);
}
/** The line beside Send a test, or null with nothing to say. */
function notifyTestLine() {
const test = page.loopNotifyTest;
if (!test) return null;
if (test.waiting) return el("p", "loop-why", "Waiting for the app's confirm...");
if (!test.ok) return el("p", "loop-error", test.error);
if (test.sent) return el("p", "loop-why", "Sent, and the address answered OK. Check that the message arrived.");
return null;
}
function gitButton() {
const b = el("button", "btn", "Open the Git board");
b.type = "button";
@@ -915,6 +691,30 @@ function gitButton() {
return b;
}
/** "Review rounds per phase": fresh reviewer rounds after a phase's own review, off with Review. */
function roundsField(f) {
const box = el("label", "loop-number");
box.appendChild(el("span", null, "Review rounds per phase"));
const input = el("input", "is-compact loop-text loop-narrow");
input.type = "number";
input.id = "loop-review-rounds";
input.min = "0";
input.max = "6";
input.step = "1";
input.value = String(f.reviewRounds);
input.disabled = !f.review;
input.addEventListener("input", () => {
f.reviewRounds = Number(input.value);
});
box.appendChild(input);
const wrap = el("div", null);
wrap.appendChild(box);
wrap.appendChild(
el("p", "loop-hint", f.review ? "When a phase's own review leaves a Critical or a Warning, fresh reviewers run up to this many more rounds before the phase is committed. 0 turns them off." : "Applies only with Review on")
);
return wrap;
}
/** The form as the console saves it (exported for the page tests). */
export function setupBody(f, s) {
const body = { ...f, quickCheck: f.quickCheck.trim(), notifyUrl: f.notifyUrl.trim(), notifyParam: f.notifyParam.trim() || DEFAULT_NOTIFY_PARAM };
@@ -0,0 +1,433 @@
// Plan2Code Web Console - the Review Loop's setup screen, drawn by the page from the console's saved setup and the app's facts; defines only.
//
// The dashboard's Review Loop card opens this in place of the cards. Nothing
// here runs an agent: Start saves the picks through POST /review-loop-setup,
// then sends them to the desktop app (`review-loop-start { setup }`), which
// confirms in its own window. Its field builders come from ../loop-parts.js, shared with
// the Implementation Loop's screen. The notification address belongs to the
// Implementation Loop's setup: this screen shows it and, when changed, saves it
// there (POST /loop-setup), because the app reads it from that file alone.
import { el } from "../render.js";
import { hooks, page, redraw } from "../state.js";
import { specList } from "../selectors.js";
import { postJson } from "../net.js";
import { tellApp } from "../app-bridge.js";
import { MATCH_SESSION, STRENGTH_WORDS, field, hasMapping, notifyFields, notifyProblem, radios, select, silenceField, toggle } from "../loop-parts.js";
const SCOPES = [
["branch", "Branch against main, with uncommitted changes", "Everything this branch changed since it left main, plus what is not committed yet."],
["uncommitted", "Uncommitted changes only", "Only what is changed in your working tree right now."],
["spec", "A spec's work", "The files the chosen spec's phases built."],
];
export const HANDS_OFF_LINE = "Please do not edit this project's files while rounds run: anything changed goes into the round.";
export const REVIEWER_NOTE = "Each round's reviewer runs fresh, whatever the Subagents switch says; the switch still governs other helpers.";
export const COMMIT_FIRST_LINE = "Commit my current changes first as Work before Review Loop";
const CAP_HINT = "Rounds stop sooner on a clean one. You can always add a round later, one at a time, up to 6 in all.";
/**
* Open the screen for `spec` (the picker's selected spec object, or null). The
* saved setup and the read-only facts come from the console; the agent and its
* helpers come from the app. A spec pre-fills the picker and the spec scope.
*/
export async function openReviewLoopSetup(spec) {
if (page.gone || page.pendingResult || page.local.launching) return;
const dir = spec && spec.dir ? spec.dir : "";
page.reviewStart = null;
page.loopNotifyTest = null;
page.reviewLoopSetup = { spec: dir, loaded: false, failed: false, form: null, facts: null, problems: [], starting: false, resolvedFor: undefined, notifyKindChosen: false };
tellApp("review-loop-facts");
redraw();
const mine = page.reviewLoopSetup;
let res;
try {
res = await fetch("/review-loop-setup?facts=1" + (dir ? "&spec=" + encodeURIComponent(dir) : ""), { cache: "no-store" });
} catch {
res = null;
}
if (page.reviewLoopSetup !== mine) return;
const answer = res && res.ok ? await res.json().catch(() => null) : null;
if (page.reviewLoopSetup !== mine) return;
if (!answer) {
mine.failed = true;
redraw();
return;
}
const facts = page.reviewFacts;
mine.form = {
scope: ["branch", "uncommitted", "spec"].includes(answer.scope) ? answer.scope : "branch",
spec: typeof answer.spec === "string" ? answer.spec : "",
cap: Number.isInteger(answer.cap) ? answer.cap : 3,
commit: answer.commit !== false,
agreeCommit: false,
suggestions: answer.suggestions === true,
strength: typeof answer.strength === "string" ? answer.strength : "",
silenceMinutes: Number.isInteger(answer.silenceMinutes) ? answer.silenceMinutes : 20,
notifyRounds: answer.notifyRounds === true,
notifyKind: (facts && facts.notifyKind) || "query",
notifyUrl: (facts && facts.notifyUrl) || "",
notifyParam: (facts && facts.notifyParam) || "message",
};
// The picker's spec lives in the form; the saved one only matters on the spec scope.
if (dir) mine.form.spec = dir;
mine.facts = { branch: typeof answer.branch === "string" ? answer.branch : "", pending: Number.isInteger(answer.pending) ? answer.pending : null, resolved: undefined };
mine.loaded = true;
redraw();
}
const reviewAgent = () => (page.reviewFacts && typeof page.reviewFacts.agent === "string" ? page.reviewFacts.agent : "");
/** The facts' notify values arrive with the app's answer, which can follow the setup: take them while the fields are still as saved. */
function adoptNotify(s) {
const facts = page.reviewFacts;
if (!facts || s.notifyAdopted || !s.form) return;
s.notifyAdopted = true;
if (!s.form.notifyUrl) s.form.notifyUrl = facts.notifyUrl || "";
s.form.notifyKind = facts.notifyKind || s.form.notifyKind;
s.form.notifyParam = facts.notifyParam || s.form.notifyParam;
}
/** Read the agent's strengths once the app has said which agent it is (the two answers come in either order). */
function ensureResolved(s) {
if (!page.reviewFacts || s.resolvedFor === reviewAgent()) return;
const agent = reviewAgent();
s.resolvedFor = agent;
if (!agent) {
s.facts.resolved = null;
return;
}
fetch("/review-loop-setup?agent=" + encodeURIComponent(agent), { cache: "no-store" })
.then((res) => (res.ok ? res.json() : null))
.catch(() => null)
.then((answer) => {
if (page.reviewLoopSetup !== s || s.resolvedFor !== agent) return;
s.facts.resolved = answer && answer.resolved && typeof answer.resolved === "object" ? answer.resolved : null;
redraw();
});
}
function close() {
page.reviewLoopSetup = null;
page.reviewStart = null;
redraw();
}
/**
* Why Start is grayed, or "" when it can go, in the spec's order. Exported for
* the page's unit tests.
*/
export function reviewStartBlock(form, facts, appFacts) {
if (!form || !facts) return "Loading the setup...";
if (!appFacts) return "Asking the app...";
if (appFacts.running) return "A loop is already running in this window. Stop it from the banner first.";
if (appFacts.promptSupport === false) return "This agent cannot be started with a first prompt.";
if (form.scope === "spec" && !form.spec) return "Pick the spec whose work to review.";
if (form.commit && facts.pending !== null && facts.pending > 0 && !form.agreeCommit) {
return `${facts.pending} uncommitted ${facts.pending === 1 ? "change needs" : "changes need"} your say-so: tick the box to commit ${facts.pending === 1 ? "it" : "them"} first, or turn commits off.`;
}
const problem = notifyProblem(form.notifyUrl, form.notifyParam, form.notifyKind);
if (problem) return problem;
return "";
}
/** The form as the console saves it (exported for the page tests). */
export function reviewSetupBody(f) {
return {
scope: f.scope,
spec: f.scope === "spec" ? f.spec : "",
cap: f.cap,
commit: f.commit,
suggestions: f.suggestions,
strength: f.strength,
silenceMinutes: f.silenceMinutes,
notifyRounds: f.notifyRounds,
};
}
/** What the app is sent: the saved picks and whether the person agreed to the pre-run commit. */
export function reviewStartMessage(f, facts) {
const dirty = facts && facts.pending !== null && facts.pending > 0;
return { ...reviewSetupBody(f), preRunCommitAgreed: Boolean(f.commit && dirty && f.agreeCommit) };
}
function factRow(list, label, value) {
const row = el("div", "loop-fact");
row.appendChild(el("dt", null, label));
row.appendChild(el("dd", null, value));
list.appendChild(row);
}
function agentLine(facts) {
if (!facts) return "Asking the app...";
if (!facts.agent) return "No agent is chosen yet";
const label = facts.agentLabel || facts.agent;
return facts.helpers ? `${label} (starts its own helpers: one session per round)` : `${label} (no helpers: a reviewer session, then a fixer session, each round)`;
}
export function renderReviewLoopSetup(main) {
const s = page.reviewLoopSetup;
const pane = el("div", "dash-confirm loop-setup review-loop-setup");
pane.appendChild(el("p", "card-kicker", "Step 3 · Review Loop"));
pane.appendChild(el("h2", "dash-title", "Set up the Review Loop"));
if (s.failed) {
pane.appendChild(el("p", "loop-error", "The setup could not be read. Go back and try again."));
} else if (!s.loaded) {
const wait = el("p", "dash-working");
wait.append(el("span", "spinner tiny"), el("span", null, "Loading the setup..."));
pane.appendChild(wait);
} else {
drawBody(pane, s);
}
const actions = el("div", "confirm-actions");
const back = el("button", "btn ghost", "Back");
back.type = "button";
back.addEventListener("click", close);
actions.appendChild(back);
const help = el("button", "linky loop-help", "How the loop works");
help.type = "button";
help.addEventListener("click", () => hooks.openHelpOn("loop"));
actions.appendChild(help);
pane.appendChild(actions);
main.appendChild(pane);
}
/** One strength for every round: Match my session, or a mapped word. Grayed when this agent maps none. */
function strengthPick(s) {
const f = s.form;
const resolved = s.facts.resolved;
const appFacts = page.reviewFacts;
const box = field("Strength");
const loading = !appFacts || resolved === undefined;
const none = !loading && (appFacts.strengthsMapped === false || !hasMapping(resolved));
if (none) {
const gray = el("p", "loop-hint loop-strength-none");
gray.append("This agent has no strengths mapped yet. ");
const link = el("button", "linky", "Map them in Agents & models");
link.type = "button";
link.addEventListener("click", () => hooks.openPrefs("agents"));
gray.appendChild(link);
box.appendChild(gray);
return box;
}
if (loading) {
box.appendChild(el("p", "loop-hint", "Asking the app which agent this loop uses..."));
return box;
}
const options = [["", MATCH_SESSION], ...STRENGTH_WORDS.map(([word, label]) => [word, resolved[word] ? label : label + " (not mapped)", !resolved[word]])];
if (f.strength && !resolved[f.strength]) f.strength = "";
box.appendChild(
select("review-loop-strength", "Strength for every round", options, f.strength, (v) => {
f.strength = v;
s.problems = [];
redraw();
})
);
const row = f.strength ? resolved[f.strength] : null;
box.appendChild(el("p", "loop-hint", row ? [row.model, row.effort].filter(Boolean).join(", ") : "Rounds use the model and effort this window started with."));
return box;
}
function specPicker(s) {
const f = s.form;
const specs = specList();
const wrap = el("div", "loop-spec-pick");
const options = [["", "Choose a spec..."]];
for (const sp of specs) options.push([sp.dir, sp.dir]);
// A spec the list does not hold (one picked on the dashboard that has since moved) stays visible.
if (f.spec && !specs.some((sp) => sp.dir === f.spec)) options.push([f.spec, f.spec]);
wrap.appendChild(
select("review-loop-spec", "Spec to review", options, f.spec, (v) => {
f.spec = v;
s.problems = [];
redraw();
})
);
return wrap;
}
function drawBody(pane, s) {
const f = s.form;
adoptNotify(s);
ensureResolved(s);
const appFacts = page.reviewFacts;
const redo = () => {
s.problems = [];
redraw();
};
const lines = el("div", "loop-lines");
for (const text of [
"The app reviews your change in rounds, each in a fresh agent session. Round 1 looks at everything in scope; each later round looks only at what the round before it changed.",
"It stops on a clean round, at the round cap, or when you press a stop button on the banner at the top of the window. It never pushes.",
]) {
lines.appendChild(el("p", "loop-line", text));
}
lines.appendChild(el("p", "loop-line loop-hands-off", HANDS_OFF_LINE));
pane.appendChild(lines);
const facts = el("dl", "loop-facts");
factRow(facts, "Agent", agentLine(appFacts));
factRow(facts, "Branch", s.facts.branch || "unknown");
factRow(facts, "Uncommitted changes", s.facts.pending === null ? "unknown" : String(s.facts.pending));
pane.appendChild(facts);
const form = el("div", "loop-form");
const scope = field("What to review");
scope.appendChild(radios("reviewscope", SCOPES, f.scope, (v) => ((f.scope = v), redo())));
if (f.scope === "spec") scope.appendChild(specPicker(s));
form.appendChild(scope);
const cap = field("Round cap", CAP_HINT);
const capLabel = el("label", "loop-number");
capLabel.appendChild(el("span", null, "Stop after this many rounds (1 to 6)"));
const capInput = el("input", "is-compact loop-text loop-narrow");
capInput.type = "number";
capInput.id = "review-loop-cap";
capInput.min = "1";
capInput.max = "6";
capInput.step = "1";
capInput.value = String(f.cap);
capInput.addEventListener("input", () => {
f.cap = Number(capInput.value);
});
capLabel.appendChild(capInput);
cap.appendChild(capLabel);
form.appendChild(cap);
const commit = field("Commit");
commit.appendChild(toggle("review-loop-commit", "Commit each round to the current branch", f.commit, (v) => ((f.commit = v), redo())));
if (f.commit && s.facts.pending !== null && s.facts.pending > 0) {
commit.appendChild(toggle("review-loop-agree", COMMIT_FIRST_LINE, f.agreeCommit, (v) => ((f.agreeCommit = v), redo())));
}
form.appendChild(commit);
const sugg = field("Suggestions");
sugg.appendChild(toggle("review-loop-suggestions", "Apply Suggestions on their own", f.suggestions, (v) => ((f.suggestions = v), redo())));
sugg.appendChild(el("p", "loop-hint", "Off: Suggestions are listed in the report for you to pick. On: they are applied in one last pass."));
form.appendChild(sugg);
form.appendChild(strengthPick(s));
const reviewer = field("Reviewers");
reviewer.appendChild(el("p", "loop-hint loop-reviewer-note", REVIEWER_NOTE));
form.appendChild(reviewer);
const retry = field("If a round goes quiet");
retry.appendChild(silenceField(f, "Count the agent as stuck after this many minutes with no activity"));
retry.appendChild(el("p", "loop-hint", "No activity means no file changes, in the project or the agent's session, so allow for your slowest test run. A stuck round is retried once."));
form.appendChild(retry);
form.appendChild(
notifyFields(s, f, {
intro: "When the Review Loop needs you or ends, except when you stop it yourself, the app sends a short message naming the round. The address is the Implementation Loop's: changing it here changes it there. Leave it empty to send nothing.",
phasesId: "review-loop-notify-rounds",
phasesKey: "notifyRounds",
phasesText: "Also tell me when each round finishes",
onTest: () => sendTest(s),
})
);
pane.appendChild(form);
const block = reviewStartBlock(f, s.facts, appFacts);
const gated = Boolean(block);
const foot = el("div", "loop-start");
if (gated) {
const why = el("p", "loop-why", block);
why.setAttribute("role", "status");
foot.appendChild(why);
}
if (s.problems.length) {
const bad = el("ul", "loop-problems");
for (const p of s.problems) bad.appendChild(el("li", null, p));
foot.appendChild(bad);
}
const waiting = s.starting && !page.reviewStart;
if (waiting) foot.appendChild(el("p", "loop-why", "Waiting for the app's confirm..."));
if (page.reviewStart && !page.reviewStart.ok) foot.appendChild(el("p", "loop-error", page.reviewStart.error));
if (page.reviewStart && page.reviewStart.ok) foot.appendChild(el("p", "loop-why", "The Review Loop is starting..."));
const start = el("button", "btn primary", "Start the Review Loop");
start.type = "button";
start.id = "review-loop-start";
start.disabled = gated || waiting || page.gone || page.pendingResult || Boolean(page.reviewStart && page.reviewStart.ok);
start.addEventListener("click", () => startReviewLoop(s));
foot.appendChild(start);
pane.appendChild(foot);
}
/**
* Save the notification fields into the Implementation Loop's setup, the only
* place the app reads them from. A project with no loop setup yet gets the
* loop's defaults beside the new address. Resolves to a problem line or "".
*/
async function saveNotify(s) {
const f = s.form;
const facts = page.reviewFacts || {};
const url = f.notifyUrl.trim();
const param = f.notifyParam.trim() || "message";
if (url === (facts.notifyUrl || "") && f.notifyKind === (facts.notifyKind || "query") && param === (facts.notifyParam || "message")) return "";
let current = null;
try {
const res = await fetch("/loop-setup", { cache: "no-store" });
current = res.ok ? await res.json() : null;
} catch {
current = null;
}
if (!current) return "The notification address could not be saved. Try again.";
// The loop's own screen drops these two before it saves; the store rejects them as unknown fields.
const { remembered, saved, ...entry } = current;
const { status, body } = await postJson("/loop-setup", { ...entry, notifyKind: f.notifyKind, notifyUrl: url, notifyParam: param });
if (status !== 200 || !body || body.ok !== true) {
return Array.isArray(body && body.problems) && body.problems.length ? body.problems.join(" ") : "The notification address could not be saved. Try again.";
}
// What the app now reads, so a second Start does not save it again.
if (page.reviewFacts) page.reviewFacts = { ...page.reviewFacts, notifyKind: f.notifyKind, notifyUrl: url, notifyParam: param };
return "";
}
async function sendTest(s) {
const f = s.form;
if (!f.notifyUrl.trim() || notifyProblem(f.notifyUrl, f.notifyParam, f.notifyKind) || (page.loopNotifyTest && page.loopNotifyTest.waiting)) return;
s.problems = [];
page.loopNotifyTest = { waiting: true };
redraw();
const problem = await saveNotify(s);
if (page.reviewLoopSetup !== s) return;
if (problem) {
page.loopNotifyTest = null;
s.problems = [problem];
redraw();
return;
}
tellApp("loop-notify-test");
}
async function startReviewLoop(s) {
const f = s.form;
if (reviewStartBlock(f, s.facts, page.reviewFacts) || (s.starting && !page.reviewStart)) return;
s.problems = [];
page.reviewStart = null;
s.starting = true;
redraw();
const problem = await saveNotify(s);
if (page.reviewLoopSetup !== s) return;
if (problem) {
s.starting = false;
s.problems = [problem];
redraw();
return;
}
const { status, body } = await postJson("/review-loop-setup", reviewSetupBody(f));
if (page.reviewLoopSetup !== s) return;
if (status !== 200 || !body || body.ok !== true) {
s.starting = false;
s.problems = Array.isArray(body && body.problems) && body.problems.length ? body.problems : ["The setup could not be saved. Try again."];
redraw();
return;
}
tellApp("review-loop-start", { setup: reviewStartMessage(f, s.facts) });
redraw();
}