diff --git a/app/nullius/standard/pages/recipe.py b/app/nullius/standard/pages/recipe.py index 4d1cca13..5cf5ecf9 100644 --- a/app/nullius/standard/pages/recipe.py +++ b/app/nullius/standard/pages/recipe.py @@ -426,10 +426,11 @@ 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; field: the input it is about - def add(step, message, shown=False, field=None): + # each problem once; shown: the step already says it elsewhere, so only Review lists it; field: the input it is about; unset: nothing is + # chosen yet, which the Model step does not say before its field is used + def add(step, message, shown=False, field=None, unset=False): 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 {}), **({"field": field} if field else {})}) + errors.append({"step": STEP[step], "message": message, **({"shown": True} if shown else {}), **({"field": field} if field else {}), **({"unset": True} if unset else {})}) out = {"errors": errors, "notes": notes, "review": [], "jobs": [], "confirm": "", "script": "", "parts": [], "model": "", "served_models": {}} name = str(recipe.get("name") or "") @@ -482,7 +483,7 @@ def add(step, message, shown=False, field=None): orig = (b.get("setups") or {}).get("original") or {} picked = str(recipe.get("model") or "").strip() if not picked: - add("model", "Choose a model.") + add("model", "Choose a model.", unset=True) continue method = "model" if recipe.get("model_choice", "any") != "paper" and "model" in (b.get("setups") or {}) else "original" if method == "original": @@ -592,7 +593,7 @@ def add(step, message, shown=False, field=None): add("model", f"{providers.label(provider)} does not serve what {b['label']}'s judge speaks: choose another provider.") model = str(recipe.get("model") or "").strip() if not _MODEL.match(model) and (needs_model or model): - add("model", "Choose a model or enter its ID.") + add("model", "Choose a model or enter its ID.", unset=not model) if model_choice == "paper" and model in orig.get("models", []) and provider_ in orig.get("providers", {}): model = orig["providers"][provider_] + (orig.get("served_as") or {}).get(model, model) # each unit tried K times (the upstream's --num-trials: pass^k); the user simulator's and the judge's models @@ -767,7 +768,7 @@ def called_of(p: dict) -> List[str]: add("model", f"Served by pins {m} twice, with different providers: give its fields the same ones.") by_model[m] = list(slugs) # each field's model as the run sends it, for the builder to ask its providers under that name - out["served_models"] = {role: next((sent_of(p)[role] for p in sorted(picks, key=lambda q: q["control"]) if sent_of(p)[role]), None) + out["served_models"] = {role: next((sent_of(p)[role] for p in sorted(picks, key=lambda q: q["control"]) if _MODEL.match(sent_of(p)[role] or "")), None) for role in roles} def pinned(p: dict) -> Dict[str, List[str]]: diff --git a/app/static/builder/command-builder-core.js b/app/static/builder/command-builder-core.js index 88825f5f..8b838d58 100644 --- a/app/static/builder/command-builder-core.js +++ b/app/static/builder/command-builder-core.js @@ -509,7 +509,7 @@ const RESERVED = ['agent','a','model','m','dataset','d','path','p','n-tasks','l','n-concurrent','n','max-retries','r','env','e','job-name','jobs-dir','o','agent-timeout-multiplier','include-task-name','i','ak','agent-kwarg','ek','environment-kwarg','verifier-kwarg','agent-env','ae']; function validate(r) { const errors = [], notes = []; - const add = (step, message, group) => errors.push({step, message, ...(group ? {group} : {})}); + const add = (step, message, group, unset) => errors.push({step, message, ...(group ? {group} : {}), ...(unset ? {unset} : {})}); if (isStandard(r)) return {errors, notes}; // compiled and checked by the server, from its definition files if (r.harness !== 'harbor') { add(STEP.runner, RUNNER_GONE); return {errors, notes}; } const blocker = routeBlocker(r.benchmark); @@ -533,9 +533,9 @@ const named = r.model.trim() || (benchmarkCallsModel(r) && r.agents.every(id => agentById(id, r)?.control) ? (r.userModel || '').trim() : ''); if (callsModel && r.model_choice === 'paper') { const allowed = Object.values(paperModels(r).sent?.[r.provider] || {}); - if (!allowed.includes(r.model)) add(STEP.model, 'Choose one of the paper models on this provider.'); + if (!allowed.includes(r.model)) add(STEP.model, 'Choose one of the paper models on this provider.', '', !r.model); } - if (callsModel && !named) add(STEP.model, benchmarkCallsModel(r) ? 'Enter a model for the agent and/or simulated user and evaluator.' : 'Enter a model.'); + if (callsModel && !named) add(STEP.model, benchmarkCallsModel(r) ? 'Enter a model for the agent and/or simulated user and evaluator.' : 'Enter a model.', '', true); if (callsModel && !PROVIDERS.includes(r.provider)) add(STEP.model, 'Choose a provider: OpenRouter, OpenAI, Anthropic or a custom provider.'); for (const [key,label] of [['keyEnv','API key source variable'],['urlEnv','Endpoint source variable']]) { if (callsModel && (key !== 'urlEnv' || r[key]) && !/^[A-Z_][A-Z0-9_]*$/.test(r[key])) add(STEP.model, label + ' must be an environment variable name.'); diff --git a/app/static/builder/command-builder.css b/app/static/builder/command-builder.css index 3ffa42ab..9186496d 100644 --- a/app/static/builder/command-builder.css +++ b/app/static/builder/command-builder.css @@ -220,12 +220,7 @@ #nullius-builder .ui-field-row > input, #nullius-builder .ui-field-row > textarea { background: var(--nb-surface); } @media (max-width: 650px) { #nullius-builder label.nb-field.ui-field-row { grid-template-columns: minmax(0, 1fr); gap: 10px; } #nullius-builder .ui-field-row > input, #nullius-builder .ui-select-trigger { font-size: 16px; } } -#nullius-builder .nb-model-control { display: flex; position: relative; min-width: 0; } #nullius-builder .nb-model-control input { padding: 6px 36px 6px 11px; min-height: 34px; font-size: 13px; } -#nullius-builder .nb-model-open { display: grid; place-items: center; padding: 0; position: absolute; right: 1px; top: 1px; bottom: 1px; width: 32px; border: 0; background: transparent; color: var(--nb-muted); border-radius: 7px; } -.nb-model-option { display: flex; flex-direction: column; gap: 2px; } -.nb-model-option small, .nb-model-status { color: var(--text-dim); font-size: 12px; } -.nb-model-status { padding: 8px 9px; } @media (max-width: 650px) { #nullius-builder .nb-model-control input { font-size: 16px; } } /* Compact settings rows use one shared control column, including paired fields. */ diff --git a/app/static/builder/command-builder.js b/app/static/builder/command-builder.js index 60769ebe..27124be2 100644 --- a/app/static/builder/command-builder.js +++ b/app/static/builder/command-builder.js @@ -6,7 +6,8 @@ // the model's providers (POST /new-run/endpoints), a pick or a slug typed and Enter joins the list under it, each // removable. Empty: any provider. What a row shows is C.servedRow's; `compiled()` is the server's last compile and // the key of the recipe it was made for (C.servedKey). - function servedRows({C, root, r, compiled, esc, button, providers}) { + // A role whose model is being typed has no row: `typing(role)`. + function servedRows({C, root, r, compiled, esc, button, providers, typing = () => false}) { const NAME = {model: 'model', simulator: 'user simulator', judge: 'judge'}; // the model a Served by is for, as the step shows it: the field's, else the leaderboard's or the official one const shown = (rec, role) => { @@ -43,7 +44,7 @@ const rec = r(); root.querySelectorAll('input[data-served-by]').forEach(input => { const role = input.dataset.servedBy, s = row(rec, role), list = root.querySelector(`[data-served-list="${role}"]`); - input.closest('.std-served').hidden = !C.servedRoles(rec).includes(role) || !s.visible; + input.closest('.std-served').hidden = !C.servedRoles(rec).includes(role) || !s.visible || typing(role); Object.assign(input.dataset, {servedModel: s.model, servedPending: String(s.pending), chosen: s.chosen.join(',')}); input.placeholder = s.placeholder; if (list && list.dataset.of !== JSON.stringify(s.chosen)) { list.dataset.of = JSON.stringify(s.chosen); list.innerHTML = chips(role, s.chosen); } @@ -219,9 +220,10 @@ }; // The standard's recipe as the server compiles it from the definitions (POST // /new-run/runner). Nothing typed here is a command; Run sends the choices. - let runnerOut = null, runnerKey = '', runnerTimer, runnerServed = null; + let runnerOut = null, runnerKey = '', runnerOutKey = '', runnerTimer, runnerServed = null; // Served by's rows (servedRows above), given the models the server last named and what decided them (C.servedCompiled) - const {field: servedField, sync: syncServed, acceptCompile} = servedRows({C, root, r, esc, button, compiled: () => runnerServed, providers: window.NulliusServingProviders}); + const {field: servedField, sync: syncServed, acceptCompile} = servedRows({C, root, r, esc, button, compiled: () => runnerServed, providers: window.NulliusServingProviders, + typing: role => !!root.querySelector(`[data-field="${role === 'model' ? role : role + '_model'}"][data-typing]`)}); // Switching runner keeps the recipe being edited, one per runner, for as long as the page is open: switching back finds it as it was. const keptByRunner = {}; // Nullius's own mark for the standard; Harbor's for Harbor @@ -876,7 +878,7 @@ runnerServed = accepted.served; if (step === S.model) syncServed(); if (!accepted.current) return; - runnerOut = out; + runnerOut = out; runnerOutKey = key; if (step === REVIEW) renderForm(); refreshPlan(); }, 120); @@ -975,6 +977,32 @@ $('#nb-next').textContent=step===REVIEW?'Export recipe JSON':stepName(steps[nextShown(step,1)],nextShown(step,1))+' →'; placeThumb(); } + // The open step's errors. The Model step says none over a model being typed, nor before one is chosen or its field left. + let modelActed=false; + function localErrors() { + const rec=r(),el=document.activeElement,typing=root.contains(el)&&el.dataset.typing; + if(step===REVIEW)modelActed=true; + // nor the last check's while the next is on its way + const quiet=step===S.model&&(typing||C.isStandard(rec)&&runnerKey!==runnerOutKey); + $('#nb-localerrors').textContent=fieldErrors($('#nb-form'),quiet?[]:compiled.errors.filter(e=>e.step===step&&!e.shown&&!(e.unset&&!modelActed)),esc).map(e=>e.message).join(' '); + } + // A model picked, entered, or left in its field: the recipe takes it at once. What the page shows of it waits for a + // press to end, so a button pressed to leave the field does not move from under the pointer. + let pressing=false,afterPress=null; + document.addEventListener('pointerdown',()=>{pressing=true;},true); + for(const end of ['pointerup','pointercancel'])document.addEventListener(end,()=>{pressing=false;const show=afterPress;afterPress=null;if(show)setTimeout(show);},true); + function commitModel(el) { + if(document.activeElement===el&&!document.hasFocus())return; // the window lost the focus, not the field: still being typed + const rec=r(),key=el.dataset.field,value=el.value.trim(),changed=value!==(rec[key]||''); + modelActed=true;delete el.dataset.typing; + if(changed){ + if(rec.modelFormat!=='provider-id'){for(const k of ['model','userModel','evalModel'])if(typeof rec[k]==='string')rec[k]=C.bareModel(rec[k]);rec.modelFormat='provider-id';} + C.setModelOf(rec,key,value);saveDraft(); // the field's pin goes with its model + } + const show=()=>{syncServed();refreshPlan();}; // asks nothing of a recipe already checked + if(pressing)afterPress=show; + else queueMicrotask(show); + } function refreshPlan() { const rec=r(); if(C.isStandard(rec)){ @@ -982,7 +1010,7 @@ const out=runnerOut||{errors:[],notes:[]}; compiled={errors:out.errors||[],notes:out.notes||[]}; }else{compiled=C.compile(rec);} - $('#nb-localerrors').textContent=fieldErrors($('#nb-form'),compiled.errors.filter(e=>e.step===step&&!e.shown),esc).map(e=>e.message).join(' '); + localErrors(); const errors=$('#nb-errors'); if(errors){ errors.hidden=!compiled.errors.length; @@ -1172,7 +1200,7 @@ else if(b.id==='nb-next'){if(step===REVIEW){if(!compiled.errors.length)download(JSON.stringify(r(),null,2)+'\n',r().name+'.json','application/json');return;}step=nextShown(step,1);} else if(b.id==='nb-back')step=nextShown(step,-1); else if(b.id==='nb-save'){if(schema.local)openSave();return;} - else if(b.id==='nb-startover'){try{localStorage.removeItem(draftKey);}catch{}recipe=C.prefill({});savedId='';runnerOut=null;runnerKey='';step=S.benchmark;tab='select';status('Started over from the defaults.');} + else if(b.id==='nb-startover'){try{localStorage.removeItem(draftKey);}catch{}recipe=C.prefill({});savedId='';runnerOut=null;runnerKey='';modelActed=false;step=S.benchmark;tab='select';status('Started over from the defaults.');} else if(b.id==='nb-save-cancel'){$('#nb-save-dialog').close();return;} else if(b.id==='nb-saved-toggle'){renderSaved();$('#nb-saved').showModal();loadSaved();return;} else if(b.id==='nb-saved-close'){$('#nb-saved').close();return;} @@ -1191,7 +1219,7 @@ if(el.id==='nb-recipe-title'){updateSavePreview();return;} if(d.servedBy!==undefined)return; // what is typed in a Served by filters its menu: a pick, or Enter, adds it (nb-pick) if(d.stdUnsandboxed!==undefined)return; // a box's value is no tick: its change sets the recipe - if(d.providerModel && rec.modelFormat !== 'provider-id'){for(const key of ['model','userModel','evalModel'])if(typeof rec[key]==='string')rec[key]=C.bareModel(rec[key]);rec.modelFormat='provider-id';} + if(d.providerModel){d.typing='true';syncServed();localErrors();return;} // what is typed in a model field filters its list: a pick, Enter or leaving the field sets it if(d.field){const p=d.field.startsWith('param:')?C.parameters().find(p=>p.key===d.field.slice(6)):null; const value=el.type==='number'?(el.value===''?'':Number(el.value)):el.value; if(p)rec.params[p.key]=p.type==='optional-boolean'?(value==='__default__'?null:value==='true'):value; @@ -1200,7 +1228,6 @@ else if(!d.providerModel&&['model','userModel','evalModel'].includes(d.field)&&/^(openrouter|openai)\//.test(String(value))){rec.provider=C.providerOf(rec,value);rec[d.field]=C.bareModel(value); renderForm();refreshPlan();const f=root.querySelector(`[data-field="${d.field}"]`);if(f){f.focus();f.setSelectionRange(f.value.length,f.value.length);}return;} // the provider the prefix named, and whether it is set else if(d.field==='provider'){C.setChoice(rec,value);renderForm();refreshPlan();return;} // whether it is set in Settings, and the names a runner's models are sent as, follow the provider - else if(['model','simulator_model','judge_model'].includes(d.field)){C.setModelOf(rec,d.field,value);syncServed();} // the field's pin goes with its model; its Served by follows, in place else rec[d.field]=value; if(el.list?.id==='nb-paths')completeDirectory(el.value); }else if(d.stdMinutes){const t=Object.assign({},rec.timeouts);if(el.value===''||!(Number(el.value)>0))delete t[d.stdMinutes];else t[d.stdMinutes]=Number(el.value);if(Object.keys(t).length)rec.timeouts=t;else delete rec.timeouts;refreshPlan();return; @@ -1217,13 +1244,15 @@ // no cap, unsaid. It is said, and the field emptied, so that it shows what the recipe holds root.addEventListener('focusout',event=>{ const el=event.target; + if(el.dataset.providerModel)commitModel(el); // a change undone by hand since the focus fires no change event if(el.type==='number'&&(el.dataset.field||el.dataset.stdMinutes||el.dataset.benchOptSelect)&&el.validity&&el.validity.badInput){el.value='';window.nulliusNotify?.(`${el.getAttribute('aria-label')}: enter a number.`,{error:true,key:'bad-number'});} }); // a provider picked in a Served by, or slugs typed there and Enter: they join its list, after the ones there root.addEventListener('nb-pick',event=>{const role=event.target.dataset.servedBy;if(!role)return;C.addServed(r(),role,event.detail);syncServed();refreshPlan();}); root.addEventListener('change',async event=>{ const el=event.target,d=el.dataset; - if(d.custom?.endsWith(':type')){$('#nb-parameters').innerHTML=customRows(!['common','extra'].includes(tab)?tab:'');} + if(d.providerModel)commitModel(el); + else if(d.custom?.endsWith(':type')){$('#nb-parameters').innerHTML=customRows(!['common','extra'].includes(tab)?tab:'');} else if(d.stdUnsandboxed!==undefined){r().unsandboxed=el.checked;refreshPlan();} else if(d.stdVersion!==undefined){ // in place: only the card's count changes on this step, so nothing else is drawn again C.setStandardBenchmark(r(),el.value);benchTasks();render(false,false);} diff --git a/app/static/builder/model-picker.js b/app/static/model-picker.js similarity index 71% rename from app/static/builder/model-picker.js rename to app/static/model-picker.js index 53a83521..3268fbee 100644 --- a/app/static/builder/model-picker.js +++ b/app/static/model-picker.js @@ -1,9 +1,10 @@ // Provider model IDs stay verbatim; browsing a catalogue never chooses a model. // The same picker serves a model's Served by (list="nb-served"): its rows are the providers of the model the field // names (data-served-model), and a field of several takes each pick, or a slug typed as is, into its list. +// Outside the builder, data-model-picker on an input is the selector of its provider's select, in its form or judge card. (() => { - // the rows a typed query keeps: the query in the id or the name, case aside; the ones already chosen left out - const matching = (items, query, chosen = []) => items.filter(m => !chosen.includes(m.id) && (m.id + ' ' + m.name).toLowerCase().includes(query.toLowerCase())); + // the rows a typed query keeps, by the tables' search (tables.js); the ones already chosen left out + const matching = (items, query, chosen = []) => items.filter(m => !chosen.includes(m.id) && window.NulliusTable.matches(m.id + ' ' + m.name, query)); // what Enter takes: the highlighted row, else, in a field of several, the text as typed (a slug the list may lack) const entered = (items, index, text, several) => items[index] || (several && text.trim() ? {id: text.trim(), typed: true} : null); // The row and its menu share one request per model for five minutes, including failures. An in-flight request @@ -25,13 +26,22 @@ providers.subscribe = listener => listeners.add(listener); return providers; } - if (typeof module === 'object' && module.exports) { module.exports = {matching, entered, servingProviders}; return; } + // Where a provider's select says its models are: the list on its chosen option, Decision's live one, or the + // provider's catalogue. local:, a named endpoint in Settings, is custom: there. + const sourceOf = option => option?.dataset.models && !('live' in option.dataset) + ? {models: option.dataset.models.split('|').map(id => ({id, name: id}))} + : {url: option && 'live' in option.dataset ? '/settings/decision/models' : '/new-run/models', + provider: (option?.value || '').replace(/^local(?=$|:)/, 'custom'), listed: (option?.dataset.models || '').split('|').filter(Boolean)}; + if (typeof module === 'object' && module.exports) { module.exports = {matching, entered, servingProviders, sourceOf}; return; } const root = document.getElementById('nullius-builder'); - if (!root) return; - const schema = JSON.parse(document.getElementById('nb-schema').textContent); - const providers = window.NulliusServingProviders = servingProviders(nulliusFetch, schema.csrf); + const csrf = root ? JSON.parse(document.getElementById('nb-schema').textContent).csrf : document.querySelector('[name=csrf]')?.value; + const providers = root && (window.NulliusServingProviders = servingProviders(nulliusFetch, csrf)); const cache = new Map(); let active = null, serial = 0, choosing = false; const severalOf = input => input.dataset.pickerSeveral === 'true'; + const placeOf = input => { + if (root) return {url: '/new-run/models', provider: root.dataset.modelProvider}; + return sourceOf([input.closest('[data-judge-card]'), input.closest('form')].map(at => at?.querySelector(input.dataset.modelPicker)).find(Boolean)?.selectedOptions[0]); + }; function close() { if (!active) return; active.input.setAttribute('aria-expanded', 'false'); @@ -58,14 +68,17 @@ } function choose(model, input = active.input) { close(); choosing = true; + const card = input.closest('[data-judge-card]'); // a field of several hands the pick to the page, which lists it, and is left empty for the next one if (severalOf(input)) { input.value = ''; input.dispatchEvent(new CustomEvent('nb-pick', {bubbles: true, detail: model.id})); } else { input.value = model.id; + if (card) input.blur(); // autosave draws a saved field again only once it is left input.dispatchEvent(new Event('input', {bubbles: true})); input.dispatchEvent(new Event('change', {bubbles: true})); } - input.focus(); choosing = false; + if (!card) input.focus(); + choosing = false; } function paint() { if (!active) return; @@ -75,7 +88,7 @@ // no model yet, or the one the run sends not yet known (the server compiles it): no list is asked if (several && !input.dataset.servedModel) status.textContent = input.dataset.servedPending === 'true' ? 'Loading providers…' : 'Choose the model first'; else if (!result) status.textContent = several ? 'Loading providers…' : 'Loading models…'; - else if (result.ok && input.dataset.field === 'model' && JSON.parse(root.dataset.paperModels || 'null') !== null && !result.models.length) status.textContent = 'No paper models available from this provider.'; + else if (result.ok && root && input.dataset.field === 'model' && JSON.parse(root.dataset.paperModels || 'null') !== null && !result.models.length) status.textContent = 'No paper models available from this provider.'; else if (!result.ok) status.textContent = result.message || (several ? "Provider list unavailable. Enter a provider's slug by hand." : 'Model list unavailable. Enter a model ID manually.'); else { const matches = matching(result.models, query, several ? (input.dataset.chosen || '').split(',').filter(Boolean) : []); @@ -91,30 +104,34 @@ const name = document.createElement('span'); name.textContent = model.name; row.append(name); if (model.id !== model.name) { const id = document.createElement('small'); id.textContent = model.id; row.append(id); } - row.addEventListener('pointerdown', e => e.preventDefault()); row.addEventListener('click', () => choose(model)); menu.append(row); }); position(); } - async function models(provider) { - let entry = cache.get(provider); + async function models({models: given, url, provider, listed = []}) { + if (given) return {ok: true, models: given}; + const key = url + ' ' + provider; + let entry = cache.get(key); if (!entry || Date.now() - entry.at > 300000) { - entry = {at: Date.now(), promise: nulliusFetch('/new-run/models', {method: 'POST', headers: {'Content-Type': 'application/json', 'X-CSRF-Token': schema.csrf}, body: JSON.stringify({provider})}) + entry = {at: Date.now(), promise: nulliusFetch(url, {method: 'POST', headers: {'Content-Type': 'application/json', 'X-CSRF-Token': csrf}, body: JSON.stringify({provider})}) .then(r => r.json()).then(r => ({...r, models: Array.isArray(r.models) ? r.models : []})) .catch(() => ({ok: false, models: [], message: 'Model list unavailable. Enter a model ID manually.'}))}; - cache.set(provider, entry); + cache.set(key, entry); } const result = await entry.promise; - if (!result.ok) cache.delete(provider); - return result; + if (!result.ok) cache.delete(key); + // a live list that cannot be read leaves the one drawn with the page + return listed.length && !result.models.length ? {ok: true, models: listed.map(id => ({id, name: id}))} : result; } async function open(input, all = false) { close(); const menu = document.createElement('div'); menu.className = 'ui-select-menu nb-model-menu'; menu.id = input.getAttribute('aria-controls'); const several = severalOf(input); menu.setAttribute('popover', 'manual'); menu.setAttribute('role', 'listbox'); menu.setAttribute('aria-label', several ? 'Serving providers' : 'Provider models'); + // a press in the menu leaves the keyboard in the field + for (const press of ['pointerdown', 'mousedown']) menu.addEventListener(press, e => e.preventDefault()); document.body.append(menu); - const state = {input, menu, wrap: input.parentElement, several, provider: root.dataset.modelProvider, model: input.dataset.servedModel || '', query: all ? '' : input.value, result: null, items: [], index: -1}; + const state = {input, menu, wrap: input.parentElement, several, provider: root?.dataset.modelProvider, model: input.dataset.servedModel || '', query: all ? '' : input.value, result: null, items: [], index: -1}; active = state; input.setAttribute('aria-expanded', 'true'); paint(); if (menu.showPopover) menu.showPopover(); if (several) { @@ -123,18 +140,18 @@ if (active === state) { state.result = result; paint(); } return; } - const paper = input.dataset.field === 'model' ? JSON.parse(root.dataset.paperModels || 'null') : null; - const result = await models(state.provider); + const paper = root && input.dataset.field === 'model' ? JSON.parse(root.dataset.paperModels || 'null') : null; + const result = await models(placeOf(input)); state.result = paper === null || !result.ok ? result : {...result, models:Object.entries(paper) .filter(([, served])=>result.models.some(m=>m.id === served)) .map(([id, served])=>({id:root.dataset.standardModel === 'true' ? id : served, name:id === served ? id : id + ' · ' + served}))}; if (active === state) paint(); } function scan() { - if (active && (!active.input.isConnected || active.input.closest('[hidden]') || active.provider !== root.dataset.modelProvider)) close(); + if (active && (!active.input.isConnected || active.input.closest('[hidden]') || active.provider !== root?.dataset.modelProvider)) close(); // the model a Served by lists the providers of has moved (the server named the one the run sends): its rows follow else if (active && active.several && active.model !== (active.input.dataset.servedModel || '')) void open(active.input, !active.query); - root.querySelectorAll('input[list="nb-models"], input[list="nb-served"]').forEach(input => { + (root || document).querySelectorAll(root ? 'input[list="nb-models"], input[list="nb-served"]' : 'input[data-model-picker]:not([role])').forEach(input => { if (input.getAttribute('list') === 'nb-served') input.dataset.pickerSeveral = 'true'; else input.dataset.providerModel = 'true'; input.removeAttribute('list'); input.autocomplete = 'off'; input.setAttribute('role', 'combobox'); input.setAttribute('aria-autocomplete', 'list'); input.setAttribute('aria-expanded', 'false'); @@ -142,25 +159,31 @@ const wrap = document.createElement('span'); wrap.className = 'nb-model-control'; input.before(wrap); wrap.append(input); const button = document.createElement('button'); button.type = 'button'; button.className = 'nb-model-open'; button.innerHTML = ''; button.setAttribute('aria-label', severalOf(input) ? 'Browse the serving providers' : 'Browse provider models'); + // the field keeps the keyboard: pressing this is not leaving it, and ArrowDown opens the list + for (const press of ['pointerdown', 'mousedown']) button.addEventListener(press, e => e.preventDefault()); + button.tabIndex = -1; button.addEventListener('click', e => { e.preventDefault(); input.focus(); void open(input, true); }); wrap.append(button); input.addEventListener('focus', () => { if(!choosing)void open(input); }); // a field of several keeps the keyboard after a pick: a click on it opens its menu again for the next one if (severalOf(input)) input.addEventListener('click', () => { if(active?.input !== input)void open(input); }); input.addEventListener('input', () => { if(choosing)return; if (active?.input === input) { active.query = input.value; paint(); } else void open(input); }); input.addEventListener('keydown', e => { + if (e.isComposing || e.keyCode === 229) return; // an input method's own keys if (e.key === 'Escape' || e.key === 'Tab') { if(e.key === 'Escape' && active){e.preventDefault();e.stopPropagation();} close(); return; } if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); if(active?.input !== input)void open(input, true); else highlight(active.index + (e.key === 'ArrowDown' ? 1 : -1)); } if (e.key === 'Enter') { const pick = entered(active?.input === input ? active.items : [], active?.input === input ? active.index : -1, input.value, severalOf(input)); - if (!pick) return; + // the first Enter puts an open menu away (in the builder it takes the id as typed); it never submits a half-typed search + if (!pick) { if (active?.input === input) { e.preventDefault(); close(); if (root) input.dispatchEvent(new Event('change', {bubbles: true})); } return; } e.preventDefault(); choose(pick, input); } }); }); } - new MutationObserver(scan).observe(root, {childList: true, subtree: true, attributes: true, attributeFilter: ['data-model-provider', 'data-served-model']}); + if (root) new MutationObserver(scan).observe(root, {childList: true, subtree: true, attributes: true, attributeFilter: ['data-model-provider', 'data-served-model']}); document.addEventListener('pointerdown', e => { if(active && !active.wrap.contains(e.target) && !active.menu.contains(e.target))close(); }); document.addEventListener('scroll', e => { if(active && !active.menu.contains(e.target))close(); }, true); window.addEventListener('resize', close); + document.addEventListener('nullius-settings-saved', scan); // a saved field is drawn again scan(); })(); diff --git a/app/static/settings/judges.js b/app/static/settings/judges.js index a0c2eed5..64108a51 100644 --- a/app/static/settings/judges.js +++ b/app/static/settings/judges.js @@ -37,35 +37,8 @@ const modelField = card.querySelector('.st-field[id$="_MODEL"]'); modelField.hidden = !on; const model = modelField.querySelector('input.st-input'); - const list = model?.list; - if (list) { - list.replaceChildren(); - for (const value of (on?.dataset.models || '').split('|').filter(Boolean)) { - const option = document.createElement('option'); option.value = value; list.append(option); - } - } if (model) model.placeholder = on?.dataset.default || ''; } - // A provider with no list of its own here: its catalogue, asked once when the field is first used; a live list - // replaces the one drawn with the page. Typing a model still works. - const catalogues = new Map(); - async function offerCatalogue(card, model) { - const on = chosen(card); - if (!on || (on.dataset.models && !('live' in on.dataset)) || !model.list) return; - const provider = on.value.replace(/^local(?=$|:)/, 'custom'); // local:, a named endpoint, is the builder's custom: - const url = 'live' in on.dataset ? '/settings/decision/models' : '/new-run/models'; - if (!catalogues.has(url + provider)) { - catalogues.set(url + provider, nulliusFetch(url, {method: 'POST', headers: {'Content-Type': 'application/json', - 'X-CSRF-Token': document.querySelector('#settings-form [name=csrf]').value}, body: JSON.stringify({provider})}) - .then(r => { if (!r.ok) throw new Error("Model catalogue unavailable"); return r.json(); }).then(j => { if (j.error) throw new Error(j.error); return j.models || []; }).catch(() => { catalogues.delete(url + provider); return []; })); - } - const models = await catalogues.get(url + provider); - if (!models.length) return; - if (chosen(card) !== on) return; - model.list.replaceChildren(...models.map(m => { - const option = document.createElement('option'); option.value = m.id; if (m.name !== m.id) option.label = m.name; return option; - })); - } cards.forEach(card => { // Runs before autosave's listener on the form: a protocol picked here is named, so it is saved. card.addEventListener('change', event => { @@ -75,7 +48,6 @@ } if (event.target.matches('[data-picker], [data-protocol-picker]')) update(card); }); - card.addEventListener('focusin', event => { if (event.target.matches('input.st-input')) offerCatalogue(card, event.target); }); }); // Initialize after autosave records the server state, so a sole replacement // for an unavailable saved provider is persisted rather than merely displayed. diff --git a/app/static/style.css b/app/static/style.css index 04ff2132..7f6b8ae3 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -1813,6 +1813,15 @@ select.ui-select-native { display: none !important; } .ui-select-option[aria-disabled=true] { opacity: .45; cursor: default; } @media (max-width: 560px) { .ui-select-trigger { font-size: 16px; } } +/* A model field's picker (model-picker.js). */ +.nb-model-control { display: flex; position: relative; min-width: 0; } +.nb-model-open { display: grid; place-items: center; padding: 0; position: absolute; right: 1px; top: 1px; bottom: 1px; width: 32px; border: 0; background: transparent; color: var(--text-dim); border-radius: 7px; } +.nb-model-control > input[role=combobox] { width: 100%; min-width: 0; padding-right: 36px; } +.nb-model-control:has(> input[hidden]) { display: none; } +.nb-model-option { display: flex; flex-direction: column; gap: 2px; } +.nb-model-option small, .nb-model-status { color: var(--text-dim); font-size: 12px; } +.nb-model-status { padding: 8px 9px; } + /* Shared slider:
……
. --fill (0 to 1) is the filled part, kept by controls.js. .marked draws a tick at --mark (0 to 1): past it the track is dotted, a step beyond the values (No limit); .ui-range-at-mark labels the tick. .unset: no value chosen. diff --git a/app/static/tables.js b/app/static/tables.js index 50902b19..c6a8411b 100644 --- a/app/static/tables.js +++ b/app/static/tables.js @@ -2,10 +2,10 @@ into (the macros of templates/_tables.html; their styles in style.css, "the table toolkit"), and the card toolkit's (templates/_cards.html). */ window.NulliusTable = { - /* Whether `text` holds every word of `query`, in any order and case. */ + /* Whether `text` holds every word of `query`, in any order and case, - _ / : aside. */ matches(text, query) { - const t = (text ?? '').toLowerCase(); - return query.toLowerCase().split(/\s+/).every(w => t.includes(w)); + const plain = s => s.toLowerCase().replace(/[-_/:]/g, ''), t = plain(text ?? ''); + return query.split(/\s+/).every(w => t.includes(plain(w))); }, /* A header with data-type sorts its column on a click or Enter; num sorts diff --git a/app/templates/agents/entry.html b/app/templates/agents/entry.html index 80cf73ac..cf845eb0 100644 --- a/app/templates/agents/entry.html +++ b/app/templates/agents/entry.html @@ -107,7 +107,7 @@

Runs

- +
{% if kind == 'agent' %}{% endif %} @@ -120,6 +120,8 @@

Runs

{% endblock %} {% block scripts %} + + {% if kind == 'agent' %} - + {% endblock %} diff --git a/app/templates/catalogue/benchmark.html b/app/templates/catalogue/benchmark.html index 4a57c4fc..be84e2e4 100644 --- a/app/templates/catalogue/benchmark.html +++ b/app/templates/catalogue/benchmark.html @@ -93,7 +93,7 @@ {% if s.judged %} {% if providers %}{% endif %} - + {% endif %} {% if s.judged and not providers %}

The judge needs a model key first: set one in Settings.

@@ -293,4 +293,6 @@

As published

{% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %} + +{% endblock %} diff --git a/app/templates/settings/settings.html b/app/templates/settings/settings.html index 2c8aa449..92fd9257 100644 --- a/app/templates/settings/settings.html +++ b/app/templates/settings/settings.html @@ -15,7 +15,7 @@ {% set chosen = (hosts_row.shown.split(',') | map('trim') | select | list) if hosts_row else [] %} {#- mode, in a provider's editor: 'plain' is edited in place (a name, an endpoint's URL); 'key' is written, never shown, and replaced; 'optional-key' may also be removed. Elsewhere, Replace and Remove. -#} -{% macro field(r, label, writable, options=none, mode='', placeholder='', tip='') %} +{% macro field(r, label, writable, options=none, mode='', placeholder='', tip='', picker='') %} {% set plain = mode == 'plain' %}
@@ -30,7 +30,7 @@ {% if mode != 'key' %}{% endif %} {% endif %} - + {% if r.problem %}

{{ r.problem }}

{% endif %} {% if options is not none %}{% for o in options %}{% endfor %}{% endif %} {% if r.source == 'environment' %}

Also set in the process environment: the running process keeps that value until it is restarted; the file applies then.

{% endif %} @@ -223,7 +223,7 @@

Judges

Decision model {{ judge_rows('DECISION', decision_providers, decision, 'Where the Decision model is asked') }} - {{ field(by['DECISION_MODEL'], 'Model', writable, decision_providers[decision.provider].models) }} + {{ field(by['DECISION_MODEL'], 'Model', writable, picker='[data-picker]') }}
{% endif %} {% set prow = by.get('LLM_JUDGE_PROVIDER') %} @@ -231,7 +231,7 @@

Judges

LLM {{ judge_rows('LLM_JUDGE', llm_providers, llm, "The LLM judge's provider") }} - {{ field(by['LLM_JUDGE_MODEL'], 'Model', writable, []) }} + {{ field(by['LLM_JUDGE_MODEL'], 'Model', writable, picker='[data-picker]') }}
{% endif %} @@ -473,6 +473,8 @@

General

+ + diff --git a/app/ui_tests/test_judge_cards.py b/app/ui_tests/test_judge_cards.py index 9669a753..d115d1bb 100644 --- a/app/ui_tests/test_judge_cards.py +++ b/app/ui_tests/test_judge_cards.py @@ -24,7 +24,7 @@ provider.kind = '[data-picker]'; const protocol = select(options([['chat', {}, 'OpenAI Chat Completions'], ['messages', {}, 'Anthropic Messages']]), {value: 'chat'}); protocol.kind = '[data-protocol-picker]'; protocol.dataset.name = 'value:LLM_JUDGE_PROTOCOL'; protocol.field = {hidden: false}; -const model = {placeholder: '', list: {replaceChildren() {}}}, modelField = {hidden: false, querySelector: () => model}; +const model = {placeholder: ''}, modelField = {hidden: false, querySelector: () => model}; const via = {hidden: false, textContent: ''}, none = {hidden: false}; const parts = {'[data-picker]': provider, '[data-protocol-picker]': protocol, '[data-judge-via]': via, '[data-no-judge-provider]': none, '.st-field[id$="_MODEL"]': modelField}; const listeners = {}, card = {querySelector: s => parts[s], addEventListener(t, f) { listeners[t] = f; }}; @@ -46,22 +46,6 @@ process.stdout.write(JSON.stringify(out)); ''' -# Decision on OpenRouter: the list drawn with the page, then the live one asked when the field is first used. -LIVE = PROGRAM.split("require(process.argv[1]);")[0].replace( - "['openrouter', {available: 'true', protocol: 'chat', protocols: 'chat'}, 'OpenRouter']", - "['openrouter', {available: 'true', protocol: 'systemone', protocols: 'systemone|decisions', models: '~typesafe/jev-latest', live: ''}, 'OpenRouter']" -).replace("const model = {placeholder: '', list: {replaceChildren() {}}}", - "const shown = []; const model = {placeholder: '', matches: () => true, list: {replaceChildren(...o) { shown.push(o.map(x => x.value)); }, append() {}}}") + r''' -const asked = []; -global.nulliusFetch = (url, init) => { asked.push([url, JSON.parse(init.body)]); - return Promise.resolve({ok: true, json: () => Promise.resolve({ok: true, models: [{id: '~typesafe/jev-latest', name: '~typesafe/jev-latest'}, {id: 'b/decider:free', name: 'b/decider:free'}]})}); }; -document.querySelector = () => ({value: 'token'}); -require(process.argv[1]); -doc.DOMContentLoaded(); provider.value = 'openrouter'; listeners.change({target: provider}); -listeners.focusin({target: model}); -setTimeout(() => { listeners.focusin({target: model}); setTimeout(() => process.stdout.write(JSON.stringify({asked, shown: shown.slice(-2)}))); }); -''' - class JudgeCard(unittest.TestCase): @classmethod @@ -83,11 +67,6 @@ def test_the_protocol_follows_the_provider_and_is_saved_only_once_chosen(self): self.assertEqual(got[6], {"provider": "", "hidden": True, "protocol": "messages", "named": "", "protocolRow": False, "via": "", "none": True, "model": False}) # none left: Add a provider - def test_decision_judge_on_openrouter_asks_the_live_list_once_when_the_field_is_used(self): - got = json.loads(subprocess.run([self.node, "-e", LIVE, str(SCRIPT)], capture_output=True, text=True, check=True).stdout) - self.assertEqual(got["asked"], [["/settings/decision/models", {"provider": "openrouter"}]]) # once, for both uses - self.assertEqual(got["shown"], [["~typesafe/jev-latest", "b/decider:free"]] * 2) - if __name__ == "__main__": unittest.main() diff --git a/app/ui_tests/test_served_by_builder.py b/app/ui_tests/test_served_by_builder.py index 437c5e1f..7abac169 100644 --- a/app/ui_tests/test_served_by_builder.py +++ b/app/ui_tests/test_served_by_builder.py @@ -75,6 +75,9 @@ def test_the_compile_route_gives_each_fields_model_as_the_run_sends_it(self): 'model': 'gpt-4o', 'limit': 1, 'concurrency': 1, 'where': 'local'} response = client.post('/new-run/runner', json={'recipe': recipe}, headers={'X-CSRF-Token': 'served-test-token'}) self.assertEqual(response.json['served_models']['model'], 'openai/gpt-4o-2024-08-06') + recipe.update(model_choice='any', model='qwen 3') # no model ID: there is nothing to ask the providers of + response = client.post('/new-run/runner', json={'recipe': recipe}, headers={'X-CSRF-Token': 'served-test-token'}) + self.assertIsNone(response.json['served_models']['model']) class TheRows(CompilerCase): @@ -157,6 +160,12 @@ def test_a_model_change_asks_once_and_an_old_list_never_draws_its_row(self): 'stale': [[], old_first, next_model], 'final': [False, next_model], 'requests': ['openai/gpt-4o-2024-08-06', next_model], 'pins': None}) + def test_a_model_being_typed_has_no_row_until_it_is_set(self): + out = self.js(self.SETUP.replace('esc,providers,', 'esc,providers,typing:role=>typed===role,').replace('const rows=', 'let typed="";const rows=') + + 'const got=[];C.addServed(r,"model","openai");for(typed of ["","model","judge",""]){rows.sync();got.push([label.hidden,seen().chips]);}' + 'process.stdout.write(JSON.stringify(got));') + self.assertEqual(out, [[hidden, ['openai']] for hidden in (False, True, False, False)]) + def test_a_failed_compile_keeps_the_model_the_server_named(self): """A compile that failed names no model: the row keeps the one the server last named for the same recipe (a pin added in between), waits while none is known (a failed first compile, or a compile that names none), and takes @@ -199,7 +208,7 @@ def test_a_pin_failure_keeps_an_overlapping_compiles_models_in_either_order(self class ThePicker(unittest.TestCase): """model-picker.js, as the Model row and each Served by use it: what typing keeps, and what Enter takes.""" - PICKER = Path(__file__).resolve().parents[1] / 'static' / 'builder' / 'model-picker.js' + PICKER = Path(__file__).resolve().parents[1] / 'static' / 'model-picker.js' ROWS = [{'id': 'deepinfra/fp8', 'name': 'DeepInfra · fp8'}, {'id': 'together', 'name': 'Together · fp8'}, {'id': 'novita/bf16', 'name': 'Novita · bf16'}] @classmethod @@ -209,7 +218,8 @@ def setUpClass(cls): raise unittest.SkipTest('Node is required for the picker') def js(self, code): - program = 'const P=require(' + json.dumps(str(self.PICKER)) + ');const ROWS=' + json.dumps(self.ROWS) + ';\n' + code + program = ('global.window={};global.document={readyState:"loading",addEventListener(){}};require(' + + json.dumps(str(self.PICKER.with_name('tables.js'))) + ');const P=require(' + json.dumps(str(self.PICKER)) + ');const ROWS=' + json.dumps(self.ROWS) + ';\n' + code) return json.loads(subprocess.run([self.node, '-'], input=program, check=True, capture_output=True, text=True).stdout) def test_typing_filters_a_models_providers(self): @@ -217,6 +227,22 @@ def test_typing_filters_a_models_providers(self): 'ids(P.matching(ROWS,"fp8")),ids(P.matching(ROWS,"fp8",["deepinfra/fp8"])),ids(P.matching(ROWS,"")).length,ids(P.matching(ROWS,"zz"))]));') self.assertEqual(out, [['novita/bf16'], ['deepinfra/fp8'], ['deepinfra/fp8', 'together'], ['together'], 3, []]) + def test_a_model_is_found_by_its_words_in_any_order_whatever_joins_them(self): + rows = [{'id': 'qwen/qwen-2.5-coder-32b-instruct', 'name': 'Qwen2.5 Coder 32B Instruct'}, {'id': 'qwen/qwen3-8b', 'name': 'Qwen: Qwen3 8B'}] + for query in ('Qwen 32b', '32B qwen', 'qwen 2.5 32b', 'qwen_2.5 32b', 'qwen/qwen-2.5', ' qwen2.5 '): + with self.subTest(query=query): + out = self.js(f'process.stdout.write(JSON.stringify(P.matching({json.dumps(rows)},{json.dumps(query)}).map(m=>m.id)));') + self.assertEqual(out, [rows[0]['id']]) + rows.append({'id': 'qwen/qwen3.6-35b', 'name': 'Qwen3.6 35B'}) + self.assertEqual(self.js(f'process.stdout.write(JSON.stringify(P.matching({json.dumps(rows)},"qwen 3.5")));'), []) # a version's dot counts: 35b is not 3.5 + + def test_a_provider_names_its_own_list_its_live_one_or_its_catalogue(self): + out = self.js('const at=(value,dataset)=>P.sourceOf({value,dataset});process.stdout.write(JSON.stringify([' + 'at("typesafe",{models:"a|b"}).models.map(m=>m.id),at("openrouter",{models:"a",live:""}),at("local:lab",{}),at("openai",{})]));') + self.assertEqual(out, [['a', 'b'], {'url': '/settings/decision/models', 'provider': 'openrouter', 'listed': ['a']}, + {'url': '/new-run/models', 'provider': 'custom:lab', 'listed': []}, + {'url': '/new-run/models', 'provider': 'openai', 'listed': []}]) + def test_enter_takes_a_slug_the_list_lacks_in_a_field_of_several(self): out = self.js('process.stdout.write(JSON.stringify([P.entered([],-1," my-provider/fp8 ",true),P.entered(ROWS,1,"x",true),' 'P.entered([],-1,"x",false),P.entered([],-1," ",true),P.entered(ROWS,-1,"gpt-4o",false)]));')