Review finding 1: a hire start refusal the apply step can also raise after the decision is consumed (decision-stale, organization-instance-*, organization-refused, definition-missing, invalid-request and the rest) no longer says "Nothing was applied". It says that part may be applied when the inbox shows the proposal as answered, and to check Agents first. Only codes that prepare() or the route checks alone raise keep "Nothing was applied". Review P3: a failed workflows or autonomy read keeps the last good read, so an open editor or a dirty form stays through it. Focus holds a section only in a field being typed in; a focused button is rebuilt and gets focus back by data-focus-key. Autonomy has Discard changes. The project tab fade is 0px when every tab fits. s8 and s9 header pins at 1440 now measure from the content edge: 1418 was 100vw-based, ran under the page scrollbar and is the P2-11 clipping itself. Correction to the previous commit's message: P1-2 is the unknown project, agent or harness wording; P2-4 names the refused field; P2-6 is the Queue refusal reason; P2-8 is "bus stopped".
202 lines
15 KiB
JavaScript
202 lines
15 KiB
JavaScript
// Starter packs SP6 (#1873, design section 8): the owner's workflow list and editor on an
|
|
// organization's page. GET /api/orgs/<id>/workflows reads the org's and each code project's workflows
|
|
// with the file revision; a save is POST .../workflows/<name> {revision, workflow, project?} and a delete
|
|
// DELETE .../workflows/<name> {revision, project?} (workflow.set.console). The bus checks the shape; this
|
|
// page marks a step role that resolves to no org definition or role template (and is not `human`) as
|
|
// naming no current role. Every organization-supplied string goes through esc.
|
|
(() => {
|
|
'use strict';
|
|
const esc = x => String(x ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
const base = org => `/api/orgs/${encodeURIComponent(org)}`;
|
|
const STATES = [['todo', 'To do'], ['in-progress', 'In progress'], ['in-review', 'Review'], ['blocked', 'Blocked'], ['done', 'Done']];
|
|
const STATE_LABEL = Object.fromEntries(STATES);
|
|
// The writer's workflow name rule (organization.mjs PLAN_NAME); a name it would refuse is refused here first.
|
|
const NAME = /^[a-z][a-z0-9-]{0,63}$/;
|
|
const NAME_RULE = 'A workflow name is 1 to 64 lowercase letters, digits or dashes, starting with a letter.';
|
|
const MISSING = 'names no current role';
|
|
const states = new Map();
|
|
const guidance = {
|
|
'revision-conflict': 'The organization changed since this page read it. Reload the page before saving.',
|
|
'organization-busy': 'The organization is busy with another write. Try again shortly.',
|
|
'invalid-request': 'The bus refused the workflow. Check each step has a title, a state and one to eight distinct roles.',
|
|
'project-not-found': 'That project is not in the organization file.',
|
|
'credential-leak': 'The workflow carries a value the credential store holds.',
|
|
'read-only': 'This Console was started without send. Workflows can be read, not changed.',
|
|
'owner-only': 'Only the owner can read and change workflows.',
|
|
'sign-in-required': 'Sign in again to read workflows.',
|
|
'cross-origin': 'The request did not come from this Console.',
|
|
'not-configured': 'This Console cannot read the organization file.',
|
|
'org-unavailable': 'The organization file could not be read.',
|
|
'no-bus-host': 'The organization bus is not running.',
|
|
};
|
|
async function call(url, method, body) {
|
|
const r = await fetch(url, method === 'GET' ? { cache: 'no-store' } : { method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
|
|
let value = null;
|
|
try { value = await r.json(); } catch { value = null; }
|
|
if (!r.ok) throw Error(guidance[value?.error] ?? `The bus refused: ${value?.error ?? 'outcome unknown'}.`);
|
|
return value;
|
|
}
|
|
const plain = v => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
async function read(org, s) {
|
|
const value = await call(`${base(org)}/workflows`, 'GET');
|
|
if (!plain(value) || !plain(value.workflows) || !plain(value.projects) || !plain(value.roles) || typeof value.revision !== 'string') throw Error('The workflow read returned an unexpected answer.');
|
|
s.data = value;
|
|
s.known = new Set([...(value.roles.definitions || []), ...(value.roles.templates || []), 'human']);
|
|
}
|
|
// E2E6 P1-1: a poll reloads the data but keeps the page's own state: an open editor and its draft,
|
|
// a pending delete confirmation and the last receipt.
|
|
async function load(org) {
|
|
const prev = states.get(org);
|
|
const s = { data: null, known: new Set(), error: null, editing: prev?.editing ?? null, confirm: prev?.confirm ?? null, status: prev?.status ?? '' };
|
|
try { await read(org, s); } catch (error) {
|
|
// Review P3: a failed poll while an editor is open keeps the last good read, so the fresh section
|
|
// still carries its data-live-key and graftLive puts the held section, editor and focus back.
|
|
if (prev?.editing && prev.data) Object.assign(s, { data: prev.data, known: prev.known });
|
|
else s.error = error.message;
|
|
}
|
|
states.set(org, s);
|
|
}
|
|
const scopes = s => [['', 'Organization', s.data.workflows], ...Object.keys(s.data.projects).sort().map(p => [p, `Project ${p}`, s.data.projects[p]])];
|
|
const roleChip = (s, role) => s.known.has(role)
|
|
? `<code>${esc(role)}</code>`
|
|
: `<code>${esc(role)}</code> <span class="wf-missing" data-wf-missing>${MISSING}</span>`;
|
|
function stepItem(s, step) {
|
|
const roles = Array.isArray(step?.roles) ? step.roles : [];
|
|
return `<li data-wf-step><span>${esc(step?.title)}</span> <span class="muted">${esc(STATE_LABEL[step?.state] ?? step?.state)}</span> <span class="wf-roles">${roles.map(r => roleChip(s, r)).join(', ')}</span></li>`;
|
|
}
|
|
function workflowItem(org, s, scope, name, w) {
|
|
const steps = Array.isArray(w?.steps) ? w.steps : [];
|
|
const confirm = s.confirm && s.confirm.scope === scope && s.confirm.name === name;
|
|
const actions = !s.data.writable ? '' : confirm
|
|
? `<p>Delete this workflow? <button class="btn" type="button" data-wf-delete-yes data-focus-key="${esc(`wf-yes:${scope}:${name}`)}">Delete</button> <button class="btn" type="button" data-wf-delete-no data-focus-key="${esc(`wf-no:${scope}:${name}`)}">Keep</button></p>`
|
|
: `<p><button class="btn" type="button" data-wf-edit data-focus-key="${esc(`wf-edit:${scope}:${name}`)}">Edit</button> <button class="btn" type="button" data-wf-delete data-focus-key="${esc(`wf-delete:${scope}:${name}`)}">Delete</button></p>`;
|
|
return `<li class="wf-item" data-wf="${esc(name)}" data-wf-scope="${esc(scope)}"><strong data-wf-title>${esc(w?.title || name)}</strong> <span class="muted"><code>${esc(name)}</code></span>
|
|
${w?.description ? `<p>${esc(w.description)}</p>` : ''}<ol class="wf-steps">${steps.map(st => stepItem(s, st)).join('')}</ol>${actions}</li>`;
|
|
}
|
|
function stepRow(s, step, i) {
|
|
const roles = step.roles.split(',').map(r => r.trim()).filter(Boolean);
|
|
const missing = roles.filter(r => !s.known.has(r));
|
|
return `<fieldset class="wf-step" data-wf-edit-step="${i}"><legend>Step ${i + 1}</legend>
|
|
<label>Title<input name="title" maxlength="120" value="${esc(step.title)}" autocomplete="off"></label>
|
|
<label>State<select name="state">${STATES.map(([v, l]) => `<option value="${v}"${step.state === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label>
|
|
<label>Roles, separated by commas<input name="roles" value="${esc(step.roles)}" autocomplete="off"></label>
|
|
<p class="wf-note" data-wf-step-missing>${missing.length ? `${missing.map(r => `<code>${esc(r)}</code>`).join(', ')} ${MISSING}` : ''}</p>
|
|
<button class="btn" type="button" data-wf-step-remove>Remove step</button></fieldset>`;
|
|
}
|
|
function editor(s) {
|
|
const e = s.editing;
|
|
if (!e) return '';
|
|
const scopeField = e.isNew
|
|
? `<label>Where<select name="scope">${scopes(s).map(([v, l]) => `<option value="${esc(v)}"${e.scope === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label><label>Name<input name="name" maxlength="64" value="${esc(e.name)}" autocomplete="off" placeholder="lowercase letters, digits, dashes"></label>`
|
|
: `<p>${e.scope ? `Project ${esc(e.scope)}` : 'Organization'}, <code>${esc(e.name)}</code></p>`;
|
|
return `<form class="wf-editor" data-wf-editor data-live-hold><h4>${e.isNew ? 'New workflow' : 'Edit workflow'}</h4>${scopeField}
|
|
<label>Title<input name="title" maxlength="120" value="${esc(e.draft.title)}" autocomplete="off"></label>
|
|
<label>Description<textarea name="description" maxlength="1000" rows="2">${esc(e.draft.description)}</textarea></label>
|
|
${e.draft.steps.map((st, i) => stepRow(s, st, i)).join('')}
|
|
<p><button class="btn" type="button" data-wf-step-add>Add step</button> <button class="btn" type="submit">Save workflow</button> <button class="btn" type="button" data-wf-cancel>Cancel</button></p>
|
|
<p class="note">Roles name an organization role, a role template, or <code>human</code>.</p></form>`;
|
|
}
|
|
function section(org) {
|
|
const s = states.get(org);
|
|
if (!s || s.error) return `<section class="panel" data-workflows data-workflows-org="${esc(org)}"><h3>Workflows</h3><p>${esc(s?.error ?? 'Workflows could not be read.')}</p></section>`;
|
|
const lists = scopes(s).map(([scope, label, flows]) => {
|
|
const names = Object.keys(flows || {}).sort();
|
|
return `<div class="wf-scope" data-wf-scope-list="${esc(scope)}"><h4>${esc(label)}</h4>${names.length ? `<ul class="wf-list">${names.map(n => workflowItem(org, s, scope, n, flows[n])).join('')}</ul>` : '<p class="note">No workflows.</p>'}</div>`;
|
|
}).join('');
|
|
const add = s.data.writable ? (s.editing ? '' : `<p><button class="btn" type="button" data-wf-new data-focus-key="${esc(`wf-new:${org}`)}">New workflow</button></p>`) : '<p class="note">Only the owner, on a Console started with send, can change workflows.</p>';
|
|
return `<section class="panel" data-workflows data-workflows-org="${esc(org)}" data-live-key="${esc(`workflows:${org}`)}"><h3>Workflows</h3><p>A workflow lists the steps a task goes through, the state each step puts it in and the roles that do it.</p>${lists}${add}${editor(s)}<p role="status" data-workflows-status>${esc(s.status)}</p></section>`;
|
|
}
|
|
function redraw(org) {
|
|
const el = [...document.querySelectorAll('[data-workflows-org]')].find(n => n.dataset.workflowsOrg === org);
|
|
if (el) el.outerHTML = section(org);
|
|
}
|
|
// The editor's current values back into the draft, so adding or removing a step keeps what was typed.
|
|
function capture(root, s) {
|
|
const form = root.querySelector('[data-wf-editor]');
|
|
if (!form || !s.editing) return;
|
|
const e = s.editing;
|
|
if (e.isNew) { e.scope = form.elements.scope?.value ?? e.scope; e.name = form.elements.name?.value ?? e.name; }
|
|
e.draft.title = form.querySelector(':scope > label > input[name="title"]').value;
|
|
e.draft.description = form.elements.description.value;
|
|
e.draft.steps = [...form.querySelectorAll('[data-wf-edit-step]')].map(f => ({ title: f.querySelector('[name="title"]').value, state: f.querySelector('[name="state"]').value, roles: f.querySelector('[name="roles"]').value }));
|
|
}
|
|
const flowsIn = (s, scope) => scope ? s.data.projects[scope] : s.data.workflows;
|
|
const target = (s, scope) => scope ? { project: scope } : {};
|
|
async function reload(org, s, status) {
|
|
try { await read(org, s); s.status = status; } catch (error) { s.status = `${status} ${error.message}`; }
|
|
}
|
|
document.addEventListener('click', async ev => {
|
|
const button = ev.target.closest('[data-wf-new],[data-wf-edit],[data-wf-cancel],[data-wf-step-add],[data-wf-step-remove],[data-wf-delete],[data-wf-delete-yes],[data-wf-delete-no]');
|
|
if (!button) return;
|
|
const root = button.closest('[data-workflows-org]'), org = root?.dataset.workflowsOrg, s = states.get(org);
|
|
if (!s?.data) return;
|
|
const item = button.closest('[data-wf]'), scope = item?.dataset.wfScope ?? '', name = item?.dataset.wf;
|
|
if (button.hasAttribute('data-wf-new')) {
|
|
s.editing = { isNew: true, revision: s.data.revision, scope: '', name: '', draft: { title: '', description: '', steps: [{ title: '', state: 'todo', roles: '' }] } };
|
|
} else if (button.hasAttribute('data-wf-edit')) {
|
|
const w = flowsIn(s, scope)?.[name];
|
|
s.editing = { isNew: false, revision: s.data.revision, scope, name, draft: { title: w?.title ?? '', description: w?.description ?? '', steps: (w?.steps ?? []).map(st => ({ title: st.title ?? '', state: st.state ?? 'todo', roles: (st.roles ?? []).join(', ') })) } };
|
|
} else if (button.hasAttribute('data-wf-cancel')) {
|
|
s.editing = null;
|
|
} else if (button.hasAttribute('data-wf-step-add')) {
|
|
capture(root, s); s.editing.draft.steps.push({ title: '', state: 'todo', roles: '' });
|
|
} else if (button.hasAttribute('data-wf-step-remove')) {
|
|
capture(root, s); s.editing.draft.steps.splice(Number(button.closest('[data-wf-edit-step]').dataset.wfEditStep), 1);
|
|
} else if (button.hasAttribute('data-wf-delete')) {
|
|
s.confirm = { scope, name };
|
|
} else if (button.hasAttribute('data-wf-delete-no')) {
|
|
s.confirm = null;
|
|
} else if (button.hasAttribute('data-wf-delete-yes')) {
|
|
button.disabled = true;
|
|
try {
|
|
await call(`${base(org)}/workflows/${encodeURIComponent(name)}`, 'DELETE', { revision: s.data.revision, ...target(s, scope) });
|
|
s.confirm = null;
|
|
await reload(org, s, `Deleted ${name}.`);
|
|
} catch (error) { s.status = error.message; }
|
|
}
|
|
redraw(org);
|
|
});
|
|
// Every keystroke goes back into the draft, so any repaint draws what was typed.
|
|
document.addEventListener('input', ev => {
|
|
const form = ev.target.closest('[data-wf-editor]'), root = form?.closest('[data-workflows-org]');
|
|
if (form && root) { const st = states.get(root.dataset.workflowsOrg); if (st?.editing) capture(root, st); }
|
|
const field = ev.target.closest('[data-wf-edit-step] [name="roles"]');
|
|
if (!field) return;
|
|
const s = states.get(field.closest('[data-workflows-org]')?.dataset.workflowsOrg);
|
|
if (!s) return;
|
|
const missing = field.value.split(',').map(r => r.trim()).filter(r => r && !s.known.has(r));
|
|
// textContent and created nodes only: a typed name never becomes markup.
|
|
const note = field.closest('[data-wf-edit-step]').querySelector('[data-wf-step-missing]');
|
|
note.textContent = missing.length ? `${missing.join(', ')} ${MISSING}` : '';
|
|
});
|
|
document.addEventListener('submit', async ev => {
|
|
if (!ev.target.matches('[data-wf-editor]')) return;
|
|
ev.preventDefault();
|
|
const root = ev.target.closest('[data-workflows-org]'), org = root?.dataset.workflowsOrg, s = states.get(org);
|
|
if (!s?.editing) return;
|
|
capture(root, s);
|
|
const e = s.editing;
|
|
if (!NAME.test(e.name)) { s.status = NAME_RULE; redraw(org); return; }
|
|
// A save is a set: a new workflow under a name the scope already holds would replace it without a word.
|
|
if (e.isNew && Object.hasOwn(flowsIn(s, e.scope) ?? {}, e.name)) { s.status = `A workflow named ${e.name} already exists here. Edit it instead.`; redraw(org); return; }
|
|
// E2E6 P2-1: a step role that names no current role is named before the bus refuses it generically.
|
|
const unknown = e.draft.steps.flatMap((st, i) => st.roles.split(',').map(r => r.trim()).filter(r => r && !s.known.has(r)).map(r => [i + 1, r]));
|
|
if (unknown.length) { s.status = `${unknown.map(([i, r]) => `Step ${i}: ${r}`).join('; ')} ${unknown.length === 1 ? 'names' : 'name'} no current role. Use an organization role, a role template or human.`; redraw(org); return; }
|
|
const workflow = {
|
|
...(e.draft.title.trim() ? { title: e.draft.title.trim() } : {}),
|
|
...(e.draft.description.trim() ? { description: e.draft.description.trim() } : {}),
|
|
steps: e.draft.steps.map(st => ({ title: st.title.trim(), state: st.state, roles: st.roles.split(',').map(r => r.trim()).filter(Boolean) })),
|
|
};
|
|
const button = ev.target.querySelector('button[type="submit"]');
|
|
button.disabled = true;
|
|
try {
|
|
// The revision the editor opened on: a change made since then is a revision-conflict, not overwritten.
|
|
await call(`${base(org)}/workflows/${encodeURIComponent(e.name)}`, 'POST', { revision: e.revision ?? s.data.revision, workflow, ...target(s, e.scope) });
|
|
s.editing = null;
|
|
await reload(org, s, `Saved ${e.name}.`);
|
|
} catch (error) { s.status = error.message; }
|
|
redraw(org);
|
|
});
|
|
window.MosaicWorkflows = { load, section };
|
|
})();
|