diff --git a/Templates/OpenBench/pipeline_edit.html b/Templates/OpenBench/pipeline_edit.html index b741075..afef463 100644 --- a/Templates/OpenBench/pipeline_edit.html +++ b/Templates/OpenBench/pipeline_edit.html @@ -4,78 +4,122 @@
{% if pipeline %}{{ pipeline.name }}{% else %}Pipelines{% endif %}

{% if pipeline %}Edit pipeline{% else %}New pipeline{% endif %}

-

Steps run one after another. How a step ends decides which step comes next

+

Draw what runs, and what starts when it ends

{% endblock %} {% block content %} -
+ {% csrf_token %}
-

General

-
-
-
- - -
-
- - -
-
- - -
-
- - +
+
+ + +
+
+ +
+ + +
-
-
-

Steps

- +
+ +
+

Flow

+
+
+ +
+

-
+ +
+
-
-

What happens next

- -
-
-
- -
-
-

Checks

- -
+

Checks

    {% for issue in issues %}
  • @@ -86,14 +130,28 @@
-
+
+
+ Limits, so that a loop can never run forever +
+
+ + +
+
+ + +
+
+
+
+ +
Cancel
- - {{ graph|json_script:"graph-data" }} {{ meta|json_script:"meta-data" }} @@ -101,47 +159,107 @@ (function () { 'use strict'; - const meta = JSON.parse(document.getElementById('meta-data').textContent); - const parsed = JSON.parse(document.getElementById('graph-data').textContent); - const token = document.querySelector('#pl-form input[name=csrfmiddlewaretoken]').value; + const NS = 'http://www.w3.org/2000/svg'; - const isObj = value => value !== null && typeof value === 'object' && !Array.isArray(value); - const seed = isObj(parsed) ? parsed : {}; - const pairsOf = obj => Object.entries(isObj(obj) ? obj : {}).map(([key, value]) => [key, String(value)]); + const meta = JSON.parse(document.getElementById('meta-data').textContent); + const seed = JSON.parse(document.getElementById('graph-data').textContent); + const form = document.getElementById('pl-form'); + const token = form.querySelector('input[name=csrfmiddlewaretoken]').value; - const KIND_LABELS = { TEST : 'Test (SPRT or fixed games)', TUNE : 'Tune (SPSA)', DATAGEN : 'Datagen' }; - const OUTCOME_LABELS = { passed : 'it passes', failed : 'it fails', stopped : 'it is stopped', any : 'it ends, however it ends' }; + const stage = document.getElementById('pl-stage'); + const menu = document.getElementById('pl-menu'); + const panel = document.getElementById('pl-panel'); + const hint = document.getElementById('pl-hint'); + const checks = document.getElementById('pl-checks'); + + const isObj = value => value !== null && typeof value === 'object' && !Array.isArray(value); + const root = isObj(seed) ? seed : {}; + + const texts = obj => { + const out = {}; + if (isObj(obj)) Object.keys(obj).forEach(key => { out[key] = String(obj[key]); }); + return out; + }; + + // Words + + const OUTCOME_TEXT = { passed : 'it passes', failed : 'it fails', stopped : 'it is stopped', any : 'it ends, however it ends' }; + const MENU_TEXT = { passed : 'If it passes', failed : 'If it fails', stopped : 'If it is stopped', any : 'However it ends' }; + const MENU_ICON = { passed : 'fa-check', failed : 'fa-xmark', stopped : 'fa-stop', any : 'fa-arrows-rotate' }; + const KIND_LABEL = { TEST : 'Test (SPRT or fixed games)', TUNE : 'Tune (SPSA)', DATAGEN : 'Datagen' }; + const IMPOSSIBLE = { TUNE : ['failed'], DATAGEN : ['failed'] }; // A finished tune or datagen always passes + const OPTIONAL = ['dev_bench', 'base_bench']; + + const LABEL = { + engine : 'Engine', repo : 'Repository', branch : 'Branch', network : 'Network', options : 'UCI options', + time_control : 'Time control', bench : 'Bench', + book_name : 'Opening book', upload_pgns : 'Upload PGNs', priority : 'Priority', throughput : 'Throughput', + syzygy_wdl : 'Syzygy WDL', syzygy_adj : 'Syzygy adjudication', win_adj : 'Win adjudication', draw_adj : 'Draw adjudication', + workload_size : 'Games per workload', test_mode : 'Mode', test_bounds : 'SPRT bounds', + test_confidence : 'SPRT confidence', test_max_games : 'Number of games', + spsa_alpha : 'Alpha', spsa_gamma : 'Gamma', spsa_A_ratio : 'A ratio', spsa_iterations : 'Iterations', + spsa_pairs_per : 'Pairs per iteration', spsa_reporting_type : 'Reporting', spsa_distribution_type : 'Distribution', + spsa_inputs : 'Parameters', + datagen_max_games : 'Games', datagen_custom_genfens : 'Custom genfens', datagen_play_reverses : 'Play reverses', + }; + + function label(key) { + const side = key.startsWith('dev_') ? 'dev_' : key.startsWith('base_') ? 'base_' : ''; + return LABEL[key] || LABEL[key.slice(side.length)] || key; + } + + function fullLabel(key) { + const side = key.startsWith('dev_') ? 'Dev ' : key.startsWith('base_') ? 'Base ' : ''; + return side + label(key).toLowerCase(); + } + + const GROUP_ORDER = ['Match', 'Dev', 'Base', 'SPSA', 'Datagen', 'Advanced']; + const GROUP_TITLE = { + Match : 'Games', Dev : 'Dev (the change)', Base : 'Base (what it is compared with)', + SPSA : 'SPSA', Datagen : 'Datagen', Advanced : 'Advanced', + }; + + function groupOf(key) { + if (key.startsWith('dev_')) return 'Dev'; + if (key.startsWith('base_')) return 'Base'; + if (key.startsWith('spsa_')) return 'SPSA'; + if (key.startsWith('datagen_')) return 'Datagen'; + if (key.startsWith('test_') || key === 'book_name' || key === 'workload_size') return 'Match'; + return 'Advanced'; + } + + const CHOICES = { test_mode : ['SPRT', 'GAMES'], upload_pgns : ['FALSE', 'TRUE'] }; + const LONG = ['spsa_inputs', 'datagen_custom_genfens']; + + // The model: what the editor is showing, which build() turns back into a graph const model = { - start : typeof seed.start === 'string' ? seed.start : '', - max_visits : seed.max_visits == null ? '' : String(seed.max_visits), - max_steps : seed.max_steps == null ? '' : String(seed.max_steps), - steps : Object.entries(isObj(seed.steps) ? seed.steps : {}).map(([id, step]) => ({ + start : typeof root.start === 'string' ? root.start : '', + max_visits : root.max_visits == null ? '' : String(root.max_visits), + max_steps : root.max_steps == null ? '' : String(root.max_steps), + steps : Object.entries(isObj(root.steps) ? root.steps : {}).map(([id, step]) => ({ id : id, name : (isObj(step) && step.name) || id, kind : (isObj(step) && step.kind) || 'TEST', - payload : pairsOf(isObj(step) ? step.payload : {}), + payload : texts(isObj(step) ? step.payload : {}), msg : '', })), - edges : (Array.isArray(seed.edges) ? seed.edges : []).filter(isObj).map(edge => ({ + edges : (Array.isArray(root.edges) ? root.edges : []).filter(isObj).map(edge => ({ from : edge.from, on : edge.on, to : edge.to == null ? '' : edge.to, - set : pairsOf(edge.set), + set : texts(edge.set), })), }; - const defaultsFor = kind => pairsOf(meta.defaults[kind]); - const stepName = step => step.name || step.id; + const sel = { step : null, edge : null }; + let lastIssues = []; - if (!model.steps.length) { - model.steps.push({ id : 'step1', name : 'Step 1', kind : 'TEST', payload : defaultsFor('TEST'), msg : '' }); - } - if (!model.steps.some(step => step.id === model.start)) { - model.start = model.steps[0].id; - } + const stepById = id => model.steps.find(step => step.id === id); + const nameOf = step => (step && (step.name || step.id)) || ''; + + // Small DOM helpers. Text always goes in as text, never as HTML - // Small DOM helper. Text always goes in as text, never as HTML function el(tag, attrs, ...kids) { const node = document.createElement(tag); for (const [key, value] of Object.entries(attrs || {})) { @@ -155,12 +273,43 @@ return node; } - function button(label, handler, cls) { - const node = el('button', { type : 'button', class : 'anchorbutton ' + (cls || 'btn-start') + ' pl-small' }, label); + function svgEl(tag, attrs, ...kids) { + const node = document.createElementNS(NS, tag); + for (const [key, value] of Object.entries(attrs || {})) node.setAttribute(key, value); + kids.forEach(kid => node.append(kid)); + return node; + } + + function button(content, handler, cls) { + const node = el('button', { type : 'button', class : 'anchorbutton ' + (cls || 'btn-blue') + ' ed-small' }, content); node.addEventListener('click', handler); return node; } + // Steps and what they need + + function needed(step) { + const keys = (meta.required[step.kind] || []).slice(); + if (step.kind === 'TEST') { + const mode = step.payload.test_mode || 'SPRT'; + (meta.conditional[mode] || []).forEach(key => keys.push(key)); + } + return keys; + } + + function fieldsFor(step) { + const keys = needed(step); + OPTIONAL.forEach(key => { if (key === 'dev_bench' || step.kind !== 'TUNE') keys.push(key); }); + return keys.filter((key, index) => keys.indexOf(key) === index); + } + + function scaffold(step) { + const defaults = meta.defaults[step.kind] || {}; + needed(step).forEach(key => { + if (!(key in step.payload)) step.payload[key] = defaults[key] == null ? '' : String(defaults[key]); + }); + } + function nextId() { const taken = new Set(model.steps.map(step => step.id)); let n = model.steps.length + 1; @@ -168,229 +317,48 @@ return 'step' + n; } - // The settings that a step has to have, given its kind and test mode - function needed(step) { - const keys = (meta.required[step.kind] || []).slice(); - if (step.kind === 'TEST') { - const found = step.payload.find(pair => pair[0].trim() === 'test_mode'); - const mode = (found && found[1].trim()) || 'SPRT'; - (meta.conditional[mode] || []).forEach(key => keys.push(key)); - } - return keys; + // A step that follows another starts out as a copy of it: the next one is usually the same test, longer + + function newStep(kind, from) { + const source = from && from.kind === kind ? from.payload : meta.defaults[kind]; + const step = { id : nextId(), name : 'Step ' + (model.steps.length + 1), kind : kind, payload : texts(source), msg : '' }; + scaffold(step); + model.steps.push(step); + return step; } - function scaffold(step) { - const have = new Set(step.payload.map(pair => pair[0].trim())); - const defaults = meta.defaults[step.kind] || {}; - needed(step).forEach(key => { - if (!have.has(key)) step.payload.push([key, defaults[key] == null ? '' : defaults[key]]); - }); + function changeKind(step, kind) { + const allowed = new Set(meta.allowed); + const kept = {}; + Object.keys(step.payload).forEach(key => { if (allowed.has(key)) kept[key] = step.payload[key]; }); + step.kind = kind; + step.payload = Object.assign(texts(meta.defaults[kind]), kept); + scaffold(step); } - // Editor for a list of [ setting, value ] pairs, changed in place - function kvEditor(pairs, onChange, isRequired) { - - const box = el('div'); - - const draw = () => { - box.replaceChildren(); - pairs.forEach((pair, index) => { - - const key = el('input', { placeholder : 'setting', list : 'pl-keys', spellcheck : 'false', 'aria-label' : 'Setting' }); - const val = el('textarea', { rows : String(Math.min(6, pair[1].split('\n').length)), spellcheck : 'false', 'aria-label' : 'Value' }); - key.value = pair[0]; - val.value = pair[1]; - - const flag = () => val.classList.toggle('pl-empty', !!isRequired && isRequired(pair[0]) && pair[1].trim() === ''); - key.addEventListener('input', () => { pair[0] = key.value; flag(); onChange(); }); - val.addEventListener('input', () => { pair[1] = val.value; flag(); onChange(); }); - flag(); - - const del = button('\u00d7', () => { pairs.splice(index, 1); draw(); onChange(); }, 'btn-red'); - del.title = 'Remove this setting'; - - box.append(el('div', { class : 'pl-kv-row' }, key, val, del)); - }); - }; - - draw(); - return el('div', {}, box, button('Add setting', () => { pairs.push(['', '']); draw(); onChange(); })); + function removeStep(step) { + model.steps.splice(model.steps.indexOf(step), 1); + model.edges = model.edges.filter(edge => edge.from !== step.id && edge.to !== step.id); + if (model.start === step.id) model.start = model.steps[0].id; + select(model.start); + changed(); } - function fillSelect(select, value, allowEnd) { - select.replaceChildren(); - if (allowEnd) select.append(el('option', { value : '' }, 'End the pipeline')); - model.steps.forEach(step => select.append(el('option', { value : step.id }, stepName(step)))); - select.value = value; - } + // Turn the model back into a graph - function stepSelect(value, allowEnd, onChange) { - const select = el('select', { class : 'pl-step-select', 'data-end' : allowEnd ? '1' : '0' }); - fillSelect(select, value, allowEnd); - select.addEventListener('change', () => onChange(select.value)); - return select; - } - - function refreshSelects() { - document.querySelectorAll('.pl-step-select').forEach(select => { - fillSelect(select, select.value, select.dataset.end === '1'); - }); - } - - // Steps - const stepsBox = document.getElementById('pl-steps'); - - function drawSteps() { - - stepsBox.replaceChildren(); - - model.steps.forEach(step => { - - const name = el('input', { maxlength : '64', 'aria-label' : 'Step name' }); - name.value = step.name; - name.addEventListener('input', () => { step.name = name.value; refreshSelects(); }); - - const kind = el('select', { 'aria-label' : 'Kind' }, - meta.kinds.map(k => el('option', { value : k, selected : k === step.kind }, KIND_LABELS[k] || k))); - kind.addEventListener('change', () => { step.kind = kind.value; drawSteps(); }); - - const note = el('div', { class : 'pl-note' }); - const refreshNote = () => { - const have = new Set(step.payload.map(pair => pair[0].trim())); - const missing = needed(step).filter(key => !have.has(key)); - note.textContent = missing.length ? 'Missing settings: ' + missing.join(', ') : ''; - }; - - const editor = kvEditor(step.payload, refreshNote, key => needed(step).includes(key.trim())); - refreshNote(); - - const head = el('div', { class : 'pl-box-head' }, name, kind, - button('Add the missing settings', () => { scaffold(step); drawSteps(); })); - - if (step.kind === 'TEST') { - - const number = el('input', { type : 'number', min : '1', placeholder : 'Test #', 'aria-label' : 'Test number', style : 'width: 6.5rem' }); - const copy = button('Copy settings from a test', async () => { - - const id = parseInt(number.value, 10); - if (!id) { step.msg = 'Type the number of a test first'; drawSteps(); return; } - - try { - const response = await fetch('/pipelines/test-fields/' + id + '/', { credentials : 'same-origin' }); - const data = await response.json(); - - if (!response.ok) { step.msg = data.error || 'Could not copy that test'; drawSteps(); return; } - - step.payload.splice(0, step.payload.length, ...pairsOf(data.payload)); - scaffold(step); - step.msg = 'Copied from test #' + id + '. Check the branches before saving'; - } catch (error) { - step.msg = 'Could not copy that test'; - } - - drawSteps(); - }); - - head.append(number, copy); - } - - const remove = button('Remove step', () => { - model.steps.splice(model.steps.indexOf(step), 1); - model.edges = model.edges.filter(edge => edge.from !== step.id && edge.to !== step.id); - if (model.start === step.id) model.start = model.steps[0].id; - drawAll(); - }, 'btn-red'); - remove.disabled = model.steps.length < 2; - head.append(remove); - - stepsBox.append(el('div', { class : 'pl-box' }, head, - step.msg ? el('div', { class : 'pl-note' }, step.msg) : null, note, editor)); - }); - } - - // Rules between steps - const edgesBox = document.getElementById('pl-edges'); - - function drawEdges() { - - edgesBox.replaceChildren(); - - if (!model.edges.length) { - edgesBox.append(el('p', { class : 'pl-note' }, 'No rules yet, so the pipeline ends after its first step.')); - } - - model.edges.forEach(edge => { - - const from = stepSelect(edge.from, false, value => { edge.from = value; }); - const to = stepSelect(edge.to, true, value => { edge.to = value; }); - const on = el('select', { 'aria-label' : 'Outcome' }, - meta.outcomes.map(o => el('option', { value : o, selected : o === edge.on }, OUTCOME_LABELS[o] || o))); - on.addEventListener('change', () => { edge.on = on.value; }); - - const remove = button('Remove', () => { - model.edges.splice(model.edges.indexOf(edge), 1); - drawEdges(); - }, 'btn-red'); - - const row = el('div', { class : 'pl-edge' }, 'When', from, 'ends and', on, 'then', to, remove); - const sub = el('details', { open : edge.set.length > 0 }, - el('summary', {}, 'Change settings for the step that starts'), - kvEditor(edge.set, () => {}, null)); - - edgesBox.append(el('div', { class : 'pl-box', style : 'margin: 0 0 .9rem' }, row, sub)); - }); - } - - const startSelect = document.getElementById('pl-start'); - startSelect.addEventListener('change', () => { model.start = startSelect.value; }); - - function drawAll() { - drawSteps(); - drawEdges(); - fillSelect(startSelect, model.start, false); - } - - // General settings - const nameField = document.getElementById('pl-name'); - const visitsField = document.getElementById('pl-visits'); - const totalField = document.getElementById('pl-total'); - - visitsField.max = meta.limits.visits; - totalField.max = meta.limits.total; - visitsField.value = model.max_visits; - totalField.value = model.max_steps; - visitsField.addEventListener('input', () => { model.max_visits = visitsField.value; }); - totalField.addEventListener('input', () => { model.max_steps = totalField.value; }); - - const keyList = document.getElementById('pl-keys'); - meta.allowed.forEach(key => keyList.append(el('option', { value : key }))); - - document.getElementById('pl-add-step').addEventListener('click', () => { - if (model.steps.length >= meta.limits.steps) return; - model.steps.push({ id : nextId(), name : 'Step ' + (model.steps.length + 1), kind : 'TEST', payload : defaultsFor('TEST'), msg : '' }); - drawAll(); - }); - - document.getElementById('pl-add-edge').addEventListener('click', () => { - const last = model.steps[model.steps.length - 1]; - model.edges.push({ from : model.steps[0].id, on : 'passed', to : model.steps.length > 1 ? last.id : '', set : [] }); - drawEdges(); - }); - - // Turn the editor back into a graph function build() { const steps = {}; model.steps.forEach(step => { const payload = {}; - step.payload.forEach(([key, value]) => { if (key.trim()) payload[key.trim()] = value; }); + Object.keys(step.payload).forEach(key => { if (key.trim()) payload[key.trim()] = step.payload[key]; }); steps[step.id] = { name : step.name, kind : step.kind, payload : payload }; }); const edges = model.edges.map(edge => { const out = { from : edge.from, on : edge.on, to : edge.to === '' ? null : edge.to }; const set = {}; - edge.set.forEach(([key, value]) => { if (key.trim()) set[key.trim()] = value; }); + Object.keys(edge.set).forEach(key => { if (key.trim()) set[key.trim()] = edge.set[key]; }); if (Object.keys(set).length) out.set = set; return out; }); @@ -403,50 +371,521 @@ return graph; } - // Checks, from the server, so that they are the very same rules that a run uses - const checksBox = document.getElementById('pl-checks'); + // The flow, drawn by the server, with the very same code that draws a run - function showIssues(issues) { + let timer = null; + let ticket = 0; - checksBox.replaceChildren(); - - if (!issues.length) { - checksBox.append(el('li', { class : 'pl-check' }, el('span', {}, 'No problems found'))); - return; - } - - const names = {}; - model.steps.forEach(step => { names[step.id] = stepName(step); }); - - issues.forEach(issue => { - const icon = issue.level === 'error' ? 'fa-circle-exclamation' : issue.level === 'warning' ? 'fa-triangle-exclamation' : 'fa-circle-info'; - const who = typeof issue.step === 'string' ? (names[issue.step] || issue.step) : ''; - checksBox.append(el('li', { class : 'pl-check pl-check-' + issue.level }, - el('i', { class : 'fa-solid ' + icon }), ' ', - el('span', {}, who ? el('strong', {}, who) : null, who ? ' ' : null, issue.message))); - }); + function changed() { + drawHint(); + clearTimeout(timer); + timer = setTimeout(refresh, 250); } - document.getElementById('pl-check').addEventListener('click', async () => { + async function refresh() { + const mine = ++ticket; const body = new FormData(); body.append('csrfmiddlewaretoken', token); body.append('graph', JSON.stringify(build())); try { - const response = await fetch('/pipelines/check/', { method : 'POST', body : body, credentials : 'same-origin' }); + const response = await fetch('/pipelines/preview/', { method : 'POST', body : body, credentials : 'same-origin' }); const data = await response.json(); + if (mine !== ticket) return; + drawCanvas(data.svg || ''); showIssues(data.issues || [{ level : 'error', step : null, message : data.error || 'The check failed' }]); } catch (error) { - showIssues([{ level : 'error', step : null, message : 'The check could not be done' }]); + if (mine !== ticket) return; + showIssues([{ level : 'error', step : null, message : 'The flow could not be drawn. Reload the page and try again' }]); } + } + + const nodeFor = id => Array.from(stage.querySelectorAll('g.pl-node')).find(node => node.getAttribute('data-step') === id); + const edgeFor = index => Array.from(stage.querySelectorAll('g.pl-edge')).find(node => node.getAttribute('data-edge') === String(index)); + + function drawCanvas(markup) { + + closeMenu(); + + if (!markup) { + stage.replaceChildren(el('p', { class : 'ed-note' }, 'The flow cannot be drawn yet. The checks below say why.')); + return; + } + + stage.innerHTML = markup; // Escaped by the server, which is the only place that writes it + const svg = stage.querySelector('svg'); + if (!svg) return; + + // A wide invisible copy of every arrow, so that a thin line is easy to hit + svg.querySelectorAll('g.pl-edge').forEach(group => { + const line = group.querySelector('.pl-line'); + if (!line) return; + const hit = line.cloneNode(false); + hit.setAttribute('class', 'ed-hit'); + hit.removeAttribute('marker-end'); + group.insertBefore(hit, line); + }); + + // A + on top of every step: this is where the next step comes from + svg.querySelectorAll('g.pl-node').forEach(group => { + const box = group.querySelector('.pl-box'); + if (!box) return; + const x = Number(box.getAttribute('x')) + Number(box.getAttribute('width')) / 2; + const y = Number(box.getAttribute('y')); + svg.append(svgEl('g', { class : 'ed-plus', 'data-plus' : group.getAttribute('data-step') }, + svgEl('title', {}, 'Add what happens next'), + svgEl('circle', { cx : x, cy : y, r : 11 }), + svgEl('path', { d : 'M' + (x - 5) + ' ' + y + ' h10 M' + x + ' ' + (y - 5) + ' v10' }))); + }); + + applyMarks(); + } + + function applyMarks() { + + stage.querySelectorAll('.ed-sel, .ed-bad, .ed-warn').forEach(node => node.classList.remove('ed-sel', 'ed-bad', 'ed-warn')); + + const worst = {}; + lastIssues.forEach(issue => { + if (typeof issue.step !== 'string') return; + if (issue.level === 'error') worst[issue.step] = 'ed-bad'; + else if (issue.level === 'warning' && !worst[issue.step]) worst[issue.step] = 'ed-warn'; + }); + Object.keys(worst).forEach(id => { const node = nodeFor(id); if (node) node.classList.add(worst[id]); }); + + if (sel.step !== null) { const node = nodeFor(sel.step); if (node) node.classList.add('ed-sel'); } + if (sel.edge !== null) { const node = edgeFor(sel.edge); if (node) node.classList.add('ed-sel'); } + } + + stage.addEventListener('click', event => { + + const plus = event.target.closest('.ed-plus'); + if (plus) { openMenu(plus.getAttribute('data-plus')); return; } + + const edge = event.target.closest('g.pl-edge'); + if (edge) { selectEdge(Number(edge.getAttribute('data-edge'))); return; } + + const node = event.target.closest('g.pl-node'); + if (node) { select(node.getAttribute('data-step')); return; } + + closeMenu(); }); - document.getElementById('pl-form').addEventListener('submit', () => { + // The + menu: what should start, and when + + function closeMenu() { menu.hidden = true; } + + function openMenu(stepId) { + + const step = stepById(stepId); + const node = nodeFor(stepId); + const box = node && node.querySelector('.pl-box'); + if (!step || !box) return; + + const x = Number(box.getAttribute('x')) + Number(box.getAttribute('width')) / 2; + const y = Number(box.getAttribute('y')); + + menu.replaceChildren(el('div', { class : 'ed-menu-title' }, 'After ' + nameOf(step))); + + meta.outcomes.filter(outcome => !(IMPOSSIBLE[step.kind] || []).includes(outcome)).forEach(outcome => { + const exists = model.edges.some(edge => edge.from === stepId && edge.on === outcome); + const item = el('button', { type : 'button', class : 'ed-menu-item ed-menu-' + outcome, role : 'menuitem' }, + el('i', { class : 'fa-solid ' + MENU_ICON[outcome] }), MENU_TEXT[outcome] || outcome, + exists ? el('small', {}, 'open') : null); + item.addEventListener('click', () => chain(stepId, outcome)); + menu.append(item); + }); + + menu.style.left = Math.max(4, x - 96) + 'px'; + menu.style.top = (y + 20) + 'px'; + menu.hidden = false; + } + + function chain(stepId, outcome) { + + const from = stepById(stepId); + const existing = model.edges.find(edge => edge.from === stepId && edge.on === outcome); + + if (existing) { selectEdge(model.edges.indexOf(existing)); return; } + + if (model.steps.length >= meta.limits.steps) { + flash('A pipeline may have at most ' + meta.limits.steps + ' steps'); + closeMenu(); + return; + } + + const next = newStep(from.kind, from); + model.edges.push({ from : stepId, on : outcome, to : next.id, set : {} }); + select(next.id); + changed(); + } + + document.addEventListener('click', event => { + if (!event.target.closest('.ed-plus, #pl-menu')) closeMenu(); + }); + + document.addEventListener('keydown', event => { + if (event.key === 'Escape') closeMenu(); + }); + + // Selecting + + function select(id) { + sel.step = id; + sel.edge = null; + closeMenu(); + drawPanel(); + applyMarks(); + } + + function selectEdge(index) { + + const edge = model.edges[index]; + if (!edge) return; + + sel.step = edge.from; + sel.edge = index; + closeMenu(); + drawPanel(); + applyMarks(); + + const row = panel.querySelector('.ed-rule.ed-picked'); + if (row) row.scrollIntoView({ block : 'nearest' }); + } + + function markRows() { + panel.querySelectorAll('.ed-rule').forEach(row => { + row.classList.toggle('ed-picked', Number(row.getAttribute('data-edge')) === sel.edge); + }); + } + + // The panel: the settings of the selected step, and what it leads to + + function fillSelect(select, value, allowEnd) { + select.replaceChildren(); + if (allowEnd) select.append(el('option', { value : '' }, 'end the pipeline')); + model.steps.forEach(step => select.append(el('option', { value : step.id }, 'start ' + nameOf(step)))); + select.value = value; + } + + function stepSelect(value, allowEnd, onChange) { + const select = el('select', { class : 'ed-step-select', 'data-end' : allowEnd ? '1' : '0', 'aria-label' : 'Step' }); + fillSelect(select, value, allowEnd); + select.addEventListener('change', () => onChange(select.value)); + return select; + } + + function refreshSelects() { + panel.querySelectorAll('.ed-step-select').forEach(select => { + fillSelect(select, select.value, select.getAttribute('data-end') === '1'); + }); + } + + function field(step, key, isRequired) { + + const choices = CHOICES[key]; + const current = step.payload[key] == null ? '' : step.payload[key]; + let input; + + if (choices) { + input = el('select', { 'aria-label' : fullLabel(key) }, choices.map(choice => el('option', { value : choice }, choice))); + if (!choices.includes(current)) input.append(el('option', { value : current }, current)); + } else if (LONG.includes(key)) { + input = el('textarea', { rows : '4', spellcheck : 'false', 'aria-label' : fullLabel(key) }); + } else { + input = el('input', { spellcheck : 'false', 'aria-label' : fullLabel(key) }); + } + + input.value = current; + + const flag = () => input.classList.toggle('ed-empty', isRequired && input.value.trim() === ''); + input.addEventListener(choices ? 'change' : 'input', () => { + step.payload[key] = input.value; + flag(); + if (key === 'test_mode') { scaffold(step); drawPanel(); } + changed(); + }); + flag(); + + return el('div', { class : LONG.includes(key) ? 'ed-field ed-wide' : 'ed-field' }, + el('label', {}, label(key) + (isRequired ? '' : ' (optional)')), input); + } + + // The settings that a rule changes for the step that it starts + + function setEditor(edge) { + + const box = el('div'); + const preferred = ['dev_time_control', 'base_time_control', 'test_bounds', 'test_confidence', 'test_max_games', + 'dev_branch', 'base_branch', 'dev_options', 'base_options', 'dev_network', 'base_network', 'priority', 'throughput', 'workload_size', 'book_name']; + const allowed = new Set(meta.allowed); + const keys = preferred.filter(key => allowed.has(key)).concat(meta.allowed.filter(key => !preferred.includes(key))); + + const draw = () => { + + box.replaceChildren(); + + Object.keys(edge.set).forEach(key => { + const input = el('input', { spellcheck : 'false', 'aria-label' : fullLabel(key) }); + input.value = edge.set[key]; + input.addEventListener('input', () => { edge.set[key] = input.value; changed(); }); + const remove = button('\u00d7', () => { delete edge.set[key]; draw(); changed(); }, 'btn-red'); + remove.title = 'Stop changing this setting'; + box.append(el('div', { class : 'ed-set-row' }, el('label', {}, fullLabel(key)), input, remove)); + }); + + const pick = el('select', { 'aria-label' : 'Change a setting' }, + el('option', { value : '' }, 'Change a setting\u2026'), + keys.filter(key => !(key in edge.set)).map(key => el('option', { value : key }, fullLabel(key)))); + + pick.addEventListener('change', () => { + if (!pick.value) return; + const target = stepById(edge.to) || stepById(edge.from); + edge.set[pick.value] = (target && target.payload[pick.value]) || ''; + draw(); + changed(); + }); + + box.append(pick); + }; + + draw(); + return box; + } + + function ruleRow(edge, index) { + + const on = el('select', { 'aria-label' : 'Outcome' }, meta.outcomes.map(outcome => el('option', { value : outcome }, OUTCOME_TEXT[outcome] || outcome))); + on.value = edge.on; + on.addEventListener('change', () => { edge.on = on.value; changed(); }); + + const to = stepSelect(edge.to, true, value => { edge.to = value; changed(); }); + + const remove = button('\u00d7', () => { + model.edges.splice(model.edges.indexOf(edge), 1); + sel.edge = null; + drawPanel(); + applyMarks(); + changed(); + }, 'btn-red'); + remove.title = 'Remove this rule'; + + const more = el('details', { open : Object.keys(edge.set).length > 0 || sel.edge === index }, + el('summary', {}, 'Change settings for the step that starts'), setEditor(edge)); + + const row = el('div', { class : 'ed-box ed-rule' + (sel.edge === index ? ' ed-picked' : ''), 'data-edge' : String(index) }, + el('div', { class : 'ed-inline' }, 'If', on, 'then', to, remove), more); + + row.addEventListener('click', () => { sel.edge = index; applyMarks(); markRows(); }); + return row; + } + + function addRule(step) { + + const used = model.edges.filter(edge => edge.from === step.id).map(edge => edge.on); + const options = meta.outcomes.filter(outcome => !(IMPOSSIBLE[step.kind] || []).includes(outcome)); + + model.edges.push({ from : step.id, on : options.find(outcome => !used.includes(outcome)) || 'any', to : '', set : {} }); + sel.edge = model.edges.length - 1; + + drawPanel(); + applyMarks(); + changed(); + } + + function drawPanel() { + + panel.replaceChildren(); + + const step = stepById(sel.step); + + if (!step) { + panel.append(el('div', { class : 'card-head' }, el('h2', { class : 'card-title' }, 'Step')), + el('p', { class : 'ed-note ed-pad' }, 'Click a step in the flow to change it.')); + return; + } + + const head = el('div', { class : 'card-head' }, el('h2', { class : 'card-title' }, 'Step'), + model.start === step.id + ? el('span', { class : 'ed-tag' }, 'First step') + : button('Make this the first step', () => { model.start = step.id; drawPanel(); changed(); })); + + const body = el('div', { class : 'ed-pad' }); + + const name = el('input', { maxlength : '64', required : true, style : 'width: 100%', 'aria-label' : 'Step name' }); + name.value = step.name; + name.addEventListener('input', () => { step.name = name.value; refreshSelects(); changed(); }); + + const kind = el('select', { 'aria-label' : 'Kind' }, meta.kinds.map(k => el('option', { value : k }, KIND_LABEL[k] || k))); + kind.value = step.kind; + kind.addEventListener('change', () => { changeKind(step, kind.value); drawPanel(); changed(); }); + + body.append(el('div', { class : 'ed-inline', style : 'align-items: flex-end' }, + el('div', { style : 'flex: 1 1 9rem' }, el('label', {}, 'Name'), name), + el('div', {}, el('label', {}, 'Kind'), kind))); + + if (step.msg) body.append(el('p', { class : 'ed-note' }, step.msg)); + + // Start from a test that already exists + if (step.kind === 'TEST') { + + const number = el('input', { type : 'number', min : '1', placeholder : 'Test #', 'aria-label' : 'Test number', style : 'width: 6.5rem' }); + const copy = button('Copy settings', async () => { + + const id = parseInt(number.value, 10); + if (!id) { step.msg = 'Type the number of a test first'; drawPanel(); return; } + + try { + const response = await fetch('/pipelines/test-fields/' + id + '/', { credentials : 'same-origin' }); + const data = await response.json(); + + if (!response.ok) { step.msg = data.error || 'Could not copy that test'; drawPanel(); return; } + + step.payload = texts(data.payload); + scaffold(step); + step.msg = 'Copied from test #' + id + '. Check the branches before saving'; + } catch (error) { + step.msg = 'Could not copy that test'; + } + + drawPanel(); + changed(); + }); + + body.append(el('div', { style : 'margin-top: .8rem' }, el('label', {}, 'Start from a test that already exists'), + el('div', { class : 'ed-inline' }, number, copy))); + } + + // The settings, in the same groups as the pages that create a test + const required = needed(step); + const groups = {}; + fieldsFor(step).forEach(key => { (groups[groupOf(key)] = groups[groupOf(key)] || []).push(key); }); + + GROUP_ORDER.forEach(title => { + + if (!groups[title]) return; + + const grid = el('div', { class : 'ed-grid' }, groups[title].map(key => field(step, key, required.includes(key)))); + const empty = groups[title].some(key => required.includes(key) && String(step.payload[key] == null ? '' : step.payload[key]).trim() === ''); + + body.append(el('details', { class : 'ed-group', open : title === 'Match' || (title !== 'Advanced' && empty) }, + el('summary', {}, GROUP_TITLE[title]), grid)); + }); + + // What it leads to + body.append(el('h3', { class : 'ed-h' }, 'What happens next')); + + let leads = 0; + model.edges.forEach((edge, index) => { + if (edge.from !== step.id) return; + leads++; + body.append(ruleRow(edge, index)); + }); + + if (!leads) body.append(el('p', { class : 'ed-note' }, 'Nothing: the pipeline ends after this step. Press + above the step in the flow, or add a rule here.')); + + const remove = button('Remove this step', () => removeStep(step), 'btn-red'); + remove.disabled = model.steps.length < 2; + + body.append(el('div', { class : 'ed-inline', style : 'margin-top: .6rem' }, button('Add rule', () => addRule(step)), remove)); + + panel.append(head, body); + } + + // Checks, from the server, so that they are the very same rules that a run uses + + function showIssues(list) { + + lastIssues = list; + checks.replaceChildren(); + + if (!list.length) { + checks.append(el('li', { class : 'pl-check pl-check-ok' }, el('i', { class : 'fa-solid fa-circle-check' }), el('span', {}, 'No problems found'))); + applyMarks(); + return; + } + + list.forEach(issue => { + + const icon = issue.level === 'error' ? 'fa-circle-exclamation' : issue.level === 'warning' ? 'fa-triangle-exclamation' : 'fa-circle-info'; + const who = issue.name || (typeof issue.step === 'string' ? issue.step : ''); + const jump = typeof issue.step === 'string' && stepById(issue.step); + + const item = el('li', { class : 'pl-check pl-check-' + issue.level + (jump ? ' ed-jump' : '') }, + el('i', { class : 'fa-solid ' + icon }), + el('span', {}, who ? el('strong', {}, who) : null, who ? ' ' : null, issue.message)); + + if (jump) item.addEventListener('click', () => select(issue.step)); + checks.append(item); + }); + + applyMarks(); + } + + // The line under the flow + + let flashTimer = null; + + function flash(message) { + hint.textContent = message; + hint.classList.add('ed-hint-warn'); + clearTimeout(flashTimer); + flashTimer = setTimeout(drawHint, 4000); + } + + function drawHint() { + hint.classList.remove('ed-hint-warn'); + hint.textContent = model.steps.length === 1 && !model.edges.length + ? 'This is the whole pipeline so far: one step, and then it ends. Press the + above the step to say what starts when it passes or fails.' + : 'Press + above a step to add what happens next. Click a step to change its settings, or the label on an arrow to change that rule.'; + } + + // Toolbar, limits and saving + + ['TEST', 'TUNE', 'DATAGEN'].forEach(kind => { + document.getElementById('pl-add-' + kind.toLowerCase()).addEventListener('click', () => { + + if (model.steps.length >= meta.limits.steps) { + flash('A pipeline may have at most ' + meta.limits.steps + ' steps'); + return; + } + + const step = newStep(kind, null); + select(step.id); + changed(); + }); + }); + + const visitsField = document.getElementById('pl-visits'); + const totalField = document.getElementById('pl-total'); + + visitsField.max = meta.limits.visits; + totalField.max = meta.limits.total; + visitsField.value = model.max_visits; + totalField.value = model.max_steps; + visitsField.addEventListener('input', () => { model.max_visits = visitsField.value; changed(); }); + totalField.addEventListener('input', () => { model.max_steps = totalField.value; changed(); }); + + form.addEventListener('submit', () => { document.getElementById('pl-graph').value = JSON.stringify(build()); }); - drawAll(); + // Go + + if (!model.steps.length) { + const first = { id : 'step1', name : 'Step 1', kind : 'TEST', payload : texts(meta.defaults.TEST), msg : '' }; + scaffold(first); + model.steps.push(first); + } + + if (!model.steps.some(step => step.id === model.start)) model.start = model.steps[0].id; + + sel.step = model.start; + drawPanel(); + drawHint(); + refresh(); + })();