Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions app/nullius/standard/pages/recipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "")
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
22 changes: 19 additions & 3 deletions app/static/builder/command-builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,21 @@
if (!out || !run || run.hasAttribute('data-held')) return '';
return out.ready ? '<span class="nb-note nb-ok">Ready</span>' : '<span class="nb-note nb-error">Missing something: Run waits</span>';
}
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', `<small id="nb-error-${e.field}" class="nb-error" data-field-error>${esc(e.message)}</small>`);
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);
Expand Down Expand Up @@ -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=>`<p class="nb-note">${esc(t)}</p>`).join('');
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions app/tests/test_standard_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])


Expand Down
57 changes: 57 additions & 0 deletions app/ui_tests/test_builder_limit_error.py
Original file line number Diff line number Diff line change
@@ -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(/</g,'&lt;');"
"const label={html:'',insertAdjacentHTML(_,h){this.html+=h;}};"
"const attrs={},input={setAttribute:(k,v)=>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], '<small id="nb-error-limit" class="nb-error" data-field-error>Number of problems: &lt;1</small>')
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()
Loading