2026-11-28 21:09:02 -08:00
// 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 );
2026-11-28 22:29:52 -08:00
const help = el ( "button" , "linky loop-help" , "How the Review Loop works" );
2026-11-28 21:09:02 -08:00
help . type = "button" ;
2026-11-28 22:29:52 -08:00
help . addEventListener ( "click" , () => hooks . openHelpOn ( "review-loop" ));
2026-11-28 21:09:02 -08:00
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 ();
}