Compare commits

...
2 changed files with 146 additions and 17 deletions

No files matched your search

+25 -17
View File
@@ -1117,16 +1117,21 @@
};
const DRAWER_LIMIT = 5, STOP_REASON = 'Stopped from the agent drawer.';
const STOP_UNKNOWN = 'Outcome unknown. Read the agents again before trying; nothing was retried.';
// The Stop state of the drawer's agent survives repaints: `confirm` while it asks, `busy` while the
// SP20: an organization that refuses a Stop or a Restart, in the same line for both.
const orgRefusal = (e, orgName) => e === 'org-archived' ? `${orgName} is archived, so its agents are not changed. Nothing changed.`
: e === 'org-unavailable' ? `${orgName} is not available to this Console. Nothing changed.` : '';
// Each drawer agent's question and Stop survive repaints: `confirm` while it asks, `busy` while the
// request is open, then the result in words beside the button. SP19: `kind` says whether Stop or
// Restart asks (no kind is Stop). While either asks or runs, both buttons wait.
let stopState = null; // { id, kind, confirm, busy, text }
// Restart asks (no kind is Stop). While either asks or runs, both buttons wait. SP20: kept per agent,
// as restarts are, so two Stops in two drawers each keep their line. An entry goes when the drawer
// closes after it finished, when its question is cancelled, or when its Restart starts.
const stops = new Map(); // id -> { kind, confirm, busy, text }
// SP19: each drawer agent's restart, kept per agent so several can run at once and none loses its
// line when another drawer asks or stops: `busy` while it runs, then its outcome in words. An entry
// goes when a new question starts on that agent, or when the drawer closes after it finished.
const restarts = new Map(); // id -> { busy, text }
// The state a drawer draws: its own question or Stop first, else its restart.
const actState = id => stopState?.id === id ? stopState : restarts.has(id) ? { id, kind: 'restart', ...restarts.get(id) } : null;
const actState = id => stops.has(id) ? { id, ...stops.get(id) } : restarts.has(id) ? { id, kind: 'restart', ...restarts.get(id) } : null;
const RESTART_REASON = 'restart from the agent drawer';
let drawerFocus = false, drawerShown = null;
// The drawer holds at most one history entry. A row opened from the page without a drawer pushes one
@@ -1396,7 +1401,7 @@
// Closing goes Back when a row link on this page pushed the current entry; otherwise it drops
// `agent` from the address in place. Either way the page repaints without it and focus returns to the row.
function closeDrawer() {
if (!stopState?.busy) stopState = null;
for (const [k, st] of stops) if (!st.busy) stops.delete(k);
for (const [k, r] of restarts) if (!r.busy) restarts.delete(k);
if (stateOf()?.[DRAWER_MARK] && queryOf().has('agent')) { history.back(); return; }
history.replaceState(unmarked(), '', sansAgent());
@@ -1433,10 +1438,11 @@
}
async function stopAgent(d) {
const id = d.dataset.wsDrawer, org = d.dataset.drawerOrgId, name = id.slice(org.length + 1), orgName = d.dataset.drawerOrgName;
stopState = { id, busy: true, text: `Stopping ${name}…` };
stops.set(id, { busy: true, text: `Stopping ${name}…` });
const repaint = () => document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
const paint = () => { const now = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`); if (!now) return; const s = now.querySelector('[data-drawer-status]'); if (s) s.textContent = stopState.text; const b = now.querySelector('[data-drawer-stop]'); if (b) { b.disabled = !!stopState.busy; b.firstChild.textContent = stopState.busy ? 'Stopping…' : 'Stop'; } const rb = now.querySelector('[data-drawer-restart]'); if (rb) rb.disabled = !!stopState.busy; now.querySelector('[data-drawer-stop-confirm]')?.remove(); };
const finish = text => { stopState = { id, text }; paint(); const b = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"] [data-drawer-stop]`); b?.focus({ preventScroll: true }); };
// Paint this agent's drawer in place, when it is on screen.
const paint = () => { const now = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`), st = stops.get(id); if (!now || !st) return; const s = now.querySelector('[data-drawer-status]'); if (s) s.textContent = st.text; const b = now.querySelector('[data-drawer-stop]'); if (b) { b.disabled = !!st.busy; b.firstChild.textContent = st.busy ? 'Stopping…' : 'Stop'; } const rb = now.querySelector('[data-drawer-restart]'); if (rb) rb.disabled = !!st.busy; now.querySelector('[data-drawer-stop-confirm]')?.remove(); };
const finish = text => { stops.set(id, { text }); paint(); const b = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"] [data-drawer-stop]`); b?.focus({ preventScroll: true }); };
paint();
let res, body = null;
try { res = await fetch(`/api/orgs/${enc(org)}/agent/terminate`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ instance: name, reason: STOP_REASON }), cache: 'no-store', redirect: 'manual' }); }
@@ -1444,6 +1450,8 @@
if (res.type === 'opaqueredirect' || res.status === 401) return finish('Not stopped: sign in again, then read the agents.');
try { body = await res.json(); } catch { body = null; }
if (!res.ok || body?.sent !== true && !body?.request) {
const orgWhy = orgRefusal(body?.error, orgName);
if (orgWhy) return finish(`Not stopped: ${orgWhy}`);
if (body?.sent === false && typeof body.message === 'string' && body.message) return finish(`Not stopped: ${body.message}`);
if (res.status === 403 && body?.error === 'read-only') return finish(`Not stopped: this Console only reads agents in ${orgName} (read-only).`);
if (body?.sent === false && typeof body.error === 'string') return finish(`Not stopped: the bus refused (${body.error}).`);
@@ -1451,14 +1459,14 @@
}
const request = typeof body?.request === 'string' ? body.request : '';
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(request)) return finish(STOP_UNKNOWN);
stopState = { id, busy: true, text: `Stop asked: request ${request} is open.` }; paint();
stops.set(id, { busy: true, text: `Stop asked: request ${request} is open.` }); paint();
for (let tries = 0; tries < 90; tries++) {
await new Promise(r => setTimeout(r, 2000));
let r = null;
try { const got = await fetch(`/api/orgs/${enc(org)}/agent/request?id=${enc(request)}`, { cache: 'no-store', redirect: 'manual' }); if (got.type === 'opaqueredirect') return finish('Sign in again, then read the agents.'); r = got.ok ? await got.json() : null; } catch { continue; }
if (r?.request === request && r.state === 'closed') {
if (r.reason) return finish(`Not stopped: ${r.reason}.`);
stopState = { id, text: `Stopped ${name}.` }; repaint(); return;
stops.set(id, { text: `Stopped ${name}.` }); repaint(); return;
}
}
finish(`Request ${request} is still open. Read the agents again later.`);
@@ -1472,8 +1480,8 @@
if (d?.status === 403 && e === 'read-only') return `this Console only reads agents in ${orgName} (read-only).`;
if (d?.status === 403 && (e === 'unavailable' || e === 'owner-only')) return `this Console is not the owner of ${orgName}, so it does not restart its agents.`;
if (e === 'no-bus-host') return `the bus of ${orgName} is not running. Nothing changed.`;
if (e === 'org-archived') return `${orgName} is archived, so its agents are not changed. Nothing changed.`;
if (e === 'org-unavailable') return `${orgName} is not available to this Console. Nothing changed.`;
const orgWhy = orgRefusal(e, orgName);
if (orgWhy) return orgWhy;
if (d?.result?.sent === false && typeof m === 'string' && m) return m;
if (d?.result?.sent === false && typeof e === 'string') return `the bus refused (${e}).`;
return STOP_UNKNOWN;
@@ -1501,11 +1509,11 @@
const thread = d.querySelector('[data-drawer-restart]')?.dataset.drawerThread === 'yes';
if (restarts.get(id)?.busy) return;
// The question is answered: from now on this agent's drawer draws its restart.
if (stopState?.id === id) stopState = null;
stops.delete(id);
restarts.set(id, { busy: true, text: '' });
// Paint this agent's drawer in place, when it is on screen and no question of its own holds it.
const paint = () => {
const now = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`), r = restarts.get(id); if (!now || !r || stopState?.id === id) return;
const now = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`), r = restarts.get(id); if (!now || !r || stops.has(id)) return;
const s = now.querySelector('[data-drawer-status]'); if (s) s.textContent = r.text;
const rb = now.querySelector('[data-drawer-restart]'), sb = now.querySelector('[data-drawer-stop]');
if (rb) { rb.disabled = r.busy; rb.firstChild.textContent = r.busy ? 'Restarting…' : 'Restart'; }
@@ -1548,11 +1556,11 @@
if (e.target.closest('[data-drawer-close]')) { closeDrawer(); return; }
const id = d.dataset.wsDrawer;
// SP19: nothing starts while this agent's Stop or Restart runs.
const held = (stopState?.id === id && stopState.busy) || !!restarts.get(id)?.busy;
const held = !!stops.get(id)?.busy || !!restarts.get(id)?.busy;
const ask = e.target.closest('[data-drawer-stop]') ? 'stop' : e.target.closest('[data-drawer-restart]') ? 'restart' : null;
if (ask && !held) {
const b = d.querySelector(`[data-drawer-${ask}]`), name = d.dataset.drawerName, who = `${name} in ${d.dataset.drawerOrgName}`;
stopState = { id, kind: ask, confirm: true, text: '' }; restarts.delete(id);
stops.set(id, { kind: ask, confirm: true, text: '' }); restarts.delete(id);
d.querySelector('.ws-drawer-confirm')?.remove();
b.insertAdjacentHTML('afterend', ask === 'stop' ? stopConfirm(name, who) : restartConfirm(name, who, b.dataset.drawerThread === 'yes'));
for (const x of d.querySelectorAll('[data-drawer-stop], [data-drawer-restart]')) x.disabled = true;
@@ -1569,7 +1577,7 @@
// Cancel the Stop or Restart question: nothing sent, both buttons enabled again, focus on the one that asked.
function cancelStop(d) {
const kind = d.querySelector('[data-drawer-restart-confirm]') ? 'restart' : 'stop';
stopState = null;
stops.delete(d.dataset.wsDrawer);
d.querySelector('.ws-drawer-confirm')?.remove();
for (const x of d.querySelectorAll('[data-drawer-stop], [data-drawer-restart]')) x.disabled = false;
d.querySelector(`[data-drawer-${kind}]`)?.focus({ preventScroll: true });
@@ -910,3 +910,124 @@ for (const [label, answers, line] of [
assert.equal(posts.filter(p => p.url.endsWith('/agent/launch')).length, launched ? 1 : 0);
assert.equal(await b.evaluate('window.__answers.length'), 0, 'every queued answer was asked for');
});
// SP20 (#1873): an organization refusal of Stop says so in one plain line, the line Restart gives.
for (const [label, answer, line] of [
['the organization is archived', { status: 409, body: { error: 'org-archived', message: 'organization is archived' } },
/^Not stopped: Acme Studio is archived, so its agents are not changed\. Nothing changed\.$/],
['the organization is not available', { status: 404, body: { error: 'org-unavailable' } },
/^Not stopped: Acme Studio is not available to this Console\. Nothing changed\.$/],
]) test(`SP20: a Stop refusal says so in the drawer: ${label}`, async t => {
const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Acoder' });
const d = '[data-ws-drawer="acme:coder"]';
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-stop]')`);
await b.evaluate(`window.__answers.push(${JSON.stringify(answer)})`);
await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').click()`);
await wait(`document.querySelector('${d} [data-drawer-stop-yes]')`);
await b.evaluate(`document.querySelector('${d} [data-drawer-stop-yes]').click()`);
await wait(`/^Not stopped: /.test(${status(d)}) && ${usable(d)}`);
assert.match(await b.evaluate(status(d)), line);
assert.equal(await b.evaluate(`document.activeElement === document.querySelector('${d} [data-drawer-stop]')`), true, 'focus is back on Stop');
assert.deepEqual((await b.evaluate('window.__posts')).map(p => [p.url, p.method]), [['/api/orgs/acme/agent/terminate', 'POST']]);
});
// SP20: each Stop keeps its own state, as each restart does. Another drawer's question or Stop does not
// lose a running Stop's line or its running state, and a Stop that ends does not drop another drawer's question.
test('SP20: two Stops in two drawers each keep their own line and running state', async t => {
const data = D => { D.acme.instances.ideas = { definition: 'ideas', running: ['run-4'] }; };
const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', data });
const d = '[data-ws-drawer="acme:coder"]', i = '[data-ws-drawer="acme:ideas"]';
const refused = who => ({ status: 409, body: { error: 'instance-protected', message: `instance-protected: ${who} is protected from ending. Nothing changed.`, sent: false } });
const state = x => `[${status(x)}, document.querySelector('${x} [data-drawer-stop]')?.firstChild.textContent, document.querySelector('${x} [data-drawer-stop]')?.disabled, document.querySelector('${x} [data-drawer-restart]')?.disabled]`;
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-stop]')`);
// Coder's Stop runs: its terminate is held.
await b.evaluate(`window.__answers.push({ hold: new Promise(r => { window.__release = r; }), ...${JSON.stringify(refused('coder'))} })`);
await b.evaluate(`document.querySelector('${d} [data-drawer-stop]').click()`);
await wait(`document.querySelector('${d} [data-drawer-stop-yes]')`);
await b.evaluate(`document.querySelector('${d} [data-drawer-stop-yes]').click()`);
await wait(`window.__posts.length === 1`);
// Ideas asks to stop and is cancelled; back on coder, its Stop still shows as running.
await b.evaluate('location.hash = "#/agents?agent=acme%3Aideas"');
await wait(`${open('acme:ideas')} && document.querySelector('${i} [data-drawer-stop]')`);
await b.evaluate(`document.querySelector('${i} [data-drawer-stop]').click()`);
await wait(`document.querySelector('${i} [data-drawer-stop-no]')`);
await b.evaluate(`document.querySelector('${i} [data-drawer-stop-no]').click()`);
await b.evaluate('location.hash = "#/agents?agent=acme%3Acoder"');
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-stop]')`);
assert.deepEqual(await b.evaluate(state(d)), ['Stopping coder…', 'Stopping…', true, true]);
// Ideas' Stop question is open when coder's Stop is refused; each drawer keeps its own.
await b.evaluate('location.hash = "#/agents?agent=acme%3Aideas"');
await wait(`${open('acme:ideas')} && document.querySelector('${i} [data-drawer-stop]')`);
await b.evaluate(`document.querySelector('${i} [data-drawer-stop]').click()`);
await wait(`document.querySelector('${i} [data-drawer-stop-no]')`);
await b.evaluate('window.__release()');
await b.evaluate('new Promise(r => setTimeout(r, 300))');
await b.evaluate('location.hash = "#/agents?agent=acme%3Acoder"');
await wait(`${open('acme:coder')} && /^Not stopped: /.test(${status(d)}) && ${usable(d)}`);
assert.equal(await b.evaluate(status(d)), 'Not stopped: instance-protected: coder is protected from ending. Nothing changed.');
await b.evaluate('location.hash = "#/agents?agent=acme%3Aideas"');
await wait(`${open('acme:ideas')} && document.querySelector('${i} [data-drawer-stop]')`);
assert.equal(await b.evaluate(`!!document.querySelector('${i} [data-drawer-stop-yes]')`), true, 'ideas keeps its question');
// Ideas' Stop runs and is refused; coder's line is still there after, and ideas' is too.
await b.evaluate(`window.__answers.push(${JSON.stringify(refused('ideas'))})`);
await b.evaluate(`document.querySelector('${i} [data-drawer-stop-yes]').click()`);
await wait(`/^Not stopped: /.test(${status(i)}) && ${usable(i)}`);
await b.evaluate('location.hash = "#/agents?agent=acme%3Acoder"');
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-stop]')`);
assert.deepEqual(await b.evaluate(state(d)), ['Not stopped: instance-protected: coder is protected from ending. Nothing changed.', 'Stop', false, false]);
await b.evaluate('location.hash = "#/agents?agent=acme%3Aideas"');
await wait(`${open('acme:ideas')} && document.querySelector('${i} [data-drawer-stop]')`);
assert.deepEqual(await b.evaluate(state(i)), ['Not stopped: instance-protected: ideas is protected from ending. Nothing changed.', 'Stop', false, false]);
assert.deepEqual((await b.evaluate('window.__posts')).map(p => JSON.parse(p.body).instance), ['coder', 'ideas']);
});
// SP20 review: two Stops run at once. One that ends, here the one the bus takes, which repaints the page,
// does not end the other's running state or line, and each drawer keeps its own line after.
test('SP20: two Stops running at once in two drawers each keep their own state', async t => {
const data = D => { D.acme.instances.ideas = { definition: 'ideas', running: ['run-4'] }; };
const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', scripts: [FAST], data });
const d = '[data-ws-drawer="acme:coder"]', i = '[data-ws-drawer="acme:ideas"]';
const REQ = '0f0e0d0c-0b0a-4908-8706-050403020101';
const state = x => `[${status(x)}, document.querySelector('${x} [data-drawer-stop]')?.firstChild.textContent, document.querySelector('${x} [data-drawer-stop]')?.disabled, document.querySelector('${x} [data-drawer-restart]')?.disabled]`;
const ask = async x => {
await b.evaluate(`document.querySelector('${x} [data-drawer-stop]').click()`);
await wait(`document.querySelector('${x} [data-drawer-stop-yes]')`);
await b.evaluate(`document.querySelector('${x} [data-drawer-stop-yes]').click()`);
};
const show = async (agent, x) => {
await b.evaluate(`location.hash = "#/agents?agent=acme%3A${agent}"`);
await wait(`${open(`acme:${agent}`)} && document.querySelector('${x} [data-drawer-stop]')`);
};
// Both terminates are held: coder's the bus takes, ideas' it refuses.
await b.evaluate(`window.__answers.push(
{ hold: new Promise(r => { window.__releaseCoder = r; }), status: 200, body: { sent: true, request: '${REQ}' } },
{ hold: new Promise(r => { window.__releaseIdeas = r; }), status: 409, body: { error: 'instance-protected', message: 'instance-protected: ideas is protected from ending. Nothing changed.', sent: false } },
{ status: 200, body: { request: '${REQ}', state: 'closed' } })`);
await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-stop]')`);
await ask(d);
await wait('window.__posts.length === 1');
await show('ideas', i);
await ask(i);
await wait('window.__posts.length === 2');
assert.deepEqual(await b.evaluate(state(i)), ['Stopping ideas…', 'Stopping…', true, true]);
// Coder's Stop ends while ideas' drawer is on screen; ideas' Stop still runs.
await b.evaluate('window.__releaseCoder()');
await wait('window.__posts.length === 3');
await b.evaluate('new Promise(r => setTimeout(r, 300))');
await wait(`${open('acme:ideas')} && document.querySelector('${i} [data-drawer-stop]')`);
assert.deepEqual(await b.evaluate(state(i)), ['Stopping ideas…', 'Stopping…', true, true]);
await show('coder', d);
assert.deepEqual(await b.evaluate(state(d)), ['Stopped coder.', 'Stop', false, false]);
// Ideas' Stop is refused; each drawer keeps its own line.
await show('ideas', i);
assert.deepEqual(await b.evaluate(state(i)), ['Stopping ideas…', 'Stopping…', true, true]);
await b.evaluate('window.__releaseIdeas()');
await wait(`/^Not stopped: /.test(${status(i)}) && ${usable(i)}`);
assert.deepEqual(await b.evaluate(state(i)), ['Not stopped: instance-protected: ideas is protected from ending. Nothing changed.', 'Stop', false, false]);
await show('coder', d);
assert.deepEqual(await b.evaluate(state(d)), ['Stopped coder.', 'Stop', false, false]);
assert.deepEqual((await b.evaluate('window.__posts')).map(p => [p.url, p.method]), [
['/api/orgs/acme/agent/terminate', 'POST'], ['/api/orgs/acme/agent/terminate', 'POST'], [`/api/orgs/acme/agent/request?id=${REQ}`, 'GET']]);
assert.deepEqual((await b.evaluate('window.__posts')).slice(0, 2).map(p => JSON.parse(p.body).instance), ['coder', 'ideas']);
assert.equal(await b.evaluate('window.__answers.length'), 0, 'every queued answer was asked for');
});