diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index b6266a3e..4e9230e0 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -424,10 +424,10 @@ def compile(recipe: dict, defs: Optional[Dict[str, List[dict]]] = None, *, the run sends it as.""" d = defs or _all() errors, notes = [], [] - # each problem once; shown: the step already says it elsewhere, so only Review lists it - def add(step, message, shown=False): + # each problem once; shown: the step already says it elsewhere, so only Review lists it; field: the input it is about + def add(step, message, shown=False, field=None): if not any(e["step"] == STEP[step] and e["message"] == message for e in errors): - errors.append({"step": STEP[step], "message": message, **({"shown": True} if shown else {})}) + errors.append({"step": STEP[step], "message": message, **({"shown": True} if shown else {}), **({"field": field} if field else {})}) out = {"errors": errors, "notes": notes, "review": [], "jobs": [], "confirm": "", "script": "", "parts": [], "model": "", "served_models": {}} name = str(recipe.get("name") or "") @@ -669,7 +669,10 @@ def add(step, message, shown=False): turns = None limit = recipe.get("limit") if limit not in ("", None) and _int(limit, 1) is None: - add("limits", "The number of units is a whole number of at least 1, or empty for all of them.") + # the noun of the field's own label (command-builder.js, unitsOf): Original's when it alone runs, an own agent counted as it + alone = refs and {"original" if ref == "original" or (":" in ref and definitions.own_agent(base, ref)) else ref for ref in refs} == {"original"} + units = (((b.get("setups") or {}).get("original") or {}).get("units") if alone else None) or b.get("units") or {} + add("limits", f"Number of {units.get('nouns', 'units')}: a whole number of at least 1, or empty for all.", field="limit") # empty: one at a time; on Boat, as many as the account runs at once (the run caps it to that, boat.slots) conc = _int(recipe.get("concurrency") or (MAX_CONCURRENT if backend == "boat" else 1), 1, MAX_CONCURRENT) if conc is None: @@ -1036,7 +1039,7 @@ def proving(benchmark: str, *, dataset: str = "", limit=None, provider: str = "o if not sets: errors.append(f"Choose one of {b['label']}'s datasets, or each of them.") if limit not in ("", None) and _int(limit, 1) is None: - errors.append("The number of units is a whole number of at least 1, or empty for all of them.") + errors.append(f"Number of {(b.get('units') or {}).get('nouns', 'units')}: a whole number of at least 1, or empty for all.") if _int(concurrency, 1, MAX_CONCURRENT) is None: errors.append(f"Units at a time: a whole number from 1 to {MAX_CONCURRENT}.") if judged and provider not in PROVIDERS: diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index a8438d2e..03468123 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -93,7 +93,21 @@ if (!out || !run || run.hasAttribute('data-held')) return ''; return out.ready ? 'Ready' : 'Missing something: Run waits'; } - if (typeof module === 'object' && module.exports) { module.exports = {servedRows, recipeStore, savedList, prereqHead}; return; } + // An error the server ties to a field (recipe.py: `field`) is said under that field of the open step, the field marked + // invalid and described by it; each said earlier is taken away first. Returns the step's errors no field here says. + function fieldErrors(form, errors, esc) { + form.querySelectorAll('[data-field-error]').forEach(m => m.remove()); + form.querySelectorAll('[aria-invalid][data-field]').forEach(f => { f.removeAttribute('aria-invalid'); f.removeAttribute('aria-describedby'); }); + return errors.filter(e => { + const f = e.field && form.querySelector(`[data-field="${e.field}"]`); + if (!f) return true; + f.setAttribute('aria-invalid', 'true'); + f.setAttribute('aria-describedby', 'nb-error-' + e.field); + f.closest('.nb-field').insertAdjacentHTML('beforeend', `${esc(e.message)}`); + return false; + }); + } + if (typeof module === 'object' && module.exports) { module.exports = {servedRows, recipeStore, savedList, prereqHead, fieldErrors}; return; } const root = document.getElementById('nullius-builder'); if (!root) return; const schema = JSON.parse(document.getElementById('nb-schema').textContent); @@ -957,11 +971,11 @@ const out=runnerOut||{errors:[],notes:[]}; compiled={errors:out.errors||[],notes:out.notes||[]}; }else{compiled=C.compile(rec);} - $('#nb-localerrors').textContent=compiled.errors.filter(e=>e.step===step&&!e.shown).map(e=>e.message).join(' '); + $('#nb-localerrors').textContent=fieldErrors($('#nb-form'),compiled.errors.filter(e=>e.step===step&&!e.shown),esc).map(e=>e.message).join(' '); const errors=$('#nb-errors'); if(errors){ errors.hidden=!compiled.errors.length; - errors.innerHTML=compiled.errors.map(e=>button(esc(e.message),`data-step="${e.step}" ${e.step===S.agent&&!C.isStandard(rec)?`data-config-group="${esc(e.group||'')}"`:""}`,'')).join(''); + errors.innerHTML=compiled.errors.map(e=>button(esc(e.message),`data-step="${e.step}" ${e.field?`data-error-field="${esc(e.field)}" `:''}${e.step===S.agent&&!C.isStandard(rec)?`data-config-group="${esc(e.group||'')}"`:""}`,'')).join(''); } $('#nb-next').disabled=step===REVIEW&&compiled.errors.length>0; if($('#nb-reviewnotes'))$('#nb-reviewnotes').innerHTML=compiled.notes.map(t=>`

${esc(t)}

`).join(''); @@ -1155,6 +1169,8 @@ else if(b.id==='nb-refresh'){await refreshRegistry();return;} else return; render(d.step!==undefined||['nb-next','nb-back'].includes(b.id)); + // Review's link to an error a field holds: to that field, not the step's heading + const f=d.errorField&&$(`#nb-form [data-field="${d.errorField}"]`);if(f){f.focus({preventScroll:true});f.scrollIntoView({block:'center'});} }); // a benchmark chosen on the Benchmark step's grid, or an agent, a capability or the setup picked or let go on the // Agent step's; the page stays where it is and the focus on its card diff --git a/app/tests/test_standard_ui.py b/app/tests/test_standard_ui.py index e58e6472..ba5f141d 100644 --- a/app/tests/test_standard_ui.py +++ b/app/tests/test_standard_ui.py @@ -100,6 +100,7 @@ def test_bad_choices_are_refused(self): self.assertTrue(recipe.proving("nope", stamp=STAMP)["errors"]) got = recipe.proving("fakebench", stamp=STAMP, dataset="other", limit=0) self.assertEqual(len(got["errors"]), 2) + self.assertIn("Number of tasks: a whole number of at least 1, or empty for all.", got["errors"]) # the benchmark's noun self.assertTrue(recipe.proving("fakebench", stamp="today")["errors"]) diff --git a/app/ui_tests/test_builder_limit_error.py b/app/ui_tests/test_builder_limit_error.py new file mode 100644 index 00000000..a8d3373b --- /dev/null +++ b/app/ui_tests/test_builder_limit_error.py @@ -0,0 +1,57 @@ +"""The Limits step's Number of ... field and its error: said at the field, tied to it, in the field's noun, and reached from Review.""" +import json +import re +import subprocess +import unittest + +from nullius.standard.pages import recipe +from ui_tests.builder_support import APP, CompilerCase + +PAGE = APP / "static/builder/command-builder.js" + + +class LimitError(CompilerCase): + def test_the_message_is_said_under_its_field_and_taken_away_when_valid(self): + """A field's error goes into the field's own label, the field invalid and described by it; the step keeps the rest.""" + program = ("const {fieldErrors}=require(" + json.dumps(str(PAGE)) + ");" + "const esc=x=>String(x).replace(/attrs[k]=v,removeAttribute:k=>delete attrs[k],closest:s=>s==='.nb-field'?label:null};" + "const form={querySelector:s=>s==='[data-field=\"limit\"]'?input:null," + "querySelectorAll:s=>s==='[data-field-error]'?(label.html?[{remove:()=>label.html=''}]:[]):s==='[aria-invalid][data-field]'&&attrs['aria-invalid']?[input]:[]};" + "const got=[];const rest=fieldErrors(form,[{field:'limit',message:'Number of problems: <1'},{message:'other'}],esc);" + "got.push([rest,{...attrs},label.html]);got.push([fieldErrors(form,[],esc),{...attrs},label.html]);" + "process.stdout.write(JSON.stringify(got));") + bad, good = json.loads(subprocess.run([self.node, "-"], input=program, check=True, capture_output=True, text=True).stdout) + self.assertEqual(bad[0], [{"message": "other"}]) + self.assertEqual(bad[1], {"aria-invalid": "true", "aria-describedby": "nb-error-limit"}) + self.assertEqual(bad[2], 'Number of problems: <1') + self.assertEqual(good, [[], {}, ""]) + + def test_the_message_names_the_fields_noun(self): + """For every standard benchmark, run by Original alone or by a check, the error starts with the field's own label.""" + page = PAGE.read_text(encoding="utf-8") + unitsof = page[page.index(" const unitsOf = "):page.index(" // the first clause", page.index(" const unitsOf = "))] + program = ("const C=require(" + json.dumps(str(APP / "static/builder/command-builder-core.js")) + ")(" + json.dumps(self.schema) + ");\n" + unitsof + + "const out=[];for(const b of C.standard().benchmarks)for(const runs of [b.setups.length?['original']:[],(b.controls||[]).slice(0,1).map(c=>c.key)]){" + + "if(!runs.length)continue;const r=C.createStandard(b.key);r.others=runs;r.limit=-3;out.push([b.key,runs,'Number of '+unitsOf(r).nouns,r]);}" + + "process.stdout.write(JSON.stringify(out));") + cases = json.loads(subprocess.run([self.node, "-"], input=program, check=True, capture_output=True, text=True).stdout) + self.assertIn(["gsm8k", ["original"], "Number of problems"], [c[:3] for c in cases]) + self.assertIn(["locomo", ["original"], "Number of conversations"], [c[:3] for c in cases]) + for key, runs, label, rec in cases: + with self.subTest(key, runs=runs): + errors = [e for e in recipe.compile(rec)["errors"] if e.get("field") == "limit"] + self.assertEqual([(e["step"], e["message"]) for e in errors], + [(recipe.STEP["limits"], label + ": a whole number of at least 1, or empty for all.")]) + + def test_reviews_link_puts_the_focus_on_the_field(self): + """Review's error names its field, and selecting it focuses that field rather than the step's heading.""" + page = PAGE.read_text(encoding="utf-8") + self.assertTrue(re.search(r"errors\.innerHTML=compiled\.errors\.map\(e=>button\(esc\(e\.message\),`data-step=\"\$\{e\.step\}\" \$\{e\.field\?`data-error-field=", page), "Review's error carries no field") + after = page[page.index("render(d.step!==undefined||['nb-next','nb-back'].includes(b.id));"):] + self.assertTrue(re.search(r"d\.errorField&&\$\(`#nb-form \[data-field=\"\$\{d\.errorField\}\"\]`\);if\(f\)\{f\.focus\(", after[:400]), "Review's link does not focus the field") + + +if __name__ == "__main__": + unittest.main()