diff --git a/packages/webui/src/public/workflows.js b/packages/webui/src/public/workflows.js index d9fb0e295..2e59643da 100644 --- a/packages/webui/src/public/workflows.js +++ b/packages/webui/src/public/workflows.js @@ -46,10 +46,22 @@ } // 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. + // SP17: a write in flight holds the poll. Each organization counts its writes (epoch moves when one starts + // and when it ends); a read that began before a write ended, or answers while one is in flight, is dropped + // and the page keeps what it has, which the write's answer brings up to date (written()). + const writes = new Map(); + const writeState = org => { if (!writes.has(org)) writes.set(org, { epoch: 0, inflight: 0 }); return writes.get(org); }; + async function writing(org, fn) { + const w = writeState(org); + w.epoch++; w.inflight++; + try { return await fn(); } finally { w.inflight--; w.epoch++; } + } async function load(org) { - const prev = states.get(org); + const prev = states.get(org), w = writeState(org), began = w.epoch; 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) { + const raced = () => !!prev?.data && (w.inflight > 0 || w.epoch !== began); + try { await read(org, s); if (raced()) return; } catch (error) { + if (raced()) return; // 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 }); @@ -631,6 +643,17 @@ if (btn.hasAttribute('data-wfg-delete')) { d.confirm = true; return paint('wfg-delete-no'); } if (btn.hasAttribute('data-wfg-delete-no')) { d.confirm = false; return paint('wfg-delete'); } }); + // SP17: the page's read brought up to date from a write's answer: the workflow as sent (or gone) and the + // revision the write answered. Without a revision in the answer the page reads the file again. + async function written(org, s, scope, name, workflow, answer) { + const now = states.get(org) ?? s, flows = now.data ? flowsIn(now, scope) : null; + if (plain(flows) && typeof answer?.revision === 'string' && /^[0-9a-f]{64}$/.test(answer.revision)) { + if (workflow) flows[name] = workflow; else delete flows[name]; + now.data.revision = answer.revision; + return; + } + try { await read(org, now); } catch { /* the next poll reads it */ } + } async function save({ org, name, scope, s, key }) { const d = drafts.get(key); if (!d || d.busy) return; @@ -640,10 +663,10 @@ if (refused) { d.status = refused; say(refused); return paint('wfg-save'); } d.busy = true; d.status = 'Saving…'; paint(); try { - await saveFlow(org, s, { scope, name, revision: d.revision, workflow: shape(d.flow) }); + const workflow = shape(d.flow); + await writing(org, async () => written(org, s, scope, name, workflow, await saveFlow(org, s, { scope, name, revision: d.revision, workflow }))); drafts.delete(key); notes.set(key, `Saved ${name}.`); - try { await read(org, states.get(org) ?? s); } catch { /* the next poll reads it */ } say(`Saved ${name}.`); paint(selected() ? `wfg-step:${selected()}` : 'wfg-delete'); } catch (error) { @@ -660,11 +683,10 @@ try { // The revision of the workflow the page shows (settle moves it on only while this workflow is unchanged): // a change made to it since is refused, not deleted over. - await removeFlow(org, s, { scope, name, revision: d.revision }); + await writing(org, async () => written(org, s, scope, name, null, await removeFlow(org, s, { scope, name, revision: d.revision }))); drafts.delete(key); notes.set(dkey(org, '', ''), `Deleted ${name}.`); say(`Deleted ${name}.`); - try { await read(org, s); } catch { /* the next poll reads it */ } location.hash = `${orgHash(org)}/workflows`; } catch (error) { d.busy = false; d.confirm = false; diff --git a/packages/webui/tests/workflows-browser.test.mjs b/packages/webui/tests/workflows-browser.test.mjs index 9b7ea502a..6afd8d8f5 100644 --- a/packages/webui/tests/workflows-browser.test.mjs +++ b/packages/webui/tests/workflows-browser.test.mjs @@ -45,7 +45,10 @@ const LIST = [ // page sent, and a refusal to give the next write. A write with another revision is a revision-conflict. const hex = n => n.toString(16).padStart(64, '0'); function store(writable) { - const st = { writable, docs: structuredClone(DOCS), revs: { acme: 'a'.repeat(64), bare: 'b'.repeat(64), gamma: 'c'.repeat(64) }, writes: [], refuse: null, n: 0 }; + const st = { writable, docs: structuredClone(DOCS), revs: { acme: 'a'.repeat(64), bare: 'b'.repeat(64), gamma: 'c'.repeat(64) }, writes: [], refuse: null, n: 0, held: {} }; + // SP17: hold('read') holds the next workflow read, which answers with the file as it was when the read + // began; hold('write') holds the next write before it reaches the file. Each returns the release. + st.hold = which => { let open; st.held[which] = new Promise(r => { open = r; }); return open; }; const fail = code => Object.assign(new Error(code), { code }); st.write = (id, verb, args) => { st.writes.push({ id, verb, args: structuredClone(args) }); @@ -73,10 +76,16 @@ function organizations(reads, st) { members: async () => LIST.map(member), resolve: async id => { const org = LIST.find(o => o.id === id); if (!org) return null; - const workflowsRead = async () => { reads.push(id); if (st.failRead) throw Object.assign(new Error('org-unavailable'), { code: 'org-unavailable' }); return { revision: st.revs[id], document: structuredClone(st.docs[id] ?? {}), templates: ['writer'] }; }; + const workflowsRead = async () => { + reads.push(id); + if (st.failRead) throw Object.assign(new Error('org-unavailable'), { code: 'org-unavailable' }); + const answer = { revision: st.revs[id], document: structuredClone(st.docs[id] ?? {}), templates: ['writer'] }; + const h = st.held.read; if (h) { st.held.read = null; await h; } + return answer; + }; if (!org.busHealthy) return { busHealthy: false, reads: null, bus: {}, workflowsRead, chat: { projects: async () => [], threads: async () => [] } }; return { - busHealthy: true, workflowsRead, packsWrite: st.writable ? async (verb, args) => st.write(id, verb, args) : null, decisionWrite: async () => ({}), send: async () => ({}), + busHealthy: true, workflowsRead, packsWrite: st.writable ? async (verb, args) => { const h = st.held.write; if (h) { st.held.write = null; await h; } return st.write(id, verb, args); } : null, decisionWrite: async () => ({}), send: async () => ({}), requestRead: async verb => { if (verb === 'packs.console') return { packs: [] }; if (verb === 'autonomy.get.console') return { revision: 'e'.repeat(64), autonomy: {}, levels: {} }; throw Object.assign(new Error('not-configured'), { code: 'not-configured' }); }, reads: { business: async () => ({ business: { id, projects: [], instances: [] } }), settings: async () => ({}), queue: async () => ({ rows: [] }) }, bus: { instances: async () => ({ instances: {} }), agents: async () => [], 'thread.claims': async () => [], tasks: async () => [], inbox: async () => [], messages: async () => ({ messages: [] }) }, @@ -493,6 +502,46 @@ test('the poll does not draw over a pending change, takes a new revision when on assert.match(await b.evaluate(`document.querySelector('#bus-view .sub').textContent`), /Changed elsewhere\./); }); +// SP17: changes step `step`'s title on the open graph page, so the change is pending and Save shows. +async function retitle(b, wait, step, title) { + await b.evaluate(press('[data-wfg-edit]')); + await wait(`document.querySelector('[data-wfg-form] input[name="title"]')`, 'step form'); + await b.evaluate(fill('[data-wfg-form] input[name="title"]', title)); + await b.evaluate(press('[data-wfg-apply]')); + await wait(`${titles}[${step - 1}] === ${JSON.stringify(title)} && document.querySelector('[data-wfg-save]')`, 'pending change'); +} + +test('SP17: a Save in flight holds the poll, and the page shows the saved workflow from the answer', { timeout: 60000 }, async t => { + const { b, wait, st, reads } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=2' }); + await wait(`${boxes}.length === 2 && document.querySelector('[data-wfg-detail]')`, 'site graph'); + await retitle(b, wait, 2, 'Ship the release'); + // The write is held, so the Save is in flight. + const openWrite = st.hold('write'); + await b.evaluate(press('[data-wfg-save]')); + await wait(`document.querySelector('[data-wfg-save]')?.disabled === true`, 'save in flight'); + // A poll begins while the Save is in flight: its read takes the file as it was before the write. + const openRead = st.hold('read'), n = reads.length; + await b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));true`); + for (let i = 0; i < 200 && reads.length === n; i++) await new Promise(r => setTimeout(r, 20)); + assert.ok(reads.length > n, 'the poll read began'); + openWrite(); + await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'saved'); + // The poll's read answers only now, with the file as it was before the Save. + openRead(); + await new Promise(r => setTimeout(r, 800)); + assert.deepEqual(await b.evaluate(titles), ['Build', 'Ship the release'], 'the step shows the saved title, not the read from before the Save'); + assert.equal(await b.evaluate(`document.querySelector('[data-wfg-stale],[data-wfg-unsaved]')`), null); + assert.equal(st.writes.length, 1, 'one write'); + // The page took the revision the write answered: the next Save is not refused as changed elsewhere. + const saved = st.revs.acme; + await retitle(b, wait, 2, 'Ship it'); + await b.evaluate(press('[data-wfg-save]')); + await wait(`/Saved change\\./.test(${text('[data-wfg-status]')}) && !document.querySelector('[data-wfg-unsaved]')`, 'second save'); + assert.equal(st.writes.length, 2); + assert.equal(st.writes[1].args.revision, saved); + assert.equal(st.docs.acme.projects.site.workflows.change.steps[1].title, 'Ship it'); +}); + test('a reader who cannot write sees no edit controls and one line saying who can', { timeout: 60000 }, async t => { const { b, wait } = await setup(t, { path: '#/orgs/acme/workflows/change?step=2', writable: false }); await wait(`document.querySelector('[data-wfg-detail-title]')?.textContent === 'Implement the change'`, 'step 2');