Compare commits

...
Author SHA1 Message Date
jason.woltje 9b3cbe4296 Test that a hire receipt survives an overlapping packs reload
Two forced-order tests for the hire click. They fail without the packs state fix in 5a7e6765f.
2026-11-20 23:25:29 -06:00
jason.woltje 1e8a20074d Keep a newer autonomy read that lands during a save
Re-check of 7cba209dc (P3-1): a save can commit, another writer can
commit after it, and a poll can draw that newer read before the save
answers. The save then wrote its own older values into the state, and
the new redraw painted them over the newer form. It failed closed, but
the page showed older values.

A save that answers now writes its values into the state only when the
state still holds the revision it sent or the one it got back. Any other
revision was written after the save, so it stays. The redraw draws from
that state, so it never paints older values.

The older-read test waits for the draw as well as the read, since the
dashboard draws only after all its reads (re-check P3-2). A new test
forces the newer-writer order.
2026-11-20 22:48:55 -06:00
jason.woltje 2e78c7e593 Draw an autonomy save over a clean form drawn from an older read
Review of a4a035d17 (P3-1): a reload whose read was served before a save
committed could redraw a clean form while the save was in flight. The
save then wrote its revision to the form it started on, which the page
no longer drew. The drawn form showed the old levels next to the receipt,
and a second save before the next poll was refused as a revision
conflict.

A save that answers now draws the settings section again from the saved
state when the drawn form is a different, clean form. A form the owner is
editing stays, so it saves against its own revision and fails closed.
The live section lookup skips decision notices for the hold check too.

The older-read test now waits on the held read by the revision it
carries, so a poll in the window cannot move its count (P3-3). A new test
forces the P3-1 order and checks the drawn form before any reload.
2026-11-20 22:48:55 -06:00
jason.woltje fbfcd942be Keep an autonomy save or review receipt that overlaps a reload
The autonomy panel built a new state object on every load and copied the
status from the state it found when the load began. A save kept the old
object across its own request. So a save that answered while a poll or
an organization change was reading autonomy wrote its receipt and its new
revision to an object the page no longer drew, or the load copied the
empty status forward before the receipt existed. The next draw then
showed no receipt and the old revision, so the next save was refused as
a revision conflict. A trail review wrote its line only to the node it
started on, which a redraw replaces.

Each organization now keeps one state object. A load writes its read into
it when it ends. A load that began before the last applied read, or
before a save answered, is dropped. A save or review result is kept in
that state and written to the status line the page draws now.

Browser tests hold the fixture's calls to force each order of a save
against a reload, a review against a reload, and an older read that
answers after a newer one.
2026-11-20 22:48:55 -06:00
jason.woltje 5a7e6765f8 Keep a pack preview or receipt that overlaps a packs reload
The pack picker built a new state object on every load and copied the
preview and receipt from the state it found when the load began. A click
kept the old object across its own request. So a preview or a hire receipt
that answered while a poll or an apply's page reload was reading the packs
was written to an object the page no longer drew, or was copied away
before it existed. Under host load this dropped the project preview in the
SP6 pack picker test and the hire status in the pack hire test.

Each organization now keeps one state object. A load writes its read
fields into it when it ends, and a load that began before the last one
applied is dropped, so an older list never replaces a newer one.

One browser test holds the fixture's reads to force each order of the
overlap, a second forces an older packs read to answer last, and a third
holds a reload's packs read while an apply's receipt lands.
2026-11-20 20:33:47 -06:00
jason.woltje 69b3931c35 Resolve recheck follow-up cases 2026-11-20 19:43:53 -06:00
jason.woltje b7116be9c3 Address review of proxy administration follow-ups 2026-11-20 19:43:53 -06:00
jason.woltje 0f3135e36a Show unanswered organizations with offered models 2026-11-20 19:43:53 -06:00
jason.woltje b0dd4d3e2f Recognize organizations without a launch in model survey 2026-11-20 19:43:53 -06:00
jason.woltje e8c6c7e3a4 Test the 257 model limit boundary 2026-11-20 19:43:53 -06:00
jason.woltje fe671844ea Guard shared credential names with invalid account IDs 2026-11-20 19:43:53 -06:00
jason.woltje b3eaa8fd81 Preserve account removal success when refresh fails 2026-11-20 19:43:53 -06:00
jason.woltje 07baa87381 Clarify account removal ambiguity 2026-11-20 19:43:53 -06:00
jason.woltje 5e67fd9289 test(webui): wait for restart completion 2026-11-20 18:43:48 -06:00
jason.woltje ffc7db130f test(webui): enforce switch ordering in restart check 2026-11-20 18:43:48 -06:00
jason.woltje d6de22aaf8 test(webui): isolate browser waits and offline observation 2026-11-20 18:43:48 -06:00
16 changed files with 533 additions and 63 deletions

No files matched your search

+3 -3
View File
@@ -108,7 +108,7 @@ export class ProxyPage {
rows.push({ ...view(this.#providers, key.auth_index, provider, status, key.priority ?? group.priority), source: 'apikey', groupIndex, keyIndex, models: configured.map(m => m.alias || m.name) });
}
}
return { rows, groups };
return { rows, groups, credentialNames: response.files.map(row => row?.name).filter(identifier) };
}
#public(row) {
const { accountId, provider, displayName, status, priority } = row;
@@ -271,13 +271,13 @@ export class ProxyPage {
fields(args, ['accountId', 'confirm']);
if (typeof args.accountId !== 'string' || !/^[a-f0-9]{12}$/.test(args.accountId) || args.confirm !== true) refuse('invalid-request');
return this.#write(async () => {
const { rows, groups } = await this.#accounts();
const { rows, groups, credentialNames } = await this.#accounts();
const original = this.#lock ? structuredClone(groups) : null;
const matches = rows.filter(row => row.accountId === args.accountId);
if (matches.length !== 1) refuse('invalid-request');
const row = matches[0];
// The DELETE names a credential file; another listed account on the same name would go too.
if (row.source === 'oauth' && rows.some(r => r !== row && r.source === 'oauth' && r.name === row.name)) refuse('invalid-request');
if (row.source === 'oauth' && credentialNames.filter(name => name === row.name).length !== 1) refuse('invalid-request');
if (this.#lock && !isDeepStrictEqual(await this.#client.getUpstreamGroups(), original)) refuse('proxy-down');
this.#beforeMutation('proxy.account.remove');
try {
@@ -223,6 +223,14 @@ test('remove: two listed accounts on one credential name, or one account id list
await assert.rejects(d.call('proxy.account.remove', { accountId: id('oauth-one.json'), confirm: true }), { code: 'invalid-request' });
for (const x of [s, d]) { assert.equal(x.state.calls.some(c => !c.startsWith('GET ')), false); assert.equal(x.state.files.length, 2); }
});
test('remove: a credential with an unusable id still prevents deleting its shared name', async t => {
for (const badId of ['', null, 'x'.repeat(513)]) {
const s = await fakeManagement(t, { files: [oauth(), oauth({ id: badId, name: 'oauth-one.json' })] });
await assert.rejects(s.call('proxy.account.remove', { accountId: id('oauth-one.json'), confirm: true }), { code: 'invalid-request' });
assert.equal(s.state.calls.some(c => !c.startsWith('GET ')), false);
assert.equal(s.state.files.length, 2);
}
});
test('remove: under the lock, key groups that change between the read and the write refuse with proxy-down before the fence', async t => {
const fs = await import('node:fs'); const { join } = await import('node:path'); const { tmpdir } = await import('node:os');
const { createProxyLock } = await import('../src/proxy-lock.mjs');
@@ -240,8 +240,8 @@ export async function lifecycleFixture(t) {
}
async function consoleBrowser(t, f) {
const b = await browser(); t.after(() => b.close());
b.on('Fetch.requestPaused', ({ requestId, request: incoming }) => {
let b = await browser(); const consolePage = b; t.after(() => consolePage.close());
consolePage.on('Fetch.requestPaused', ({ requestId, request: incoming }) => {
const url = new URL(incoming.url);
if (incoming.method === 'POST') f.recordOwner(url.pathname);
const req = httpRequest({ host: '127.0.0.1', port: f.port, path: url.pathname + url.search, method: incoming.method,
@@ -249,9 +249,9 @@ async function consoleBrowser(t, f) {
const parts = []; res.on('data', part => parts.push(part)); res.on('end', () => {
const responseHeaders = Object.entries(res.headers).filter(([name]) => !['connection','keep-alive','transfer-encoding'].includes(name))
.flatMap(([name, value]) => (Array.isArray(value) ? value : [value]).map(value => ({ name, value: String(value) })));
b.call('Fetch.fulfillRequest', { requestId, responseCode: res.statusCode, responseHeaders, body: Buffer.concat(parts).toString('base64') }).catch(() => {});
consolePage.call('Fetch.fulfillRequest', { requestId, responseCode: res.statusCode, responseHeaders, body: Buffer.concat(parts).toString('base64') }).catch(() => {});
});
}); req.on('error', () => b.call('Fetch.failRequest', { requestId, errorReason: 'Failed' }).catch(() => {})); req.end(incoming.postData);
}); req.on('error', () => consolePage.call('Fetch.failRequest', { requestId, errorReason: 'Failed' }).catch(() => {})); req.end(incoming.postData);
});
await b.call('Fetch.enable', { patterns: [{ urlPattern: ORIGIN + '/*', requestStage: 'Request' }] });
const s = await f.current(); await b.navigate(`${ORIGIN}/#/inbox/${s.selection.decision}`);
@@ -267,7 +267,10 @@ async function consoleBrowser(t, f) {
await wait('document.querySelector("#decide-status")?.textContent.startsWith("Recorded")');
},
async offline(html) {
await b.call('Fetch.disable');
// The Console can still poll during navigation. Close it before observing the downloaded file.
await b.close();
b = await browser(); const offlinePage = b; t.after(() => offlinePage.close());
external.length = 0;
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: `window.__now=1000;Date.now=()=>window.__now;window.__ticks=[];window.setInterval=fn=>{window.__ticks.push(fn);return window.__ticks.length;};window.__sounds=0;window.AudioContext=class{currentTime=0;destination={};resume(){}createOscillator(){return{connect(){},frequency:{value:0},start(){window.__sounds++},stop(){}}}createGain(){return{connect(){},gain:{value:0}}}};` });
await b.call('Network.enable'); await b.call('Network.emulateNetworkConditions', { offline: true, latency: 0, downloadThroughput: 0, uploadThroughput: 0 });
b.on('Network.requestWillBeSent', ({ request }) => { if (/^https?:/.test(request.url)) external.push(request.url); });
+14 -8
View File
@@ -157,20 +157,25 @@ export function offeredControl({ dataRoot, riders, receipt, exclusive, rootAgent
try { list = await riders(); } catch { throw failure('outcome-unknown'); }
const named = (Array.isArray(list) ? list : []).filter(r => typeof r?.id === 'string' && ORG_ID.test(r.id));
const riding = named.filter(r => r.cliproxy === true);
if (!riding.length) throw failure('not-configured');
const unanswered = new Set(named.filter(r => typeof r.cliproxy !== 'boolean').map(r => r.id));
if (!riding.length) throw failure(unanswered.size ? 'proxy-down' : 'not-configured');
let root;
try { root = typeof rootAgents === 'function' ? await rootAgents() : undefined; } catch { root = undefined; }
const answers = await Promise.all(riding.map(async r => {
let routes = null, named = null;
try { routes = await r.call('routes'); } catch { routes = null; }
try { named = typeof r.file === 'function' ? modelsNamed((await r.file())?.document) : null; } catch { named = null; }
let routes = null, named = null, noLaunchReply = false, document = null;
try { routes = await r.call('routes'); } catch (error) { noLaunchReply = error?.code === 'launch-not-configured'; }
try { document = typeof r.file === 'function' ? (await r.file())?.document : null; named = modelsNamed(document); } catch { named = null; }
// A separate file read can observe a newer launch than the bus did. Treat that race and
// unreadable files as unknown, never as proof that no model is in use.
const noLaunch = noLaunchReply && named !== null && !Object.hasOwn(document, 'launch');
const fromRoot = root === undefined ? null : rootModelsNamed(root, r.id);
return { id: r.id, routes, named: named && fromRoot ? [...named, ...fromRoot] : null };
return { id: r.id, routes, noLaunch, named: named && fromRoot ? [...named, ...fromRoot] : null };
}));
const providers = new Map(), usedBy = new Map();
let ready = false;
for (const { id, routes } of answers) {
for (const { id, routes, noLaunch } of answers) {
// routes explicitly refuses before reading a catalogue when the organization has no launch.
if (noLaunch) continue;
const c = routes?.catalogue;
if (c?.status !== 'ready' || !Array.isArray(c.models)) { unanswered.add(id); continue; }
ready = true;
@@ -181,8 +186,9 @@ export function offeredControl({ dataRoot, riders, receipt, exclusive, rootAgent
if (!providers.get(provider).includes(m.model)) providers.get(provider).push(m.model);
}
}
if (!ready) throw failure('proxy-down');
for (const { id, routes, named } of answers) {
if (!ready) throw failure(!unanswered.size && answers.every(a => a.noLaunch) ? 'not-configured' : 'proxy-down');
for (const { id, routes, named, noLaunch } of answers) {
if (noLaunch) continue;
if (!routes || typeof routes.instances !== 'object' || routes.instances === null || named === null) { unanswered.add(id); continue; }
const table = routes.providerModels && typeof routes.providerModels === 'object' ? routes.providerModels : {};
const legacy = routes.catalogue?.legacy && typeof routes.catalogue.legacy === 'object' ? routes.catalogue.legacy : {};
@@ -114,6 +114,38 @@ test('an organization whose usage is unknown (its file unreadable, its bus down,
}
});
test('a riding organization explicitly without launch is answered, while a bus failure remains unanswered', async t => {
const noLaunch = { ...rider('bolt', []), call: async () => { throw Object.assign(new Error('no launch'), { code: 'launch-not-configured' }); } };
const down = { ...rider('crux', []), call: async () => { throw new Error('down'); } };
const c = control(t, { riders: [rider('acme', [entry('zai', 'glm-5')]), noLaunch, down] });
assert.deepEqual((await c.models({ seed: true })).unanswered, ['crux']);
const onlyAnswered = control(t, { riders: [rider('acme', [entry('zai', 'glm-5')]), noLaunch] });
const view = await onlyAnswered.models({ seed: true });
assert.deepEqual(view.unanswered, []);
assert.equal(existsSync(offeredFile(onlyAnswered.dataRoot)), true);
await onlyAnswered.modelsSet({ provider: 'z.ai', on: [], revision: view.revision });
});
test('a no-launch response with a newer launch or unreadable file stays unanswered and blocks an unconfirmed switch off', async t => {
const noLaunch = async () => { throw Object.assign(new Error('no launch'), { code: 'launch-not-configured' }); };
for (const file of [async () => ({ document: { launch: { models: {} }, roles: {} } }), async () => { throw new Error('unreadable'); }, async () => ({ document: null })]) {
const c = control(t, { riders: [rider('acme', [entry('zai', 'glm-5')]), { ...rider('bolt', []), call: noLaunch, file }] });
const view = await c.models({ seed: true });
assert.deepEqual(view.unanswered, ['bolt']);
assert.equal(existsSync(offeredFile(c.dataRoot)), false);
await assert.rejects(c.modelsSet({ provider: 'z.ai', on: [], revision: view.revision }), { code: 'models-in-use' });
}
});
test('all riders confirmed without launch are not configured; a failed read is proxy-down', async t => {
const noLaunch = { ...rider('bolt', []), call: async () => { throw Object.assign(new Error('no launch'), { code: 'launch-not-configured' }); } };
const configured = control(t, { riders: [noLaunch] });
await assert.rejects(configured.models({ seed: true }), { code: 'not-configured' });
assert.equal(existsSync(offeredFile(configured.dataRoot)), false);
const down = control(t, { riders: [{ ...noLaunch, file: async () => { throw new Error('unreadable'); } }] });
await assert.rejects(down.models({ seed: true }), { code: 'proxy-down' });
});
test('in use counts every place the organization file names a model and the root agents it takes: project agents, root copies; not an excluded or assistant root agent, not launch.models itself', async t => {
const models = [entry('zai', 'glm-5'), entry('zai', 'glm-4.6'), entry('codex', 'gpt-5'), entry('codex', 'gpt-5-mini')];
const routes = { instances: { chief: { model: 'g5' } }, providerModels: { g5: entry('zai', 'glm-5'), g46: entry('zai', 'glm-4.6'), gpt: entry('codex', 'gpt-5'), mini: entry('codex', 'gpt-5-mini') } };
@@ -166,6 +198,9 @@ test(`a model kept on while its account is signed out counts against the ${MAX_O
// glm-0 is in use and this switches it off, but the list is too long first: no ask for a save that cannot be written.
await assert.rejects(c.modelsSet({ provider: 'z.ai', on: all.slice(1), revision: before.revision }), { code: 'models-invalid' }, `${all.length - 1} on plus 10 kept is past ${MAX_ON}`);
await assert.rejects(c.modelsSet({ provider: 'z.ai', on: all.slice(1), revision: before.revision, confirmInUse: true }), { code: 'models-invalid' });
// Exactly 257 including the 10 kept models must refuse before asking about glm-0.
assert.equal(all.slice(6).length + away.length, MAX_ON + 1);
await assert.rejects(c.modelsSet({ provider: 'z.ai', on: all.slice(6), revision: before.revision }), { code: 'models-invalid' });
assert.equal(readOffered(c.dataRoot).revision, before.revision);
assert.deepEqual(c.receipts, []);
const saved = await c.modelsSet({ provider: 'z.ai', on: all.slice(7), revision: before.revision, confirmInUse: true });
@@ -228,6 +263,7 @@ test('a damaged file: the read and the write answer outcome-unknown and write no
test('no organization riding is not-configured; none answering a ready catalogue is proxy-down; a busy lock refuses the write', async t => {
await assert.rejects(control(t, { riders: [] }).models(), { code: 'not-configured' });
await assert.rejects(control(t, { riders: [{ ...rider('acme', []), cliproxy: false }] }).models(), { code: 'not-configured' });
await assert.rejects(control(t, { riders: [{ ...rider('acme', []), cliproxy: undefined }] }).models(), { code: 'proxy-down' });
const down = { id: 'acme', cliproxy: true, call: async () => { throw new Error('down'); } };
await assert.rejects(control(t, { riders: [down, rider('bolt', [], { catalogue: { status: 'unavailable', models: [] } })] }).models(), { code: 'proxy-down' });
await assert.rejects(control(t, { riders: [rider('acme', [entry('zai', 'glm-5')])], busy: true }).modelsSet({ provider: 'z.ai', on: [], revision: 'a'.repeat(16) }), { code: 'proxy-admin-busy' });
+36 -8
View File
@@ -25,8 +25,27 @@
// E2E6 P1-1: a poll reloads this state; the last save's receipt and the open review list stay.
// A failed poll keeps the last good read only while the page holds the form (dirty, or a field has
// focus), so the held form is not dropped (review P3). A clean form shows the read error (re-check P3).
const held=org=>{const form=[...document.querySelectorAll('[data-autonomy-org]')].find(n=>n.dataset.autonomyOrg===org)?.querySelector('[data-autonomy-form]');return !!form&&(form.hasAttribute('data-live-dirty')||form.contains(document.activeElement));};
async function load(org) {const prev=states.get(org),keep={status:prev?.status??'',reviewOpen:prev?.reviewOpen===true};try{states.set(org,{...await call(org,''),...keep});}catch(error){states.set(org,prev&&!prev.error&&held(org)?{...prev,...keep}:{error:error.message,...keep});}}
// The settings section the page draws now for this organization (a decision notice carries the org too).
const live=org=>[...document.querySelectorAll('[data-autonomy-org]')].find(n=>n.dataset.autonomyOrg===org&&!n.hasAttribute('data-autonomy-decision'));
const held=org=>{const form=live(org)?.querySelector('[data-autonomy-form]');return !!form&&(form.hasAttribute('data-live-dirty')||form.contains(document.activeElement));};
// Each organization keeps one state object for the life of the page. A save or review keeps a reference
// to it across its own request, so a load that ends meanwhile writes its read into that object in place
// and never swaps it: the receipt lands where the next draw reads it. A load that began before the last
// applied read, or before a save answered, carries older values, so its answer is dropped.
const own=['status','reviewOpen','began','shown'];
function put(s,read) {for(const k of Object.keys(s))if(!own.includes(k))delete s[k];for(const [k,v]of Object.entries(read))if(!own.includes(k))s[k]=v;}
const stateOf=org=>{if(!states.has(org))states.set(org,{error:'Autonomy could not be read.',status:'',reviewOpen:false,began:0,shown:0});return states.get(org);};
async function load(org) {
const s=stateOf(org),began=++s.began;let read,failed=false;
try{read=await call(org,'');}catch(error){read={error:error.message};failed=true;}
if(began<s.shown)return;
s.shown=began;
if(failed&&!s.error&&held(org))return;
put(s,read);
}
// A result said on this organization's status line: kept in its state for the next draw, and written to
// the line the page draws now.
function say(org,text) {const s=stateOf(org);s.status=text;const line=live(org)?.querySelector('[data-autonomy-status]');if(line)line.textContent=text;}
function section(org) {
const s=states.get(org);
if(!s || s.error)return `<section class="panel" data-autonomy><h3>Autonomy</h3><p>${esc(s?.error??'Autonomy could not be read.')}</p></section>`;
@@ -51,13 +70,22 @@
}
document.addEventListener('submit',async e=>{
if(!e.target.matches('[data-autonomy-form]'))return;e.preventDefault();
const form=e.target,section=form.closest('[data-autonomy-org]'),org=section.dataset.autonomyOrg,s=states.get(org),fields=new FormData(form);
const form=e.target,org=form.closest('[data-autonomy-org]').dataset.autonomyOrg,s=states.get(org),fields=new FormData(form);
const autonomy=Object.fromEntries(classes.map(k=>[k,fields.get(k)]));autonomy.notices=fields.has('notices');autonomy.reverseWindowHours=Number(fields.get('reverseWindowHours'));
if(fields.get('authorityResolver'))autonomy.authorityResolver=fields.get('authorityResolver');
const button=form.querySelector('button[type="submit"]'),status=form.querySelector('[data-autonomy-status]');button.disabled=true;
const button=form.querySelector('button[type="submit"]');button.disabled=true;
let base=s.revision;try{if(form.dataset.revision)base=JSON.parse(form.dataset.revision);}catch{/* drawn without one */}
try{const r=await call(org,'',{revision:base,autonomy});s.revision=r.revision;s.autonomy=autonomy;s.levels=Object.fromEntries(classes.map(k=>[k,autonomy[k]]));s.status=`Saved. Receipt ${r.transaction}.`;form.dataset.revision=JSON.stringify(r.revision);delete form.dataset.liveDirty;status.textContent=s.status;}
catch(error){s.status=error.message;status.textContent=s.status;}finally{button.disabled=false;}
// A load that began before the save answered is dropped. A load that ended during the save read either
// the revision the save sent, from before it committed, or one at or after the save. One that is neither
// was written after the save by someone else: it stays, and the save's values do not replace it.
// A redraw during the save may have drawn a new form from an older read. A clean new form is drawn again
// from the state, which now holds the newest read known, so it shows that and saves against its revision.
// A new form the owner is editing stays: it saves against its own revision and fails closed.
try{const r=await call(org,'',{revision:base,autonomy}),sent=JSON.stringify(base);s.shown=++s.began;
if([sent,JSON.stringify(r.revision)].includes(JSON.stringify(s.revision))){s.revision=r.revision;s.autonomy=autonomy;s.levels=Object.fromEntries(classes.map(k=>[k,autonomy[k]]));}
form.dataset.revision=JSON.stringify(r.revision);delete form.dataset.liveDirty;s.status=`Saved. Receipt ${r.transaction}.`;
const el=live(org),drawn=el?.querySelector('[data-autonomy-form]');if(drawn&&drawn!==form&&!held(org))el.outerHTML=section(org);say(org,s.status);}
catch(error){say(org,error.message);}finally{button.disabled=false;}
});
// An edited form is dirty until it saves: holdLive keeps a dirty form through every poll.
const dirty=e=>{const form=e.target.closest?.('[data-autonomy-form]');if(form)form.dataset.liveDirty='1';};
@@ -71,8 +99,8 @@
const review=button.dataset.autonomyReview,reverse=button.hasAttribute('data-autonomy-reverse');
const body=review?{decisionClass:review}:reverse?{id:section.dataset.autonomyDecision}:{id:section.dataset.autonomyDecision,confirm:button.dataset.autonomyConfirm==='yes',...(button.dataset.autonomyConfirm==='no'?{reason:section.querySelector('[data-autonomy-reason]').value}:{})};
button.disabled=true;
try{const r=await call(org,review?'review':reverse?'reverse':'confirm',body);status.textContent=review?'Trail review recorded.':reverse?(r.restart||r.trailPending?'Reversal committed. Completion needs recovery: inspect the decision trail and the stopped agent before requesting relaunch.':'Reversal recorded.'):(body.confirm?'Confirmation recorded. Refresh the inbox for current state.':'Returned to arbiter. Refresh the inbox for current state.');}
catch(error){status.textContent=error.message;}finally{button.disabled=false;}
try{const r=await call(org,review?'review':reverse?'reverse':'confirm',body);if(review)return say(org,'Trail review recorded.');status.textContent=reverse?(r.restart||r.trailPending?'Reversal committed. Completion needs recovery: inspect the decision trail and the stopped agent before requesting relaunch.':'Reversal recorded.'):(body.confirm?'Confirmation recorded. Refresh the inbox for current state.':'Returned to arbiter. Refresh the inbox for current state.');}
catch(error){if(review)say(org,error.message);else status.textContent=error.message;}finally{button.disabled=false;}
});
window.MosaicAutonomy={load,section,notice};
})();
+13 -9
View File
@@ -767,7 +767,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
'proxy-uncertain': 'Mosaic could not confirm the remove: the model service is between writes. Check the service and the list before trying again.',
'proxy-down': 'The model service stopped answering, so Mosaic could not confirm the remove. Check the service and the list before trying again.',
'proxy-admin-busy': 'Another setup action is running. Try again when it finishes.',
'invalid-request': 'The model service no longer lists this account. Read the accounts again.',
'invalid-request': 'Mosaic could not identify one account to remove. It may no longer be listed, have a duplicate ID, or share a credential with another account. Read the accounts again.',
'human-required': 'Only the instance owner removes an account.',
};
async function adminCall(path, args) {
@@ -812,8 +812,10 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
removeBusy = true; removeAsk.error = null; paintAccounts();
try {
await adminCall('accounts/remove', { accountId: account.accountId });
removeAsk = null; message(`${name} account removed.`);
await refresh(); await setup.reread();
let removalMessage = `${name} account removed.`;
removeAsk = null; message(removalMessage);
try { await refresh(); } catch (error) { removalMessage += ` The account list could not be refreshed: ${error.message}`; message(removalMessage); }
await setup.reread({ onError: error => message(`${removalMessage} The setup status could not be refreshed: ${error.message}`) });
} catch (error) {
if (removeAsk) removeAsk.error = error.message; message(error.message);
// The outcome may be unknown: read the list again so it shows what the service holds now.
@@ -936,7 +938,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
'models-offered-conflict': 'The model list changed since this page read it. Read it again, then make your change.',
'models-invalid': 'The model service no longer lists one of these models. Read the list again.',
'proxy-down': 'No organization that uses your model service answered, so its models can\'t be listed now.',
'not-configured': 'No organization uses your model service yet. Its models show here once one does.',
'not-configured': 'No organization with a configured model launch uses your model service yet. Its models show here once one does.',
'proxy-admin-busy': 'Another change to the model service is running. Try again in a moment.',
'outcome-unknown': 'The outcome is unknown. Read the list again before you try again.',
};
@@ -953,8 +955,10 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
catch (error) { if (round === offeredRound) box.replaceChildren(el('p', offeredSays(error.code), 'small muted')); return; }
if (round !== offeredRound) return;
const providers = Array.isArray(view?.providers) ? view.providers : [];
if (!providers.length) { box.replaceChildren(el('p', 'Your model service lists no models yet.', 'small muted')); return; }
box.replaceChildren(...providers.map(p => offeredList(p, view.revision, open.has(p.provider), saved === p.provider)));
const quiet = Array.isArray(view?.unanswered) ? view.unanswered.filter(id => typeof id === 'string').map(id => window.MosaicOrg?.row?.(id)?.label || id) : [];
const notice = quiet.length ? [el('p', `Not answering now, so it is not known which models they use: ${quiet.join(', ')}. A model you switch off may stop working for them.`, 'offered-unanswered banner ref')] : [];
if (!providers.length) { box.replaceChildren(...notice, el('p', 'Your model service lists no models yet.', 'small muted')); return; }
box.replaceChildren(...notice, ...providers.map(p => offeredList(p, view.revision, open.has(p.provider), saved === p.provider)));
}
function offeredList(p, revision, open, saved) {
const name = String(p.label), models = Array.isArray(p.models) ? p.models : [];
@@ -1900,10 +1904,10 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
focusStep();
}
// True once the answer is painted, so a caller can say the list on the page is the new one.
async function load() {
async function load({ onError } = {}) {
if (!enabled || loading) return false; loading = true; let painted = false;
try { state = await admin('status'); setProviders(state.providers); causeRound++; if (state.next?.[0] === 'accounts' && triageSet === null) await readTriage(); paint(); painted = true; if (state.init.initialized) await accountsReady(); }
catch (error) { say(error.message, 'error'); if (providerKey === null) setProviders(null); }
catch (error) { say(error.message, 'error'); if (providerKey === null) setProviders(null); onError?.(error); }
finally { loading = false; }
return painted;
}
@@ -1978,7 +1982,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
start(config) { enabled = true; sendOk = config.proxyAdminSend === true; return load(); },
accounts(n) { accountCount = n; if (state) { paintService(); paintRestart(); paintOrgsCard(); paintTriageCard(); } },
// A sign-in, a key or a restart can change the next step: read the whole status again.
async reread() { if (!enabled) return; triageSet = null; await load(); },
async reread(options) { if (!enabled) return; triageSet = null; await load(options); },
enabled: () => enabled,
serviceDone: () => running(),
// An organization whose model list is ready, for Models offered. The open one first.
+17 -9
View File
@@ -62,21 +62,29 @@
}
// E2E6 P1-1, P2-2: a poll reloads the list but keeps the open preview, the project picked for each
// pack and the last receipt. A kept preview applies by its digest, so a stale one is refused by the bus.
// Each organization has one state object for the life of the page. A click keeps a reference to it
// across its own request, so a load that ends meanwhile updates the read fields in place and never
// swaps the object: the click's preview or receipt lands where the next draw reads it. A load that
// began before the last applied one carries older reads, so its answer is dropped.
async function load(org) {
const prev = states.get(org);
const s = { packs: null, applied: [], writable: false, error: null, projects: null, preview: prev?.preview ?? null, status: prev?.status ?? '', picks: prev?.picks ?? {} };
if (!states.has(org)) states.set(org, { packs: null, applied: [], writable: false, error: 'Starter packs could not be read.', projects: null, preview: null, status: '', picks: {}, began: 0, shown: 0 });
const s = states.get(org);
const began = ++s.began;
const read = { packs: null, applied: [], writable: false, error: null, projects: null };
try {
const value = await call(`${base(org)}/packs`);
s.packs = Array.isArray(value?.packs) ? value.packs.filter(p => p && typeof p === 'object' && p.pack && typeof p.pack === 'object') : [];
s.applied = Array.isArray(value?.applied) ? value.applied.filter(a => plainObj(a) && typeof a.id === 'string' && Array.isArray(a.hired) && Array.isArray(a.open)) : [];
s.writable = value?.writable === true;
} catch (error) { s.error = error.message; }
read.packs = Array.isArray(value?.packs) ? value.packs.filter(p => p && typeof p === 'object' && p.pack && typeof p.pack === 'object') : [];
read.applied = Array.isArray(value?.applied) ? value.applied.filter(a => plainObj(a) && typeof a.id === 'string' && Array.isArray(a.hired) && Array.isArray(a.open)) : [];
read.writable = value?.writable === true;
} catch (error) { read.error = error.message; }
// A project pack needs a code project. The workflow read lists them; when it fails, a project pack
// says so instead of guessing.
if (s.packs?.some(p => p.pack.scope === 'project')) {
try { const w = await call(`${base(org)}/workflows`); s.projects = w && typeof w.projects === 'object' ? Object.keys(w.projects).sort() : null; } catch { s.projects = null; }
if (read.packs?.some(p => p.pack.scope === 'project')) {
try { const w = await call(`${base(org)}/workflows`); read.projects = w && typeof w.projects === 'object' ? Object.keys(w.projects).sort() : null; } catch { read.projects = null; }
}
states.set(org, s);
if (began < s.shown) return;
s.shown = began;
Object.assign(s, read);
}
const markText = m => MARKS[m] ?? m;
function itemRow(item) {
@@ -51,3 +51,145 @@ for(const [width,height]of [[1440,900],[390,844]])for(const theme of ['light','d
await waitFor(b,`/Reversal recorded/.test(document.querySelector('[data-autonomy-status]').textContent)`);assert.equal(reverses,1);
await b.screenshot(join(shots,`reverse-${width}-${theme}.png`));
});
// The organization page reads autonomy again on a poll and after any write that changes the organization
// (mosaic-org-changed). A save or review receipt must survive a reload that overlaps it, in either order,
// and an older read that answers last must not put its older values back.
// hold(verb) makes the next call of that verb wait: its answer is computed when the call arrives, then held
// until release(). arrived resolves when the call has arrived.
function holds(){
const pending=new Map();
return {
hold(verb){const h={};h.arrived=new Promise(r=>{h.reached=r;});h.wait=new Promise(r=>{h.release=r;});pending.set(verb,[...(pending.get(verb)??[]),h]);return h;},
take:verb=>pending.get(verb)?.shift(),
};
}
async function raceFixture(t,gates){
const state={writes:0,reviews:0,setting:{merge:'out of the loop'},revision:'a'.repeat(64)};
const answer=(verb,args)=>{
if(verb==='autonomy.get.console')return {revision:state.revision,autonomy:state.setting,levels:{'cross-role':'out of the loop',merge:state.setting.merge,policy:'out of the loop',authority:'in the loop'}};
if(verb==='autonomy.set.console'){assert.equal(args.revision,state.revision);state.writes++;state.setting=args.autonomy;state.revision=String(state.writes+1).repeat(64);return {revision:state.revision,transaction:`10000000-0000-4000-8000-00000000000${state.writes}`};}
if(verb==='autonomy.review.console'){state.reviews++;return {recorded:true};}
throw Object.assign(new Error('not-configured'),{code:'not-configured'});
};
const call=async(verb,args)=>{const value=answer(verb,args),held=gates.take(verb);if(held){held.reached();await held.wait;}return value;};
const server=await startServer({port:0,sso:createDevOwner(),send:async()=>({}),organizations:{list:async()=>[{id:'acme',label:'Acme',busHealthy:true}],resolve:async()=>({busHealthy:true,decisionWrite:async()=>({}),requestRead:call,requestWrite:call,send:async()=>({}),reads:{business:async()=>({business:{id:'acme',projects:[],instances:[]}}),settings:async()=>({}),queue:async()=>({rows:[]})},bus:{instances:async()=>({instances:{}}),agents:async()=>[],'thread.claims':async()=>[],tasks:async()=>[],inbox:async()=>[],messages:async()=>({messages:[]})},chat:{projects:async()=>[],threads:async()=>[]}})},log:()=>{}});
t.after(()=>close(server));const b=await browser({machine:false});t.after(()=>b.close());
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/acme/organization`);
await waitFor(b,`document.querySelector('[data-autonomy-form] button[type=submit]')`);
return {b,state};
}
const reload=b=>b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-org-changed',{detail:{org:'acme'}}));true`);
const markDrawn=b=>b.evaluate(`document.querySelector('[data-autonomy]').dataset.drawn='before';true`);
const redrawn=b=>waitFor(b,`document.querySelector('[data-autonomy-form]') && !document.querySelector('[data-autonomy]').dataset.drawn`);
const statusText=b=>b.evaluate(`document.querySelector('[data-autonomy-form] [data-autonomy-status]').textContent`);
const submit=(b,level)=>b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value=${JSON.stringify(level)};document.querySelector('[data-autonomy-form]').requestSubmit();true`);
// Count each autonomy read by the revision it carries, once the reading load has used it: a task queued
// after the answer runs after the load's last step. A poll that reads meanwhile counts under its own revision.
const countReads=b=>b.evaluate(`{const f=window.fetch;window.__autonomyRead={};window.fetch=async(...a)=>{const r=await f(...a);if(String(a[0]).endsWith('/api/orgs/acme/autonomy')&&!a[1]?.method){const j=r.json.bind(r);r.json=()=>j().then(v=>{setTimeout(()=>{window.__autonomyRead[v.revision]=(window.__autonomyRead[v.revision]??0)+1});return v})}return r}}true`);
const readUsed=(b,revision)=>waitFor(b,`window.__autonomyRead[${JSON.stringify(revision)}]>=1`);
test('AU owner settings: a save that lands while a reload of autonomy is held keeps its receipt and revision',{timeout:60000},async t=>{
const gates=holds();const {b,state}=await raceFixture(t,gates);
// The reload's read arrives first and answers after the save has been drawn.
const list=gates.hold('autonomy.get.console');
await reload(b);await list.arrived;
await submit(b,'in the loop');
await waitFor(b,`/^Saved\\. Receipt /.test(document.querySelector('[data-autonomy-status]').textContent)`);
assert.equal(state.writes,1);
await markDrawn(b);list.release();await redrawn(b);
assert.match(await statusText(b),/^Saved\. Receipt 10000000-0000-4000-8000-000000000001\.$/,'the reload kept the receipt');
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form]').dataset.revision`),JSON.stringify(state.revision),'the form saves against the revision the save answered');
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value`),'in the loop','the form shows what was saved');
// The next save is not a revision conflict.
await submit(b,'near the loop');
await waitFor(b,`/^Saved\\. Receipt 10000000-0000-4000-8000-000000000002\\.$/.test(document.querySelector('[data-autonomy-status]').textContent)`);
assert.equal(state.writes,2);
});
test('AU owner settings: a save that answers after a reload has drawn the page keeps its receipt',{timeout:60000},async t=>{
const gates=holds();const {b,state}=await raceFixture(t,gates);
// The save arrives first and answers after a reload has drawn the page again.
const save=gates.hold('autonomy.set.console');
await submit(b,'in the loop');await save.arrived;
await markDrawn(b);await reload(b);await redrawn(b);
save.release();
await waitFor(b,`/^Saved\\. Receipt /.test(document.querySelector('[data-autonomy-form] [data-autonomy-status]').textContent)`);
await markDrawn(b);await reload(b);await redrawn(b);
assert.match(await statusText(b),/^Saved\. Receipt 10000000-0000-4000-8000-000000000001\.$/,'a later reload keeps the receipt');
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form]').dataset.revision`),JSON.stringify(state.revision));
});
test('AU owner settings: a trail review that answers after a reload has drawn the page is said',{timeout:60000},async t=>{
const gates=holds();const {b,state}=await raceFixture(t,gates);
await b.evaluate(`document.querySelector('[data-autonomy-review-list]').open=true;true`);
const review=gates.hold('autonomy.review.console');
await b.evaluate(`document.querySelector('[data-autonomy-review=merge]').click();true`);await review.arrived;
await markDrawn(b);await reload(b);await redrawn(b);
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-review-list]').open`),true,'the review list stays open');
review.release();
await waitFor(b,`document.querySelector('[data-autonomy-form] [data-autonomy-status]').textContent==='Trail review recorded.'`);
assert.equal(state.reviews,1);
await markDrawn(b);await reload(b);await redrawn(b);
assert.equal(await statusText(b),'Trail review recorded.','a later reload keeps the review receipt');
});
test('AU owner settings: an older read of autonomy that answers last does not replace a newer one',{timeout:60000},async t=>{
const gates=holds();const {b,state}=await raceFixture(t,gates);
await countReads(b);
const older=gates.hold('autonomy.get.console');
await reload(b);await older.arrived;
// Another writer changes the organization; a newer read answers first.
state.setting={merge:'near the loop'};state.revision='c'.repeat(64);
await reload(b);
// The page draws after all of the dashboard's reads, so wait for the draw as well as the read.
await waitFor(b,`document.querySelector('[data-autonomy-form] select[name=merge]')?.value==='near the loop' && window.__autonomyRead[${JSON.stringify('c'.repeat(64))}]>=1`);
older.release();
await readUsed(b,'a'.repeat(64));
const drawn=await b.evaluate(`window.MosaicAutonomy.section('acme')`);
assert.match(drawn,/<option selected>near the loop<\/option>/,'the older values were not put back');
assert.match(drawn,new RegExp(`data-revision="&quot;${'c'.repeat(64)}&quot;"`),'the newer revision stays');
});
test('AU owner settings: a save that answers after a redraw from an older read draws what was saved',{timeout:60000},async t=>{
const gates=holds();const {b,state}=await raceFixture(t,gates);
// The reload's read is served before the save commits. It draws a clean new form while the save is held.
const read=gates.hold('autonomy.get.console');
await reload(b);await read.arrived;
const save=gates.hold('autonomy.set.console');
await submit(b,'in the loop');await save.arrived;
assert.equal(state.writes,1);
await markDrawn(b);read.release();await redrawn(b);
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value`),'out of the loop','the older read was drawn');
save.release();
await waitFor(b,`/^Saved\\. Receipt /.test(document.querySelector('[data-autonomy-form] [data-autonomy-status]').textContent)`);
// Before any further reload, the drawn form shows the save and carries its revision.
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form]').dataset.revision`),JSON.stringify(state.revision),'the drawn form saves against the revision the save answered');
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value`),'in the loop','the drawn form shows what was saved');
assert.match(await statusText(b),/^Saved\. Receipt 10000000-0000-4000-8000-000000000001\.$/);
await submit(b,'near the loop');
await waitFor(b,`/^Saved\\. Receipt 10000000-0000-4000-8000-000000000002\\.$/.test(document.querySelector('[data-autonomy-status]').textContent)`);
assert.equal(state.writes,2,'the next save is not a revision conflict');
});
test('AU owner settings: a save that answers after a newer read by another writer leaves the newer read',{timeout:60000},async t=>{
const gates=holds();const {b,state}=await raceFixture(t,gates);
// The save commits, then another writer commits, and a reload draws that newer read before the save answers.
const save=gates.hold('autonomy.set.console');
await submit(b,'in the loop');await save.arrived;
assert.equal(state.writes,1);
state.setting={merge:'near the loop'};state.revision='c'.repeat(64);
await markDrawn(b);await reload(b);await redrawn(b);
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value`),'near the loop','the newer read was drawn');
save.release();
await waitFor(b,`/^Saved\\. Receipt 10000000-0000-4000-8000-000000000001\\.$/.test(document.querySelector('[data-autonomy-form] [data-autonomy-status]').textContent)`);
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form] select[name=merge]').value`),'near the loop','the drawn form keeps the newer read');
assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form]').dataset.revision`),JSON.stringify('c'.repeat(64)));
const drawn=await b.evaluate(`window.MosaicAutonomy.section('acme')`);
assert.match(drawn,/<option selected>near the loop<\/option>/,'the state keeps the newer read');
assert.match(drawn,/data-autonomy-status role="status">Saved\. Receipt 10000000-0000-4000-8000-000000000001\./,'the state keeps the receipt');
// The next save goes against the newer revision and is not a conflict.
await submit(b,'in the loop');
await waitFor(b,`/^Saved\\. Receipt 10000000-0000-4000-8000-000000000002\\.$/.test(document.querySelector('[data-autonomy-status]').textContent)`);
assert.equal(state.writes,2);
});
+3 -3
View File
@@ -69,12 +69,12 @@ export async function browser({ machine = true, args = [] } = {}) {
}
const { targetId } = await send('Target.createTarget', { url: 'about:blank' });
const { sessionId } = await send('Target.attachToTarget', { targetId, flatten: true });
const call = (method, params) => send(method, params, sessionId);
const call = (method, params, ms) => send(method, params, sessionId, ms);
await call('Page.enable');
await call('Runtime.enable');
if (machine) await call('Page.addScriptToEvaluateOnNewDocument', { source: `try { localStorage.setItem('mosaic-console-board', '{"machine":true}'); } catch {}` });
const evaluate = async expression => {
const r = await call('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
const evaluate = async (expression, ms) => {
const r = await call('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, ms);
if (r.exceptionDetails) throw new Error(r.exceptionDetails.text + ': ' + r.result.description);
return r.result.value;
};
@@ -31,7 +31,7 @@ const PREVIEW = {
// busy: the bus's apply committed but its hire loop did not run (hireError), and the packs read lists one line a
// member's pack hire left in the owner's inbox (fromPack), one raised some other way and one refused.
async function fixture(t, { busy = false } = {}) {
async function fixture(t, { busy = false, gates = null } = {}) {
const verbs = [], decisions = [];
const hired = new Map(); // name -> its pack provenance, as the bus's instances read reports it
let applied = null, route = false, instanceReads = 0;
@@ -46,19 +46,22 @@ async function fixture(t, { busy = false } = {}) {
const listed = () => applied ? [{ id: 'software-team', origin: 'shipped', project: null, hired: [...hired.keys()],
open: PREVIEW.hires.filter(h => !hired.has(h.name)).map(h => ({ name: h.name, reason: `Proposed by starter pack software-team for ${h.definition} work.`,
...(!busy || h.name === 'scout-1' ? { state: 'refused', code: 'pack-hire-route-missing' } : { state: 'awaiting-owner', decision: `inbox-${h.name}`, ...(h.name === 'coder-1' ? { fromPack: true } : {}) }) })) }] : [];
const read = async (verb, args) => {
const readAnswer = async (verb, args) => {
verbs.push([verb, args]);
if (verb === 'packs.console') return { packs: PACKS, applied: listed() };
if (verb === 'pack.preview.console') return PREVIEW;
if (verb === 'autonomy.get.console') return { revision: REV('e'), autonomy: {}, levels: {} };
throw Object.assign(new Error('not-configured'), { code: 'not-configured' });
};
const write = async (verb, args) => {
const writeAnswer = async (verb, args) => {
verbs.push([verb, args]);
if (verb === 'pack.apply.console') { applied = true; return { revision: REV('f'), added: ['board'], pack: { id: args.pack, version: '1.0.0' }, ...(busy ? { hires: [], hireError: 'organization-busy' } : { hires: hireLoop() }) }; }
if (verb === 'pack.hire.console') return { pack: args.pack, hires: hireLoop() };
throw Object.assign(new Error('not-configured'), { code: 'not-configured' });
};
// A held call is answered when it arrives, then waits for release() (holds() below).
const gated = answer => async (verb, args) => { const value = await answer(verb, args), held = gates?.take(verb); if (held) { held.reached(); await held.wait; } return value; };
const read = gated(readAnswer), write = gated(writeAnswer);
const decisionWrite = async (verb, args) => {
verbs.push([verb, args]);
if (verb === 'hire.start.console' && args.op === 'fire' && hired.has(args.name)) { hired.delete(args.name); return { id: 'fire-1', op: 'resolved', choice: 'yes' }; }
@@ -184,3 +187,80 @@ test('PD an apply whose hire loop did not run says so; the owner card counts a p
// coder-1 was left in the inbox by a pack hire, so the owner's pack hire approves it; reviewer-1 is the inbox's.
assert.equal(await b.evaluate(`document.querySelector('[data-pack-hire-button]').textContent`), 'Hire the 2 proposed agents');
});
// hold(verb) makes the next call of that verb wait: its answer is computed when the call arrives, then held
// until release(). arrived resolves when the call has arrived.
function holds() {
const pending = new Map();
return {
hold(verb) {
const h = {};
h.arrived = new Promise(r => { h.reached = r; });
h.wait = new Promise(r => { h.release = r; });
pending.set(verb, [...(pending.get(verb) ?? []), h]);
return h;
},
take: verb => pending.get(verb)?.shift(),
};
}
const reload = b => b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-org-changed',{detail:{org:'acme'}}));true`);
const markDrawn = b => b.evaluate(`document.querySelector('[data-packs]').dataset.drawn='before';true`);
const redrawn = (b, what) => waitFor(b, `document.querySelector('[data-packs]') && !document.querySelector('[data-packs]').dataset.drawn`, what);
// Count each packs answer once the reading load has used it. With no project pack listed the load has no
// further read, so a task queued after the answer runs after the load's last step.
const countPacksAnswers = b => b.evaluate(`{const f=window.fetch;window.__packsDone=0;window.fetch=async(...a)=>{const r=await f(...a);if(String(a[0]).endsWith('/api/orgs/acme/packs')){const j=r.json.bind(r);r.json=()=>j().finally(()=>setTimeout(()=>{window.__packsDone++}))}return r}}true`);
const HIRED = 'Hired scout-1. Already hired: coder-1, reviewer-1.';
// Apply the pack with no route, so scout-1 is left to hire, then set the route.
async function applied(t, gates) {
const f = await fixture(t, { gates });
await f.b.navigate(`http://127.0.0.1:${f.port}/#/orgs/acme/organization`);
await waitFor(f.b, `document.querySelector('[data-pack="software-team"] [data-pack-preview-button]')`, 'pack list');
await f.b.evaluate(`document.querySelector('[data-pack="software-team"] [data-pack-preview-button]').click();true`);
await waitFor(f.b, `document.querySelector('[data-pack-apply]')`, 'preview');
await f.b.evaluate(`document.querySelector('[data-pack-apply]').click();true`);
await waitFor(f.b, `/^Applied\\./.test(document.querySelector('[data-packs-status]')?.textContent??'') && document.querySelector('[data-pack-hire-button]')`, 'apply status and hire button');
f.setRoute(true);
return f;
}
// The page reads the packs again on a poll and after any write that changes the organization
// (mosaic-org-changed). A hire receipt must survive a reload that overlaps the hire, in either order.
test('PD a hire receipt that lands while an earlier read of the packs is held is kept', { timeout: 90000 }, async t => {
const gates = holds();
const { b, verbs } = await applied(t, gates);
await countPacksAnswers(b);
// A reload's packs read is held. The hire answers, reads the packs itself and asks the page to read
// everything again; both of those reads answer first. Then the held read answers last.
const earlier = gates.hold('packs.console');
await reload(b);
await earlier.arrived;
await b.evaluate(`document.querySelector('[data-pack-hire-button]').click();true`);
await waitFor(b, `document.querySelector('[data-packs-status]')?.textContent==='${HIRED}' && window.__packsDone>=2`, 'hire status');
earlier.release();
await waitFor(b, `window.__packsDone>=3`, 'held read answered');
await markDrawn(b);
await reload(b);
await redrawn(b, 'page drawn again after the held read');
assert.equal(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), HIRED, 'the hire receipt is kept');
assert.equal(await b.evaluate(`document.querySelector('[data-pack-hire-button]')`), null, 'nothing left to hire');
assert.deepEqual(verbs.filter(([v]) => v === 'pack.hire.console').map(([, a]) => a), [{ pack: 'software-team' }]);
});
test('PD a hire that answers after a reload has drawn the page keeps its receipt', { timeout: 90000 }, async t => {
const gates = holds();
const { b, verbs } = await applied(t, gates);
// The hire arrives first and answers after a reload has drawn the page again.
const hire = gates.hold('pack.hire.console');
await b.evaluate(`document.querySelector('[data-pack-hire-button]').click();true`);
await hire.arrived;
await markDrawn(b);
await reload(b);
await redrawn(b, 'page drawn again during the hire');
hire.release();
await waitFor(b, `document.querySelector('[data-packs-status]')?.textContent==='${HIRED}'`, 'hire status');
await markDrawn(b);
await reload(b);
await redrawn(b, 'page drawn again after the hire');
assert.equal(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), HIRED, 'a later reload keeps the hire receipt');
assert.deepEqual(verbs.filter(([v]) => v === 'pack.hire.console').map(([, a]) => a), [{ pack: 'software-team' }]);
});
@@ -35,7 +35,23 @@ const PREVIEW = {
skills: { notEnabled: ['lint-fix'] }, chief: true, plan: {}, digest: REV('d'),
};
async function fixture(t, { send = true } = {}) {
// hold(verb) makes the next read of that verb wait: its answer is computed when the read arrives, then
// held until release(). arrived resolves when the read has arrived.
function holds() {
const pending = new Map();
return {
hold(verb) {
const h = {};
h.arrived = new Promise(r => { h.reached = r; });
h.wait = new Promise(r => { h.release = r; });
pending.set(verb, [...(pending.get(verb) ?? []), h]);
return h;
},
take: verb => pending.get(verb)?.shift(),
};
}
async function fixture(t, { send = true, gates = null, packs = () => PACKS } = {}) {
const verbs = [];
let flows = {
revision: REV('a'),
@@ -48,13 +64,18 @@ async function fixture(t, { send = true } = {}) {
},
templates: ['coder', 'reviewer'],
};
const read = async (verb, args) => {
verbs.push([verb, args]);
if (verb === 'packs.console') return { packs: PACKS };
const answer = (verb, args) => {
if (verb === 'packs.console') return { packs: packs() };
if (verb === 'pack.preview.console') return { ...PREVIEW, project: args.project ?? null };
if (verb === 'autonomy.get.console') return { revision: REV('e'), autonomy: {}, levels: {} };
throw Object.assign(new Error('not-configured'), { code: 'not-configured' });
};
const read = async (verb, args) => {
verbs.push([verb, args]);
const value = answer(verb, args), held = gates?.take(verb);
if (held) { held.reached(); await held.wait; }
return value;
};
const write = async (verb, args) => {
verbs.push([verb, args]);
if (verb === 'pack.apply.console') return { revision: REV('f'), added: ['board', 'definitions.reviewer'], pack: { id: args.pack, version: '1.0.0' }, hires: [{ name: 'lead-reviewer', state: 'refused', code: 'definition-not-hireable' }] };
@@ -128,6 +149,85 @@ test('SP6 pack picker: list, preview with marks, flagged, credential and noHire
assert.deepEqual(verbs.filter(([v]) => v === 'pack.preview.console').at(-1)[1], { pack: 'web-project', project: 'site' });
});
// The page reads the packs again on a poll and after any write that changes the organization
// (mosaic-org-changed). A preview the owner asked for must survive a reload that overlaps it, in either
// order, and an older reload that answers last must not put its older list back.
const reload = b => b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-org-changed',{detail:{org:'acme'}}));true`);
const markDrawn = b => b.evaluate(`document.querySelector('[data-packs]').dataset.drawn='before';true`);
const redrawn = (b, what) => waitFor(b, `document.querySelector('[data-packs]') && !document.querySelector('[data-packs]').dataset.drawn`, what);
test('SP6 pack picker: a preview that overlaps a reload of the packs is kept, in either order', { timeout: 60000 }, async t => {
const gates = holds();
const { b, verbs } = await fixture(t, { gates });
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-preview-button]')`, 'pack list');
// The reload's packs read starts first and answers after the preview has been drawn.
const list = gates.hold('packs.console');
await reload(b);
await list.arrived;
await b.evaluate(`document.querySelector('[data-pack="software-team"] [data-pack-preview-button]').click();true`);
await waitFor(b, `document.querySelector('[data-pack-preview="software-team"]')`, 'preview');
await markDrawn(b);
list.release();
await redrawn(b, 'page drawn again after the reload');
assert.ok(await b.evaluate(`!!document.querySelector('[data-pack-preview="software-team"]')`), 'the reload kept the preview');
// The preview's read starts first and answers after the reload has drawn the page.
const preview = gates.hold('pack.preview.console');
await b.evaluate(`document.querySelector('[data-pack="web-project"] [data-pack-preview-button]').click();true`);
await preview.arrived;
await markDrawn(b);
await reload(b);
await redrawn(b, 'page drawn again during the preview');
preview.release();
await waitFor(b, `/for project site/.test(document.querySelector('[data-pack-preview] h4')?.textContent??'')`, 'project preview after the reload');
assert.deepEqual(verbs.filter(([v]) => v === 'pack.preview.console').map(([, a]) => a), [{ pack: 'software-team' }, { pack: 'web-project', project: 'site' }]);
});
// Count each packs answer once the reading load has used it. With no project pack listed the load has
// no further read, so a task queued after the answer runs after the load's last step.
const countPacksAnswers = b => b.evaluate(`{const f=window.fetch;window.__packsDone=0;window.fetch=async(...a)=>{const r=await f(...a);if(String(a[0]).endsWith('/api/orgs/acme/packs')){const j=r.json.bind(r);r.json=()=>j().finally(()=>setTimeout(()=>{window.__packsDone++}))}return r}}true`);
test('SP6 pack picker: an older read of the packs that answers last does not replace a newer one', { timeout: 60000 }, async t => {
const gates = holds();
let packs = [PACKS[0]];
const { b } = await fixture(t, { gates, packs: () => packs });
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-preview-button]')`, 'pack list');
await countPacksAnswers(b);
const older = gates.hold('packs.console');
await reload(b);
await older.arrived;
packs = [PACKS[0], { id: 'later', origin: 'installed', pack: { label: 'Later pack', description: 'Installed after the first read.', version: '0.1.0', scope: 'organization' } }];
await reload(b);
await waitFor(b, `document.querySelector('[data-pack="later"]') && window.__packsDone===1`, 'newer list drawn');
older.release();
await waitFor(b, `window.__packsDone===2`, 'older read answered');
assert.match(await b.evaluate(`window.MosaicPacks.section('acme')`), /data-pack="later"/, 'the older list was not put back');
await b.evaluate(`document.querySelector('[data-pack="software-team"] [data-pack-preview-button]').click();true`);
await waitFor(b, `document.querySelector('[data-pack-preview="software-team"]')`, 'preview');
assert.ok(await b.evaluate(`!!document.querySelector('[data-pack="later"]')`), 'the drawn list is the newer one');
});
test('SP6 pack picker: an apply receipt that lands while an earlier read of the packs is held is kept', { timeout: 60000 }, async t => {
const gates = holds();
const { b, verbs } = await fixture(t, { gates, packs: () => [PACKS[0]] });
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-preview-button]')`, 'pack list');
await b.evaluate(`document.querySelector('[data-pack="software-team"] [data-pack-preview-button]').click();true`);
await waitFor(b, `document.querySelector('[data-pack-apply]')`, 'preview');
await countPacksAnswers(b);
// A reload's packs read is held. The apply answers, reads the packs itself and asks the page to read
// everything again; both of those reads answer first. Then the held read answers last.
const earlier = gates.hold('packs.console');
await reload(b);
await earlier.arrived;
await b.evaluate(`document.querySelector('[data-pack-apply]').click();true`);
await waitFor(b, `/^Applied\./.test(document.querySelector('[data-packs-status]')?.textContent??'') && window.__packsDone===2`, 'apply status');
assert.equal(verbs.filter(([v]) => v === 'pack.apply.console').length, 1);
earlier.release();
await waitFor(b, `window.__packsDone===3`, 'held read answered');
const drawn = await b.evaluate(`window.MosaicPacks.section('acme')`);
assert.match(drawn, /data-packs-status>Applied\. Added board, definitions\.reviewer\./, 'the receipt is kept');
assert.doesNotMatch(drawn, /data-pack-preview=/, 'the applied preview does not come back');
});
test('SP6 pack picker without send previews but offers no apply', { timeout: 60000 }, async t => {
const { b } = await fixture(t, { send: false });
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-preview-button]')`, 'pack list');
@@ -35,4 +35,7 @@ test('signed-in Console buttons deliver the approved original request and downlo
assert.equal(await page.clock(), '25:00');
await page.advance(10000); assert.equal(await page.clock(), '25:00');
assert.deepEqual(await page.externalRequests(), []);
// A remote resource in the downloaded file must still be observed while the browser is offline.
await page.offline('<!doctype html><img src="https://external.invalid/tracker">');
assert.deepEqual(await page.externalRequests(), ['https://external.invalid/tracker']);
});
@@ -89,12 +89,53 @@ test('account-remove: Remove posts exactly { accountId }, reads the list again a
assert.deepEqual(await b.evaluate('window.__unexpected'), []);
});
test('account-remove: a failed refresh after a successful remove keeps the success and the refresh error', { timeout: 90000 }, async t => {
const { b, wait } = await open(t, { extra: { [impactKey(A)]: { body: IMPACT_ALL },
'POST /api/proxy/admin/accounts/remove': { body: { accountId: A, provider: 'claude', removed: true } } } });
await b.evaluate(`document.querySelector('[data-remove="${A}"]').click(); true`);
await wait('!!document.querySelector("#proxy-remove-yes")');
await b.evaluate(`window.__scenario['GET /api/proxy/accounts'] = { status: 503, body: { error: 'proxy-down' } }; document.querySelector('#proxy-remove-yes').click(); true`);
await wait('document.querySelector("#proxy-message").textContent.includes("not answering")');
assert.equal(await b.evaluate('document.querySelector("#proxy-message").textContent'), 'Claude account removed. The account list could not be refreshed: The model service is not answering.');
assert.equal((await writes(b)).length, 1);
});
test('account-remove: a failed setup status refresh remains visible beside successful removal', { timeout: 90000 }, async t => {
const { b, wait } = await open(t, { extra: { [impactKey(A)]: { body: IMPACT_ALL },
'POST /api/proxy/admin/accounts/remove': { body: { accountId: A, provider: 'claude', removed: true } } } });
await b.evaluate(`document.querySelector('[data-remove="${A}"]').click(); true`);
await wait('!!document.querySelector("#proxy-remove-yes")');
await b.evaluate(`window.__scenario['GET /api/proxy/admin/status'] = { status: 503, body: { error: 'outcome-unknown' } }; document.querySelector('#proxy-remove-yes').click(); true`);
await wait('document.querySelector("#proxy-setup-message").textContent.length > 0');
assert.match(await b.evaluate('document.querySelector("#proxy-message").textContent'), /^Claude account removed\..*setup status could not be refreshed/i);
assert.equal((await writes(b)).length, 1);
});
test('account-remove: a late setup warning keeps the removal receipt when priority is saved meanwhile', { timeout: 90000 }, async t => {
const { b, wait } = await open(t, { extra: { [impactKey(A)]: { body: IMPACT_ALL },
'POST /api/proxy/admin/accounts/remove': { body: { accountId: A, provider: 'claude', removed: true } },
'POST /api/proxy/priority/set': { body: { accountId: B, priority: 0 } } } });
await b.evaluate(`document.querySelector('[data-remove="${A}"]').click(); true`);
await wait('!!document.querySelector("#proxy-remove-yes")');
await b.evaluate(`(() => { const real = window.fetch; window.__held = false; window.fetch = (input, init) => {
if (String(input) === '/api/proxy/admin/status') { window.__held = true; return new Promise(resolve => { window.__releaseStatus = () => resolve(new Response(JSON.stringify({ error: 'outcome-unknown' }), { status: 503, headers: { 'Content-Type': 'application/json' } })); }); }
return real(input, init); }; window.__scenario['GET /api/proxy/accounts'] = { body: { accounts: ${JSON.stringify(LIST.slice(1))} } }; document.querySelector('#proxy-remove-yes').click(); return true; })()`);
await wait('window.__held');
await b.evaluate('document.querySelector("#proxy-order form").requestSubmit(); true');
await wait('document.querySelector("#proxy-message").textContent === "Priority saved."');
await b.evaluate('window.__releaseStatus(); true');
await wait('document.querySelector("#proxy-message").textContent.includes("setup status could not be refreshed")');
assert.match(await b.evaluate('document.querySelector("#proxy-message").textContent'), /^Claude account removed\./);
assert.equal(await b.evaluate('document.querySelector("#proxy-order [role=status]").textContent'), 'Priority saved.');
});
test('account-remove: remove-write-refused and remove-unconfirmed are named in the ask and the account stays', { timeout: 90000 }, async t => {
// No refusal says nothing was removed: a refused or unanswered write may still have taken effect.
for (const [code, words] of [['remove-write-refused', 'The model service refused to remove the account. Check the list before trying again.'],
['remove-unconfirmed', 'Mosaic asked the model service to remove the account, but it is still listed. Read the accounts again before trying again.'],
['proxy-uncertain', 'Mosaic could not confirm the remove: the model service is between writes. Check the service and the list before trying again.'],
['proxy-down', 'The model service stopped answering, so Mosaic could not confirm the remove. Check the service and the list before trying again.'],
['invalid-request', 'Mosaic could not identify one account to remove. It may no longer be listed, have a duplicate ID, or share a credential with another account. Read the accounts again.'],
['some-new-code', 'The remove could not be confirmed. Nothing was retried. Read the accounts again before trying again.']]) {
const { b, wait } = await open(t, { extra: { [impactKey(A)]: { body: IMPACT_ALL }, 'POST /api/proxy/admin/accounts/remove': { status: 400, body: { error: code } } } });
await b.evaluate(`document.querySelector('[data-remove="${A}"]').click(); true`);
@@ -202,6 +202,14 @@ test('models-offered page: an organization that is not answering is named in the
assert.equal((await writes())[1].body.confirmInUse, true);
});
test('models-offered page: unanswered organizations are visible before saving', { timeout: 90000 }, async t => {
const { b, wait, writes } = await setup(t, { admin: { models: { ...VIEW, unanswered: ['lab', 'zeta'] } } });
await openOffered(b, wait);
assert.equal(await b.evaluate('document.querySelector("#proxy-offered-list .offered-unanswered")?.textContent'),
'Not answering now, so it is not known which models they use: Lab Bench, zeta. A model you switch off may stop working for them.');
assert.deepEqual(await writes(), []);
});
test('models-offered page: a save after another change is refused as a conflict, worded, with Read the list again; a busy or unknown answer is worded too', { timeout: 90000 }, async t => {
const conflict = { status: 409, body: { error: 'models-offered-conflict' } };
const busy = { status: 409, body: { error: 'proxy-admin-busy' } };
@@ -242,7 +250,7 @@ test('models-offered page: a page without proxyAdmin sends no /api/proxy/admin/
test('models-offered page: a read the model service cannot answer is worded, never an empty list', { timeout: 90000 }, async t => {
for (const [body, line] of [
[{ error: 'proxy-down' }, /No organization that uses your model service answered/],
[{ error: 'not-configured' }, /No organization uses your model service yet/],
[{ error: 'not-configured' }, /No organization with a configured model launch uses your model service yet/],
[{ error: 'outcome-unknown' }, /The outcome is unknown/],
]) {
const { b, wait } = await setup(t, { admin: { models: { status: 503, body } } });
@@ -10,7 +10,7 @@ import { createDevOwner } from '../src/dev-owner.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
const waitFor = b => (expression, ms = 6000) => b.evaluate(`(async()=>{for(let i=0;i<${Math.ceil(ms / 30)};i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`, ms + 10000);
const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString();
async function fixture({ empty = false, bootless = false } = {}) {
@@ -267,25 +267,28 @@ test('a restart started on one organization finishes on that organization after
// Every agent request read and write is recorded, whichever organization it names; the bus answers
// are stubs (terminate, closed requests, one launch). Only acme's instances read is stubbed and
// recorded (the session gone): beta's own page reads beta's instances, which is not the chain.
const init = `window.__chain = []; const original = window.fetch;
const init = `window.__chain = []; window.__requestIds = []; const original = window.fetch;
window.fetch = async (url, options = {}) => { const s = String(url); let x;
if (options.method === 'POST' && /\\/agent\\/terminate$/.test(s)) { __chain.push(s); x = { request: '${END}' }; return ${json}; }
if (options.method === 'POST' && /\\/agent\\/terminate$/.test(s)) { __chain.push(s); await new Promise(r => { window.__releaseTerminate = r; }); x = { request: '${END}' }; return ${json}; }
if (options.method === 'POST' && /\\/agent\\/launch$/.test(s)) { __chain.push(s); x = { request: '${LAUNCHED}' }; return ${json}; }
if (/\\/agent\\/request\\?/.test(s)) { __chain.push(s.split('?')[0]); const id = new URL(s, location.href).searchParams.get('id');
if (/\\/agent\\/request\\?/.test(s)) { __chain.push(s.split('?')[0]); const id = new URL(s, location.href).searchParams.get('id'); __requestIds.push(id);
x = { request: id, instance: 'coder', action: id === '${END}' ? 'end' : 'launch', state: 'closed', done: { run: id === '${END}' ? null : 'run-9' }, cancelled: null }; return ${json}; }
if (s === '/api/orgs/acme/bus/instances' && window.__restarting) { __chain.push(s); x = { rows: [{ instances: { coder: { running: [] } } }] }; return ${json}; }
return original(url, options); };`;
const { b, wait } = await setup(t, { path: '/#/orgs/acme/organization', init });
await wait('window.MosaicAgents && document.querySelector("[data-org-dashboard] h1")');
// The button the Routing receipt offers (agents.js restartMarkup), placed on acme's page.
await b.evaluate('window.__restarting = true; document.querySelector("[data-org-dashboard]").insertAdjacentHTML("beforeend", window.MosaicAgents.restartMarkup("coder")); document.querySelector("[data-agent-restart=coder]").click()');
await wait('window.__chain.length >= 1');
// Start the same chain as the Routing receipt button and observe its final status.
await b.evaluate('window.__restarting = true; document.querySelector("[data-org-dashboard]").insertAdjacentHTML("beforeend", window.MosaicAgents.restartMarkup("coder")); void window.MosaicAgents.restart("coder", false, { text(step) { window.__restartStep = step; } }); true');
await wait('typeof window.__releaseTerminate === "function"');
await b.evaluate('location.hash = "#/orgs/beta/organization"');
await wait('location.hash === "#/orgs/beta/organization"');
// Done when the chain has launched and read the launch request back, or as soon as any of it names beta.
await wait('window.__chain.some(u => u.includes("/orgs/beta/")) || (window.__chain.some(u => /\\/agent\\/launch$/.test(u)) && window.__chain.filter(u => /\\/agent\\/request$/.test(u)).length >= 2)', 30000);
await wait('window.MosaicOrg?.id === "beta" && document.querySelector("[data-org-dashboard] h1")?.textContent === "Beta Works"');
await b.evaluate('window.__releaseTerminate()');
// Stop on a cross-org request or after the launch response has been consumed successfully.
await wait('window.__chain.some(u => u.includes("/orgs/beta/")) || window.__restartStep === "restarted"', 30000);
assert.equal(await b.evaluate('window.__restartStep'), 'restarted');
const chain = await b.evaluate('window.__chain');
assert.deepEqual([...new Set(chain)], ['/api/orgs/acme/agent/terminate', '/api/orgs/acme/agent/request', '/api/orgs/acme/bus/instances', '/api/orgs/acme/agent/launch'], chain.join(' '));
assert.deepEqual(await b.evaluate('window.__requestIds'), [END, LAUNCHED]);
// beta's page draws nothing of acme's chain.
assert.equal(await b.evaluate('!!document.querySelector("[data-agent-restart-status=coder]")'), false);
});