From fdbc34413b793f1623f30670508c890f5b7d5ec7 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 12 Nov 2026 17:30:07 -0600 Subject: [PATCH] feat(webui,bus): CB5 Console operator flow, binding confirmation and next steps, copy binding status on the Agents grid (#1873) The bus instances read adds a copy's binding status only when the copy was bound at boot or is unbound for want of a bindable service, never to a tester. decision-http returns an allowlisted binding (instance and change) on a binding confirmation and fixed next-step text on an approved resolve and on a binding hire start. The decision page names the copy and the change; the receipt shows the next step; the Agents grid shows can't launch with the binding's next step. Every new string is fixed text. --- packages/bus/src/broker.mjs | 9 ++- packages/bus/src/copy-launch.mjs | 7 ++- packages/webui/src/decision-http.mjs | 24 ++++++-- packages/webui/src/public/bus.js | 11 +++- packages/webui/src/public/workspace.js | 14 +++-- packages/webui/tests/decision-http.test.mjs | 59 ++++++++++++++++++- .../webui/tests/hire-console-browser.test.mjs | 47 +++++++++++++++ .../tests/unified-workspace-browser.test.mjs | 48 ++++++++++++++- 8 files changed, 199 insertions(+), 20 deletions(-) diff --git a/packages/bus/src/broker.mjs b/packages/bus/src/broker.mjs index 022f6547a..12d152e68 100644 --- a/packages/bus/src/broker.mjs +++ b/packages/bus/src/broker.mjs @@ -6450,11 +6450,10 @@ export class Broker { if (request.verb === "instances" && result?.instances && typeof result.instances === "object" && this.#business(s.business).copies) result.copies = Object.fromEntries(Object.entries(this.#business(s.business).copies).map(([name, c]) => [name, { ...structuredClone(c), running: c.state === 'instance' ? this.#running(s.business, name) : [], - // #1873 CB5: a copy that needs a binding (bound at boot, or missing one) carries its - // binding status and next step, fixed text from the launch gate's own checks. Never to a - // tester, and never a binding record. - ...(!s.tester && this.#copyLaunch?.status && (c.state === 'unbound' || Array.isArray(c.bound)) - ? { binding: this.#copyLaunch.status(s.business, name) } : {}), + // #1873 CB5: a copy that needs a binding (bound at boot, or missing a bindable service) + // carries its binding status and next step, fixed text from the launch gate's own checks. + // Never to a tester, and never a binding record. + ...(!s.tester && this.#copyLaunch?.status ? ((binding) => (binding ? { binding } : {}))(this.#copyLaunch.status(s.business, name, c)) : {}), }])); return result; } diff --git a/packages/bus/src/copy-launch.mjs b/packages/bus/src/copy-launch.mjs index 0604cff42..71746b951 100644 --- a/packages/bus/src/copy-launch.mjs +++ b/packages/bus/src/copy-launch.mjs @@ -380,8 +380,11 @@ export function copyLaunchGate({ credentials, writer, configDir, rolesDir, snaps // CB5: the copy's binding status for its owner's views, as copy-binding-status.mjs's fixed // { status, next }. The same checks a launch runs, without the loss report (the sweep makes it) // and without returning anything the check read. An approved binding not yet issued, or one a - // refused issue left pending, needs the owner's issue before anything else. - status(business, instance) { + // refused issue left pending, needs the owner's issue before anything else. `entry` is the copy's + // boot entry: only one bound at boot, or unbound for want of a bindable service, has a status. + status(business, instance, entry) { + const needs = Array.isArray(entry?.bound) || (entry?.state === 'unbound' && Array.isArray(entry.missing) && entry.missing.some((s) => COPY_BINDABLE.includes(s))); + if (!needs) return null; let code = 'ready'; try { check(business, instance); diff --git a/packages/webui/src/decision-http.mjs b/packages/webui/src/decision-http.mjs index 0255689ca..61e13cc48 100644 --- a/packages/webui/src/decision-http.mjs +++ b/packages/webui/src/decision-http.mjs @@ -57,6 +57,17 @@ const HIRE_START_REFUSALS = { 'definition-shared': [409, 'Another agent uses the same role definition, so this change cannot replace it. Nothing was applied.'], 'no-chief-of-staff': [409, 'This organization has no chief of staff, so a hire, fire or change cannot be checked against it. Nothing was applied.'], }; +// #1873 CB5: the owner's next step once a copy credential binding decision is approved, fixed text +// (design section 6 and its three steps). Nothing in it comes from the decision, the bus or a token. +export const BINDING_NEXT = Object.freeze({ + bind: "Binding approved. Issue the copy's token with mosaic credentials issue, then restart the organization bus. The copy's status on the Agents grid names each next step.", + unbind: "Unbind approved. The bus stops the copy's runs and revokes its credential. The copy's status on the Agents grid shows when the revoke finishes.", +}); +// A binding decision's preview names its copy and whether it binds or unbinds. Only those two leave +// this server: the copy id, incarnation, definition pin and services stay with the bus. +const bindingOf = (v) => (v?.binding && typeof v.binding === 'object' && subjectOk(v.binding.instance) && + (v.binding.after === null || (typeof v.binding.after === 'object' && !Array.isArray(v.binding.after))) + ? { instance: v.binding.instance, change: v.binding.after === null ? 'unbind' : 'bind' } : null); const BODY_MAX = 4096; const TOKEN = /^[a-f0-9]{64}$/; const DIGEST = /^[a-f0-9]{64}$/; @@ -150,7 +161,10 @@ export async function decisionHTTP(req, res, { path, decide, session, live, conf if(step==='start' && (typeof result?.id!=='string'||result.op!=='resolved'||result.choice!=='yes'))return refuse('outcome-unknown'); if(step==='templates' && !Array.isArray(result?.templates))return refuse('confirmation-unavailable'); line(step==='start'?'hire=recorded':'templates=read'); - return json(res,200,step==='start'?{id:result.id,op:result.op,choice:result.choice}:result); + // CB5: an approved binding start says what the owner does next, fixed text by its shape. + const change=step==='start' && value.hire?.binding && typeof value.hire.binding==='object' && 'services' in value.hire.binding + ? (value.hire.binding.services===null?'unbind':'bind') : null; + return json(res,200,step==='start'?{id:result.id,op:result.op,choice:result.choice,...(change?{next:BINDING_NEXT[change]}:{})}:result); } catch(err) { if(step!=='start' || !(err instanceof BusReadError) || !Object.hasOwn(HIRE_START_REFUSALS,err.code)) return refuse(busCode(err,step==='start'?'outcome-unknown':'confirmation-unavailable')); @@ -171,11 +185,12 @@ export async function decisionHTTP(req, res, { path, decide, session, live, conf const action = ordinary ? 'answer' : value.choice === v.approve.key ? 'approve' : 'deny'; if (live() !== session) return refuse('sign-in-required'); if(value.adjust!==undefined && v.kind!=='hire')return refuse('invalid-request'); - const confirmation = confirmations.issue({ session, business: v.business, decision: id, choice: value.choice, digest: v.digest, ...(v.kind==='hire'?{kind:'hire',...(value.adjust===undefined?{}:{adjust:structuredClone(value.adjust)})}:{}) }); + const binding = v.kind === 'hire' ? bindingOf(v) : null; + const confirmation = confirmations.issue({ session, business: v.business, decision: id, choice: value.choice, digest: v.digest, ...(v.kind==='hire'?{kind:'hire',...(value.adjust===undefined?{}:{adjust:structuredClone(value.adjust)}),...(binding?{change:binding.change}:{})}:{}) }); if (!confirmation) return refuse('confirmation-unavailable'); line(`action=${action}`); return json(res, 200, { id, question: typeof v.question === 'string' ? v.question : '', action, choice: value.choice, text: chosen.text, - ...(v.kind==='hire'?{kind:'hire',flagged:v.flagged,credentialLines:v.credentialLines,expiresAt:v.expiresAt}:ordinary ? { kind: 'decision' } : { grant: v.grant }), confirmation }); + ...(v.kind==='hire'?{kind:'hire',flagged:v.flagged,credentialLines:v.credentialLines,expiresAt:v.expiresAt,...(binding?{binding}:{})}:ordinary ? { kind: 'decision' } : { grant: v.grant }), confirmation }); } const keys = Object.keys(value); if (keys.length !== 2 || !keys.includes('choice') || !keys.includes('confirmation') || typeof value.choice !== 'string') return refuse('invalid-request'); @@ -189,7 +204,8 @@ export async function decisionHTTP(req, res, { path, decide, session, live, conf } catch (err) { return refuse(busCode(err, 'outcome-unknown')); } if (r?.id !== id || r.op !== 'resolved' || r.choice !== held.choice) return refuse('outcome-unknown'); line(`choice=${JSON.stringify(held.choice.slice(0, 64))}${r.grant ? ` grant=${r.grant}` : ''}`); - return json(res, 200, { id, op: 'resolved', choice: r.choice, ...(r.grant === 'started' ? { grant: 'started' } : {}) }); + return json(res, 200, { id, op: 'resolved', choice: r.choice, ...(r.grant === 'started' ? { grant: 'started' } : {}), + ...(held.change && r.choice === 'yes' ? { next: BINDING_NEXT[held.change] } : {}) }); } function json(res, status, body) { res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }); diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index c5a961762..9b9acaed2 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -396,7 +396,12 @@ let canDecide = false, ssoOn = false, answer = null; document.addEventListener('mosaic-signed-out', () => { answer = null; }); const ACTIONS = { approve: 'Approve', deny: 'Deny' }; - const hireLines = c => c?.kind !== 'hire' ? '' : `

Flagged grants — owner approval required

Requested credential scopes — owner approval required

Expires ${txt(c.expiresAt)}

`; + const hireLines = c => c?.kind !== 'hire' ? '' : `

Flagged grants — owner approval required

Requested credential scopes — owner approval required

Expires ${txt(c.expiresAt)}

${bindingLine(c)}`; + // #1873 CB5: a copy credential binding decision names its copy and whether it binds or unbinds; + // the scope lines above are the bus's computed ones. The confirmation says `change`; the inbox + // row carries the bus's preview, where an unbind is `after: null`. + const bindingChange = b => b.change === 'unbind' || (b.change === undefined && b.after === null) ? 'unbind' : 'bind'; + const bindingLine = c => c?.binding && typeof c.binding === 'object' ? `

Credential binding

${bindingChange(c.binding) === 'unbind' ? 'Unbind and revoke the credentials of' : 'Bind credentials for'} copy ${txt(c.binding.instance)}.

` : ''; const hireAdjustment = c => { if(c?.kind!=='hire' || !c.role)return ''; const list=(key,values)=>(values??[]).map((v,i)=>``).join(' '); @@ -478,7 +483,7 @@ let body; if (a.result) { const r = a.result; - body = `

${['decision','hire'].includes(r.kind) ? 'Recorded' : r.action === 'approve' ? 'Approved' : 'Denied'}: you chose “${txt(r.choice)}”, ${txt(r.text)}.${['decision','hire'].includes(r.kind) ? '' : ` ${r.grant === 'started' ? 'The grant executor started.' : r.action === 'approve' ? 'The bus started no grant for it.' : 'Nothing starts for a denial.'}`} History below shows it once the bus is read again.

${window.MosaicInbox?.receipt?.(r, a.decision) ?? ''}`; + body = `

${['decision','hire'].includes(r.kind) ? 'Recorded' : r.action === 'approve' ? 'Approved' : 'Denied'}: you chose “${txt(r.choice)}”, ${txt(r.text)}.${['decision','hire'].includes(r.kind) ? '' : ` ${r.grant === 'started' ? 'The grant executor started.' : r.action === 'approve' ? 'The bus started no grant for it.' : 'Nothing starts for a denial.'}`} History below shows it once the bus is read again.

${r.next ? `

${txt(r.next)}

` : ''}${window.MosaicInbox?.receipt?.(r, a.decision) ?? ''}`; } else if (a.confirm) { const c = a.confirm, label = `Confirm ${c.action}`; body = `

${label}

@@ -548,7 +553,7 @@ if (answer !== a) { if (res?.type === 'opaqueredirect') signOut(); else render(false); return; } if (res?.type === 'opaqueredirect') { a.error = { code: 'sign-in-required', message: 'Sign in again before answering. The sign-in proxy redirected the answer, so it never reached the Console.' }; paintDecide('#decide-status'); signOut(); return; } if (res?.ok && json?.id === a.id && json.op === 'resolved' && json.choice === c.choice) { - a.result = { kind: c.kind, action: c.action, choice: c.choice, text: c.text, grant: json.grant ?? null, grantDetails: c.grant ?? null }; + a.result = { kind: c.kind, action: c.action, choice: c.choice, text: c.text, grant: json.grant ?? null, grantDetails: c.grant ?? null, next: typeof json.next === 'string' ? json.next : null }; paintDecide('#decide-status'); announce(['decision','hire'].includes(c.kind) ? 'Recorded' : c.action === 'approve' ? 'Approved' : 'Denied'); render(false); } else { a.error = decideRefusal(res, json, 'outcome-unknown'); paintDecide('#decide-status'); announce(`Not answered: ${a.error.message}`); } } diff --git a/packages/webui/src/public/workspace.js b/packages/webui/src/public/workspace.js index 56307107a..24063ec70 100644 --- a/packages/webui/src/public/workspace.js +++ b/packages/webui/src/public/workspace.js @@ -283,8 +283,14 @@ const NOT_RUNNING = ['s-idle', '–', 'not running']; // A copy's status: running or not as the bus reports its runs, or why it can't launch. const CANT = ['s-error', '▲', "can't launch"]; - const copyWhy = (c) => (c.state === 'unbound' ? `no binding in this organization for ${(c.missing || []).join(', ')}` : c.reason || 'refused'); - const copyDot = (name, c, agents) => (c.state === 'instance' ? activity(name, c, agents) : CANT); + // #1873 CB5: the bus adds `binding` to a copy that needs a credential binding: its status code and + // the owner's next step, fixed text from the bus. A booted copy whose binding is not ready can't + // launch, and says why. + const bindingNext = (c) => (typeof c?.binding?.next === 'string' && c.binding.status !== 'ready' ? c.binding.next : ''); + const copyBlocked = (c) => c.state !== 'instance' || Boolean(bindingNext(c)); + const copyWhy = (c) => (c.state === 'unbound' ? [`no binding in this organization for ${(c.missing || []).join(', ')}`, bindingNext(c)].filter(Boolean).join('. ') + : c.state === 'instance' ? bindingNext(c) : c.reason || 'refused'); + const copyDot = (name, c, agents) => (copyBlocked(c) ? CANT : activity(name, c, agents)); // The bus names each copy's instance. Find an agent's copy by its name and project, never by // rebuilding the instance name: a collision refuses one entry that lists every claimant. const copyFor = (copies, name, project = null) => { @@ -329,7 +335,7 @@ if (inst === null) return 'status unavailable'; const { key, copy: c } = copyFor(mine?.copies, a.name, a.level === 'project' ? a.project : null); if (!c) return 'starts with the next bus start'; - return `${dot(...copyDot(key, c, mine.agents), true)}${c.state === 'instance' ? '' : `${esc(copyWhy(c))}`}`; + return `${dot(...copyDot(key, c, mine.agents), true)}${copyBlocked(c) ? `${esc(copyWhy(c))}` : ''}`; } if (inst === null) return 'status unavailable'; return dot(...(inst[a.name] ? activity(a.name, inst[a.name], mine.agents) : NOT_RUNNING), true); @@ -378,7 +384,7 @@ const copyPill = (copies, agents, name, project, small) => { const { key, copy: c } = copyFor(copies, name, project); const mark = copies === null ? ['s-unknown', '?', 'status unavailable'] : !c ? ['s-unknown', '?', 'starts with the next bus start'] : copyDot(key, c, agents); - const why = c && c.state !== 'instance' ? `${esc(name)}: ${esc(copyWhy(c))}` : ''; + const why = c && copyBlocked(c) ? `${esc(name)}: ${esc(copyWhy(c))}` : ''; return `${dot(...mark)}${esc(name)} ${esc(small)}${why}`; }; // Root: one copy per organization, each running inside that organization; an opt-out is said. diff --git a/packages/webui/tests/decision-http.test.mjs b/packages/webui/tests/decision-http.test.mjs index 63cf5d086..7a2e49322 100644 --- a/packages/webui/tests/decision-http.test.mjs +++ b/packages/webui/tests/decision-http.test.mjs @@ -4,7 +4,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { BusReadError } from '../src/bus.mjs'; -import { DECISION_REFUSALS, createConfirmations, decisionHTTP } from '../src/decision-http.mjs'; +import { BINDING_NEXT, DECISION_REFUSALS, createConfirmations, decisionHTTP } from '../src/decision-http.mjs'; const ORIGIN = 'https://console.test'; const DIGEST = 'a'.repeat(64); @@ -353,3 +353,60 @@ test('D4 templates, confirmation and resolve keep their open mapping for a defin const ok=await s.confirm('yes');assert.equal(ok.status,200); refused(await s.resolve({choice:'yes',confirmation:ok.json().confirmation}),'outcome-unknown'); }); + +// #1873 CB5: a copy credential binding decision on the Console. The confirmation carries the bus's +// computed scope lines, the copy's name and whether it binds or unbinds, and nothing else of the +// binding; the approved answer carries the owner's fixed next step. The sentinel stands for a token +// the bus should never send: placed in every binding field the bus could add, it never reaches a +// response or a log line. +const SENTINEL='sentinel-0123456789abcdef0123456789abcdef01234567'; +const bindingPreview=(after)=>({id:'d1',business:'demo',kind:'hire',question:'bind credentials for copy researcher?',digest:DIGEST, + options:[{key:'yes',text:'Approve'},{key:'no',text:'Deny'}],flagged:[],credentialLines:[{service:'gitea',scope:'read:repository'}],expiresAt:'2099-01-01T00:00:00.000Z', + binding:{instance:'researcher',source:{level:'root',name:SENTINEL,project:null},copyId:SENTINEL,fresh:true,orgIncarnation:SENTINEL,definition:{ref:SENTINEL,sha256:SENTINEL}, + before:{gitea:{slot:SENTINEL,grantId:SENTINEL,scopes:['read:repository'],resources:{projects:['stack']}}},after,generation:0}}); +const leaks=(s,...texts)=>texts.filter(t=>t.includes(SENTINEL)||t.includes(SENTINEL.slice(0,16))).length; +test('CB5 binding confirmation names the copy and the change with the computed scope lines, and the approval names the next step; nothing else of the binding leaves',async()=>{ + const after={gitea:{slot:'self',scopes:['read:repository'],resources:{projects:['stack']},token:SENTINEL}}; + const s=setup({answer:()=>bindingPreview(after),resolve:a=>({id:a.id,op:'resolved',choice:a.choice,transaction:SENTINEL,binding:{token:SENTINEL}})}); + const c=await s.confirm('yes');assert.equal(c.status,200,c.text); + const body=c.json(); + assert.deepEqual({...body,confirmation:'x'},{id:'d1',question:'bind credentials for copy researcher?',action:'answer',choice:'yes',text:'Approve',kind:'hire', + flagged:[],credentialLines:[{service:'gitea',scope:'read:repository'}],expiresAt:'2099-01-01T00:00:00.000Z',binding:{instance:'researcher',change:'bind'},confirmation:'x'}); + const r=await s.resolve({choice:'yes',confirmation:body.confirmation});assert.equal(r.status,200,r.text); + assert.deepEqual(r.json(),{id:'d1',op:'resolved',choice:'yes',next:BINDING_NEXT.bind}); + assert.equal(s.calls[1].verb,'hire.resolve.console'); + assert.equal(leaks(s,c.text,r.text,...s.lines),0); + assert.match(s.lines[0],/ step=confirmation action=answer$/);assert.match(s.lines[1],/ step=resolve choice="yes"$/); +}); +test('CB5 an unbind says the bus revokes; a denial carries no next step; a malformed binding is not echoed',async()=>{ + const u=setup({answer:()=>bindingPreview(null),resolve:a=>({id:a.id,op:'resolved',choice:a.choice})}); + const uc=await u.confirm('yes');assert.deepEqual(uc.json().binding,{instance:'researcher',change:'unbind'}); + const ur=await u.resolve({choice:'yes',confirmation:uc.json().confirmation}); + assert.deepEqual(ur.json(),{id:'d1',op:'resolved',choice:'yes',next:BINDING_NEXT.unbind}); + const d=setup({answer:()=>bindingPreview(null),resolve:a=>({id:a.id,op:'resolved',choice:a.choice})}); + const dc=await d.confirm('no'); + assert.deepEqual((await d.resolve({choice:'no',confirmation:dc.json().confirmation})).json(),{id:'d1',op:'resolved',choice:'no'}); + // An instance name the subject check refuses, or an after that is neither null nor an object, sends + // no binding field (the copy name is the only binding value the page shows). + for(const bad of [{instance:'../'+SENTINEL,after:null},{instance:'researcher',after:[SENTINEL]},{instance:'researcher',after:SENTINEL}]){ + const b=setup({answer:()=>({...bindingPreview(null),binding:{...bindingPreview(null).binding,...bad}}),resolve:a=>({id:a.id,op:'resolved',choice:a.choice})}); + const bc=await b.confirm('yes');assert.equal(bc.status,200,bc.text); + assert.equal(Object.hasOwn(bc.json(),'binding'),false,bc.text); + const br=await b.resolve({choice:'yes',confirmation:bc.json().confirmation}); + assert.equal(Object.hasOwn(br.json(),'next'),false,br.text); + assert.equal(leaks(b,bc.text,br.text,...b.lines),0); + } + assert.equal(leaks(u,uc.text,ur.text,...u.lines,...d.lines),0); +}); +test('CB5 a binding recorded and approved through the Console start names the next step by its shape, and only a binding start does',async()=>{ + const s=setup({resolve:()=>({id:'b1',op:'resolved',choice:'yes',binding:{token:SENTINEL}})}); + const bind={op:'change',level:'root',name:'researcher',reason:'token '+SENTINEL,binding:{services:{gitea:{scopes:['read:repository'],projects:['stack']}}}}; + const r=await s.run('/api/decisions/hire/start',request({body:{business:'demo',hire:bind}})); + assert.equal(r.status,200,r.text);assert.deepEqual(r.json(),{id:'b1',op:'resolved',choice:'yes',next:BINDING_NEXT.bind}); + const u=await s.run('/api/decisions/hire/start',request({body:{business:'demo',hire:{...bind,binding:{services:null}}}})); + assert.deepEqual(u.json(),{id:'b1',op:'resolved',choice:'yes',next:BINDING_NEXT.unbind}); + const h=await s.run('/api/decisions/hire/start',request({body:{business:'demo',hire:START_HIRE}})); + assert.deepEqual(h.json(),{id:'b1',op:'resolved',choice:'yes'}); + assert.equal(leaks(s,r.text,u.text,h.text,...s.lines),0); + for(const t of Object.values(BINDING_NEXT))assert.equal(leaks(s,t),0); +}); diff --git a/packages/webui/tests/hire-console-browser.test.mjs b/packages/webui/tests/hire-console-browser.test.mjs index aa20ad82b..9c45d6817 100644 --- a/packages/webui/tests/hire-console-browser.test.mjs +++ b/packages/webui/tests/hire-console-browser.test.mjs @@ -4,6 +4,7 @@ import {fixture} from './fixture.mjs'; import {mkdir} from 'node:fs/promises'; import {join} from 'node:path'; import {browser} from './browser.mjs'; +import {BINDING_NEXT} from '../src/decision-http.mjs'; for(const width of [1440,390])test(`A4 Console hire start and narrowed confirmation at ${width}px`,{timeout:120000},async t=>{ const f=await fixture(),b=await browser({machine:false});t.after(async()=>{await b.close();await f.close();}); await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`(()=>{ @@ -48,3 +49,49 @@ for(const width of [1440,390])test(`A4 Console hire start and narrowed confirmat await b.evaluate('document.querySelector("[data-decide=confirm]").click()');await wait('document.querySelector("#decide-status")?.textContent.startsWith("Recorded")'); posts=await b.evaluate('window.__posts');assert.deepEqual(Object.keys(posts.find(x=>x.p.endsWith('/resolve')).body).sort(),['choice','confirmation']); }); +// #1873 CB5: a copy credential binding decision on its decision page. The inbox row carries the bus's +// preview (an unbind is `after: null`); the page names the copy and the change and lists the computed +// scope lines, the confirmation says the change, and the receipt adds decision-http's fixed next step. +// No value besides the copy's instance reaches the page: a sentinel in every other binding field never shows. +for(const change of ['bind','unbind'])test(`CB5 Console binding decision: ${change} confirmation and receipt`,{timeout:120000},async t=>{ + const SENTINEL='cb5-sentinel-7f3a9c41d2e8b6a0'; + const f=await fixture(),b=await browser({machine:false,args:['--disable-extensions']});t.after(async()=>{await b.close();await f.close();}); + const after=change==='unbind'?null:{gitea:{scopes:['read:repository'],projects:['web'],slot:SENTINEL}}; + const binding={instance:'acme/researcher',source:'root',copyId:SENTINEL,fresh:false,orgIncarnation:SENTINEL,definition:SENTINEL,before:{gitea:{grantId:SENTINEL}},after,generation:2}; + const hire={kind:'hire',flagged:[],credentialLines:[{service:'gitea',scope:'read:repository'}],expiresAt:'2099-01-01T00:00:00.000Z',binding,options:[{key:'yes',text:'Approve'},{key:'no',text:'Deny'}]}; + const d={id:'d2',at:'2026-11-12T00:00:00.000Z',raised_by_role:'jason',raised_by_run:null,class:'gated',action:'role.hire',route_to:'human',question:`${change} credentials for copy acme/researcher?`,options:hire.options,blocking:false,console:hire}; + await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`(()=>{ + const real=fetch;window.__posts=[];const d=${JSON.stringify(d)}; + const json=v=>new Response(JSON.stringify(v),{headers:{'content-type':'application/json'}}); + window.fetch=async(url,init={})=>{ + const p=new URL(url,location.href).pathname; + if(p==='/api/config')return json({sso:true,send:true,decide:true}); + if(p==='/api/business')return json({business:{id:'acme',projects:[]}}); + if(p==='/api/bus/inbox')return json({rows:[d]}); + if(p==='/api/bus/trail')return json({rows:[{...d,table:'decisions'}]}); + if(p==='/api/bus/agents'||p==='/api/bus/messages'||p==='/api/chat/projects'||p==='/api/chat/threads')return json({rows:[]}); + if(p.startsWith('/api/decisions/')){ + const body=JSON.parse(init.body);window.__posts.push({p,body}); + if(p.endsWith('/confirmation'))return json({id:'d2',kind:'hire',action:'answer',question:d.question,choice:body.choice,text:'Approve',flagged:[],credentialLines:d.console.credentialLines,expiresAt:d.console.expiresAt,binding:{instance:'acme/researcher',change:${JSON.stringify(change)}},confirmation:'c'.repeat(64)}); + return json({id:'d2',op:'resolved',choice:body.choice,next:${JSON.stringify(BINDING_NEXT[change])}}); + } + if(p==='/api/processing'||p==='/api/bus-status')return json({error:'unavailable'}); + return real(url,init); + }; + })()`}); + const wait=expr=>b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(${expr})return;await new Promise(r=>setTimeout(r,50));}throw Error('Timed out: '+${JSON.stringify(expr)})})()`); + const text=()=>b.evaluate('document.body.innerText'); + const line=change==='unbind'?'Unbind and revoke the credentials of copy acme/researcher.':'Bind credentials for copy acme/researcher.'; + await b.viewport(1440,900);await b.navigate(f.base+'/#/inbox/d2');await wait('document.querySelector("#decide-section [data-binding-change]")'); + assert.equal(await b.evaluate('document.querySelector("#decide-section [data-binding-change]").dataset.bindingChange'),change); + assert.equal(await b.evaluate('document.querySelector("#decide-section [data-binding-change]").textContent'),line); + assert.match(await b.evaluate('document.querySelector("#decide-section").innerText'),/gitea: read:repository/); + assert.equal(await b.evaluate('!!document.querySelector("#hire-adjust")'),false); + await b.evaluate('document.querySelector(\'[data-decide="option-0"]\').click()');await wait('document.querySelector("[data-decide=confirm]")'); + assert.equal(await b.evaluate('document.querySelector("#decide-section [data-binding-change]").textContent'),line); + await b.evaluate('document.querySelector("[data-decide=confirm]").click()');await wait('document.querySelector("#decide-status")?.textContent.startsWith("Recorded")'); + assert.equal(await b.evaluate('document.querySelector("[data-binding-next]")?.textContent'),BINDING_NEXT[change]); + const posts=await b.evaluate('window.__posts');assert.deepEqual(Object.keys(posts.find(x=>x.p.endsWith('/resolve')).body).sort(),['choice','confirmation']); + assert.equal(JSON.stringify(posts).includes(SENTINEL),false); + const page=await text();assert.equal(page.includes(SENTINEL),false);assert.equal(page.includes(SENTINEL.slice(0,16)),false); +}); diff --git a/packages/webui/tests/unified-workspace-browser.test.mjs b/packages/webui/tests/unified-workspace-browser.test.mjs index 3ad71c2ef..8643cdffe 100644 --- a/packages/webui/tests/unified-workspace-browser.test.mjs +++ b/packages/webui/tests/unified-workspace-browser.test.mjs @@ -554,7 +554,8 @@ test('agents grid takes a running copy, an unbound copy and a refused project fr assert.deepEqual(pills, [['gate', 'instance', 'running'], ['researcher', 'unbound', "can't launch"], ['checker', 'instance', 'not running'], ['lint', 'refused', "can't launch"]]); const why = await b.evaluate('Object.fromEntries([...document.querySelectorAll(".ws-levels [data-org=ddigital] [data-copy-why]")].map(n => [n.dataset.copyWhy, n.innerText.trim()]))'); assert.deepEqual(Object.keys(why), ['researcher', 'lint.web']); - assert.equal(why.researcher, 'researcher: no binding in this organization for gitea'); + // CB5: the bus adds the binding's next step for a copy missing gitea, a bindable service. + assert.equal(why.researcher, 'researcher: no binding in this organization for gitea. credentials.gitea needs an owner-approved binding.'); assert.match(why['lint.web'], /^lint: project web refuses its agents: .*ghost/); const text = await b.evaluate('document.body.innerText'); for (const value of [SECRET, dir]) assert.equal(text.includes(value), false, value); @@ -625,3 +626,48 @@ test('agents grid shows a running copy, an unbound copy and a refused project wi } } }); + +// #1873 CB5: a copy that needs a credential binding carries `binding` from its bus: the status code and +// the owner's next step, copy-binding-status.mjs's fixed text. A booted copy whose binding is revoked +// can't launch and says the next step; an unbound copy missing gitea adds the step after the services; +// a ready binding launches as before with no reason line. +test('agents grid shows a copy\'s binding status and next step, and a ready binding launches', async t => { + const { checkRootAgents } = await import('../../organization/src/index.mjs'); + const { COPY_BINDING_STATUS } = await import('../../organization/src/copy-binding-status.mjs'); + const rolesDir = fileURLToPath(new URL('../../../roles', import.meta.url)); + const root = { state: 'ok', ...checkRootAgents({ agentsVersion: 1, agents: { + researcher: { definition: 'research' }, + reviewer: { definition: 'reviewer' }, + } }, { rolesDir }) }; + const DOCS = { ddigital: { roles: { chief: { definition: 'chief-of-staff' } }, projects: {} }, forge: { roles: { chief: { definition: 'chief-of-staff' } }, projects: {} } }; + const copy = (name, state, extra = {}) => ({ name, level: 'root', project: null, definition: name === 'reviewer' ? 'reviewer' : 'research', state, running: [], ...extra }); + const binding = (status) => ({ status, next: COPY_BINDING_STATUS[status] }); + const copies = { + ddigital: { researcher: copy('researcher', 'instance', { bound: ['gitea'], binding: binding('credential-revoked') }), + reviewer: copy('reviewer', 'unbound', { missing: ['gitea'], binding: binding('issue-required') }) }, + forge: { researcher: copy('researcher', 'instance', { bound: ['gitea'], running: ['r4'], binding: binding('ready') }), + reviewer: copy('reviewer', 'unbound', { missing: ['vikunja'] }) }, + }; + const orgs = workspaceOrgs({ copies }); + const organizations = { ...orgs, members: async () => Object.entries(DOCS).map(([id, doc]) => ({ id, doc })) }; + const agentLevels = { loadRoot: () => root, rolesDir, ctx: { configDir: '/cfg', dataRoot: '/data', instance: 'test' } }; + const server = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), organizations, agentLevels, log: () => {} }); t.after(() => close(server)); + const b = await browser({ machine: false, args: ['--disable-extensions'] }); t.after(() => b.close()); + await b.viewport(1440, 900); + await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/ddigital/agents`); + await waitFor(b)('document.querySelectorAll(".ws-levels [data-org=ddigital] [data-copy-state], .ws-levels [data-org=forge] [data-copy-state]").length === 4'); + const pills = await b.evaluate('[...document.querySelectorAll(".ws-levels [data-org=ddigital], .ws-levels [data-org=forge]")].flatMap(c => [...c.querySelectorAll("[data-copy-state]")].map(p => [c.dataset.org, p.dataset.levelAgent, p.dataset.copyState, p.querySelector(".ws-dot").title]))'); + assert.deepEqual(pills, [ + ['ddigital', 'researcher', 'instance', "can't launch"], ['ddigital', 'reviewer', 'unbound', "can't launch"], + ['forge', 'researcher', 'instance', 'running'], ['forge', 'reviewer', 'unbound', "can't launch"], + ]); + const why = await b.evaluate('Object.fromEntries([...document.querySelectorAll(".ws-levels [data-org=ddigital], .ws-levels [data-org=forge]")].flatMap(c => [...c.querySelectorAll("[data-copy-why]")].map(n => [`${c.dataset.org}:${n.dataset.copyWhy}`, n.innerText.trim()])))'); + assert.deepEqual(why, { + 'ddigital:researcher': `researcher: ${COPY_BINDING_STATUS['credential-revoked']}`, + 'ddigital:reviewer': `reviewer: no binding in this organization for gitea. ${COPY_BINDING_STATUS['issue-required']}`, + 'forge:reviewer': 'reviewer: no binding in this organization for vikunja', + }); + const rows = await b.evaluate('Object.fromEntries([...document.querySelectorAll("[data-agents-available] tbody tr")].map(tr => [tr.cells[0].innerText.trim().split(/\\s/)[0], tr.cells[4].innerText.replace(/\\s+/g, " ").trim()]))'); + assert.equal(rows.researcher, `▲ can't launch ${COPY_BINDING_STATUS['credential-revoked']}`); + assert.equal(rows.reviewer, `▲ can't launch no binding in this organization for gitea. ${COPY_BINDING_STATUS['issue-required']}`); +});