From 05be6c62bd39f054cc57fb4ba90b3f7488f7a027 Mon Sep 17 00:00:00 2001
From: Jason Woltje
No Message: this Console does not send chat in ${esc(orgName)}.
`); - if (change && a.level === 'org' && !a.keep && running(item) > 0) acts.push(stopActions(pick, a, orgName)); + // SP19: a restart that is running keeps its buttons even when a repaint reads no run between its end and its launch. + if (change && a.level === 'org' && !a.keep && (running(item) > 0 || restarting.has(id))) acts.push(stopActions(pick, a, orgName, !!window.MosaicAgents?.isThread?.(def))); // Why Stop is not offered, in words, where this Console could otherwise change the organization's agents. // SP13: "not running" is a reason only once the instances read has given the agent's runs. else if (change) acts.push(`${reading ? 'Its state is being read. Stop is offered once it is read and the agent is running.'
@@ -1420,7 +1430,7 @@
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}…` };
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'; } now.querySelector('[data-drawer-stop-confirm]')?.remove(); };
+ 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();
let res, body = null;
@@ -1448,6 +1458,63 @@
}
finish(`Request ${request} is still open. Read the agents again later.`);
}
+ // SP19: the drawer's Restart. The agents.js chain ends the agent through its own organization's routes
+ // (the drawer's, which on #/agents is not the page's), waits for the request to close and its runs to
+ // reach 0, then launches it; a conversation agent is not launched. It never regenerates. Each step is
+ // painted in place; a refusal leaves both buttons usable and focus on Restart.
+ const refusedWhy = (d, orgName) => {
+ const e = d?.result?.error, m = d?.result?.message;
+ 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 (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;
+ };
+ const restartWords = (name, orgName) => (step, d) => ({
+ ending: `Restarting ${name}: asking it to end…`,
+ signedOut: 'Not restarted: sign in again, then read the agents.',
+ endUnknown: `Not restarted: ${STOP_UNKNOWN}`,
+ endRefused: `Not restarted: ${refusedWhy(d, orgName)}`,
+ endOpen: `Not restarted: ${d?.stop}`,
+ endClosed: `Not restarted: ${name} was not ended (${d?.reason}).`,
+ ended: `${name} was asked to end. Waiting for its session to end…`,
+ stillRunning: `Not restarted: ${name} was asked to end, but its session is still running. Read the agents again before trying.`,
+ threadEnded: `Ended ${name} at ${d?.time}. Its next message starts it.`,
+ launching: `${name} has ended. Launching it…`,
+ launchSignedOut: `${name} was ended and not launched: sign in again, then read the agents.`,
+ launchUnknown: `${name} was ended. The launch outcome is unknown; read the agents again before trying. Nothing was retried.`,
+ launchRefused: `${name} was ended and not launched: ${refusedWhy(d, orgName)}`,
+ launchOpen: `${name} was ended. ${d?.stop}`,
+ launchClosed: `${name} was ended and not launched: ${d?.reason}.`,
+ restarted: `Restarted ${name}${d?.run ? ` (run ${d.run})` : ''}.`,
+ })[step];
+ async function restartAgent(d) {
+ const id = d.dataset.wsDrawer, org = d.dataset.drawerOrgId, name = id.slice(org.length + 1), orgName = d.dataset.drawerOrgName;
+ const thread = d.querySelector('[data-drawer-restart]')?.dataset.drawerThread === 'yes';
+ if (restarting.has(id)) return;
+ restarting.add(id);
+ const paint = () => {
+ const now = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`); if (!now || stopState?.id !== id) return;
+ const s = now.querySelector('[data-drawer-status]'); if (s) s.textContent = stopState.text;
+ const rb = now.querySelector('[data-drawer-restart]'), sb = now.querySelector('[data-drawer-stop]');
+ if (rb) { rb.disabled = !!stopState.busy; rb.firstChild.textContent = stopState.busy ? 'Restarting…' : 'Restart'; }
+ if (sb) sb.disabled = !!stopState.busy;
+ now.querySelector('.ws-drawer-confirm')?.remove();
+ };
+ const onStatus = ({ step, busy, text }) => {
+ if (!busy) restarting.delete(id);
+ // Another drawer's question or action may hold the state now; this chain then leaves it alone.
+ if (stopState && stopState.id !== id) return;
+ stopState = busy ? { id, kind: 'restart', busy: true, text } : { id, kind: 'restart', text };
+ paint();
+ if (busy) return;
+ document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"] [data-drawer-restart]`)?.focus({ preventScroll: true });
+ if (step === 'restarted' || step === 'threadEnded') document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
+ };
+ try { await window.MosaicAgents.restart(name, thread, { org, reason: RESTART_REASON, text: restartWords(name, orgName), onStatus }); }
+ catch { restarting.delete(id); stopState = { id, kind: 'restart', text: `Not restarted: ${STOP_UNKNOWN}` }; paint(); }
+ }
document.addEventListener('click', e => {
const link = e.target.closest?.('[data-ws-drawer-open]');
if (link) {
@@ -1466,33 +1533,41 @@
if (!d) return;
if (e.target.closest('[data-drawer-close]')) { closeDrawer(); return; }
const id = d.dataset.wsDrawer;
- if (e.target.closest('[data-drawer-stop]') && !(stopState?.id === id && stopState.busy)) {
- const b = d.querySelector('[data-drawer-stop]'), name = d.dataset.drawerName;
- stopState = { id, confirm: true, text: '' };
- d.querySelector('[data-drawer-stop-confirm]')?.remove();
- b.insertAdjacentHTML('afterend', stopConfirm(name, `${name} in ${d.dataset.drawerOrgName}`));
- b.disabled = true;
+ // SP19: nothing starts while this agent's Stop or Restart runs.
+ const held = (stopState?.id === id && stopState.busy) || restarting.has(id);
+ 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: '' };
+ 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;
const s = d.querySelector('[data-drawer-status]'); if (s) s.textContent = '';
- d.querySelector('[data-drawer-stop-no]')?.focus({ preventScroll: true });
+ d.querySelector(`[data-drawer-${ask}-no]`)?.focus({ preventScroll: true });
return;
}
- if (e.target.closest('[data-drawer-stop-no]')) { cancelStop(d); return; }
+ if (ask) return;
+ if (e.target.closest('[data-drawer-stop-no], [data-drawer-restart-no]')) { cancelStop(d); return; }
+ if (held) return;
if (e.target.closest('[data-drawer-stop-yes]')) stopAgent(d);
+ else if (e.target.closest('[data-drawer-restart-yes]')) restartAgent(d);
});
- // Cancel the Stop question: nothing sent, Stop enabled again and focused.
+ // 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;
- d.querySelector('[data-drawer-stop-confirm]')?.remove();
- const b = d.querySelector('[data-drawer-stop]'); if (b) { b.disabled = false; b.focus({ preventScroll: true }); }
+ 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 });
}
- // Escape cancels the Stop question while it asks, else closes the drawer, unless a dialog is open
+ // Escape cancels the Stop or Restart question while it asks, else closes the drawer, unless a dialog is open
// or something else took the key.
document.addEventListener('keydown', e => {
if (e.key !== 'Escape' || e.defaultPrevented || document.querySelector('dialog[open]')) return;
const d = document.querySelector('#bus-view [data-ws-drawer]');
if (!d) return;
e.preventDefault();
- if (d.querySelector('[data-drawer-stop-confirm]')) cancelStop(d); else closeDrawer();
+ if (d.querySelector('.ws-drawer-confirm')) cancelStop(d); else closeDrawer();
});
// ---- controls: filters write the hash query and repaint in place ----
diff --git a/packages/webui/tests/agent-drawer-browser.test.mjs b/packages/webui/tests/agent-drawer-browser.test.mjs
index 62773fce1..064c194df 100644
--- a/packages/webui/tests/agent-drawer-browser.test.mjs
+++ b/packages/webui/tests/agent-drawer-browser.test.mjs
@@ -108,10 +108,20 @@ const STUB = `(() => {
if (window.__packsBody) return new Response(window.__packsBody, { status: 200, headers: { 'content-type': 'text/html' } });
return answer(200, { writable: false, applied: [{ id: 'coding', origin: 'shipped', project: null, hired: ['research-2'], open: [] }], packs: packs[1] === 'beta' ? [{ id: 'coding', origin: 'shipped', pack: { id: 'coding', label: 'Coding', version: 2, hires: [{ name: 'research-2', definition: 'researcher', reason: 'Research.' }], definitions: { researcher: { template: 'researcher', sha256: '${'a'.repeat(64)}' } } } }] : [] });
}
+ // SP19: a test may set __runs[org][name] to the runs the instances read lists for that agent.
+ const inst = u.match(/^\\/api\\/orgs\\/([^/]+)\\/bus\\/instances$/);
+ if (inst && window.__runs?.[inst[1]]) {
+ const got = await real(url, init), v = await got.json();
+ for (const [n, runs] of Object.entries(window.__runs[inst[1]])) if (v?.rows?.[0]?.instances?.[n]) v.rows[0].instances[n].running = runs;
+ return answer(got.status, v);
+ }
if (!/\\/agent\\//.test(u) || (init.method || 'GET') === 'GET' && !u.includes('/agent/request')) return real(url, init);
window.__posts.push({ url: u, method: init.method || 'GET', body: init.body ?? null });
const a = window.__answers.shift();
if (!a) throw new TypeError('no answer queued');
+ // SP19: an answer may wait on a promise (\`hold\`) and run a step once it is given (\`then\`).
+ if (a.hold) await a.hold;
+ a.then?.();
return answer(a.status ?? 200, a.body);
};
})();`;
@@ -711,3 +721,143 @@ test('triage-followups: a drawer opened before the first render ends keeps focus
await new Promise(r => setTimeout(r, 400));
assert.equal(await b.evaluate(`${drawer('acme:coder')}.contains(document.activeElement)`), true, `focus stays in the drawer, not on ${await b.evaluate('document.activeElement?.tagName')}`);
});
+
+// SP19 (#1873): Restart in the drawer, offered only where Stop is. It reuses Stop's confirm step and
+// status line, ends the agent through its own organization's /agent/terminate, waits for the request to
+// close and for its runs to reach 0, then launches it through /agent/launch. It never regenerates. A
+// conversation agent is ended and not launched. The page's 2 s poll steps run every 20 ms here.
+const FAST = `(() => { const st = window.setTimeout.bind(window); window.setTimeout = (f, ms, ...a) => st(f, ms === 2000 ? 20 : ms, ...a); })()`;
+const END = '5e000000-0000-4000-8000-0000000000e1', LAUNCH = '5e000000-0000-4000-8000-0000000000a1';
+const closed = (request, action, extra = {}) => ({ request, instance: 'coder', action, state: 'closed', done: { run: null, transaction: null, refusal: null }, cancelled: null, ...extra });
+// Every distinct state of the drawer's actions, from now on: [status, Restart's label, Restart disabled, Stop disabled].
+const WATCH = id => `(() => { window.__seen = []; const snap = () => { const d = document.querySelector('[data-ws-drawer="${id}"]'); if (!d) return; const r = d.querySelector('[data-drawer-restart]'), s = d.querySelector('[data-drawer-stop]'); const v = [d.querySelector('[data-drawer-status]')?.textContent ?? '', r ? r.firstChild.textContent : null, !!r?.disabled, !!s?.disabled]; const l = window.__seen.at(-1); if (!l || l.join('|') !== v.join('|')) window.__seen.push(v); }; snap(); new MutationObserver(snap).observe(document.getElementById('bus-view'), { subtree: true, childList: true, characterData: true, attributes: true }); return true; })()`;
+const status = d => `(document.querySelector('${d} [data-drawer-status]')?.textContent ?? "")`;
+const usable = d => `!document.querySelector('${d} [data-drawer-restart]').disabled && !document.querySelector('${d} [data-drawer-stop]').disabled && !document.querySelector('${d} .ws-drawer-confirm')`;
+
+test('SP19: Restart asks first, then ends and launches the agent in its own organization, and never regenerates', async t => {
+ // The reader was last on Beta Works, so the Console's chosen organization is beta. #/agents shows every
+ // organization's agents; the drawer's own organization is used, not the chosen one.
+ const { b, wait, text } = await setup(t, { hash: '#/orgs/beta/organization', scripts: [FAST] });
+ await wait(`window.MosaicOrg?.id === 'beta' && document.querySelectorAll("[data-org-settings] [data-org-setting]").length > 0`);
+ await b.evaluate('location.hash = "#/agents?agent=acme%3Acoder"');
+ const d = '[data-ws-drawer="acme:coder"]';
+ await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`);
+ assert.equal(await b.evaluate('window.MosaicOrg?.id ?? null'), 'beta');
+ // Beside Stop, in the same action group as the status line.
+ assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').closest('[data-drawer-actions]') === document.querySelector('${d} [data-drawer-stop]').closest('[data-drawer-actions]')`), true);
+ assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').textContent`), 'Restart coder in Acme Studio');
+ // It asks first, in Stop's confirm step. Cancel sends nothing and puts focus back on Restart.
+ await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
+ await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
+ assert.match(await text(`${d} [data-drawer-restart-confirm]`), /^Restart coder in Acme Studio\? It ends its session and launches it again\. Restart coder Cancel$/);
+ assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-restart-confirm]').classList.contains('ws-drawer-confirm')`), true);
+ assert.deepEqual(await b.evaluate(`[document.querySelector('${d} [data-drawer-restart]').disabled, document.querySelector('${d} [data-drawer-stop]').disabled]`), [true, true]);
+ await b.evaluate(`document.querySelector('${d} [data-drawer-restart-no]').click()`);
+ await wait(`document.activeElement === document.querySelector('${d} [data-drawer-restart]') && ${usable(d)}`);
+ // Escape cancels the question too, and the drawer stays.
+ await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
+ await wait(`document.querySelector('${d} [data-drawer-restart-no]') === document.activeElement`);
+ await b.key('Escape');
+ await wait(`document.activeElement === document.querySelector('${d} [data-drawer-restart]') && ${usable(d)}`);
+ assert.equal(await b.evaluate(agentParam), 'acme:coder');
+ assert.deepEqual(await b.evaluate('window.__posts'), []);
+ // Yes: one terminate, its request followed until it closes, the runs read until none is left, one launch.
+ await b.evaluate(`window.__answers.push(
+ { body: { request: '${END}', runs: ['run-1'], cancelled: [], taken: [] }, then: () => { window.__runs = { acme: { coder: [] } }; } },
+ { body: ${JSON.stringify(closed(END, 'end'))} },
+ { body: { request: '${LAUNCH}' }, then: () => { window.__runs = { acme: { coder: ['run-2'] } }; } },
+ { body: ${JSON.stringify(closed(LAUNCH, 'launch', { done: { run: 'run-2', transaction: null, refusal: null } }))} })`);
+ await b.evaluate(WATCH('acme:coder'));
+ await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
+ await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
+ await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`);
+ await wait(`/^Restarted coder \\(run run-2\\)\\.$/.test(${status(d)}) && ${usable(d)}`);
+ const posts = await b.evaluate('window.__posts');
+ assert.deepEqual(posts.map(p => [p.url, p.method]), [
+ ['/api/orgs/acme/agent/terminate', 'POST'], [`/api/orgs/acme/agent/request?id=${END}`, 'GET'],
+ ['/api/orgs/acme/agent/launch', 'POST'], [`/api/orgs/acme/agent/request?id=${LAUNCH}`, 'GET'],
+ ]);
+ assert.deepEqual(JSON.parse(posts[0].body), { instance: 'coder', reason: 'restart from the agent drawer' });
+ assert.deepEqual(JSON.parse(posts[2].body), { instance: 'coder' });
+ assert.equal(posts.some(p => /regenerate/.test(p.url)), false, 'Restart never regenerates');
+ // The status line names each step; while it runs, Restart reads Restarting… and both buttons wait.
+ const seen = await b.evaluate('window.__seen');
+ const steps = seen.map(s => s[0]).filter((s, i, all) => s && s !== all[i - 1]);
+ assert.deepEqual(steps, ['Restarting coder: asking it to end…', 'coder was asked to end. Waiting for its session to end…', 'coder has ended. Launching it…', 'Restarted coder (run run-2).']);
+ for (const [s, label, rd, sd] of seen.filter(s => steps.slice(0, 3).includes(s[0]))) assert.deepEqual([label, rd, sd], ['Restarting…', true, true], s);
+ assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').firstChild.textContent`), 'Restart');
+});
+
+// The Assistant is a protected agent, so it has no Stop and no Restart; ideas is a conversation agent that is not.
+test('SP19: a conversation agent is ended and not launched; its next message starts it', async t => {
+ const data = D => { D.acme.instances.ideas = { definition: 'ideas', running: ['run-4'] }; };
+ const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Aideas', scripts: [FAST], data });
+ const d = '[data-ws-drawer="acme:ideas"]';
+ await wait(`${open('acme:ideas')} && document.querySelector('${d} [data-drawer-restart]')`);
+ assert.equal(await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').dataset.drawerThread`), 'yes');
+ await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
+ await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
+ assert.match(await b.evaluate(`document.querySelector('${d} [data-drawer-restart-confirm]').textContent`), /^Restart ideas in Acme Studio\? It ends its session; its next message starts it again\./);
+ await b.evaluate(`window.__answers.push(
+ { body: { request: '${END}', runs: ['run-4'], cancelled: [], taken: [] }, then: () => { window.__runs = { acme: { ideas: [] } }; } },
+ { body: ${JSON.stringify({ ...closed(END, 'end'), instance: 'ideas' })} })`);
+ await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`);
+ await wait(`/^Ended ideas at .+\\. Its next message starts it\\.$/.test(${status(d)})`);
+ const posts = await b.evaluate('window.__posts');
+ assert.deepEqual(posts.map(p => [p.url, p.method]), [['/api/orgs/acme/agent/terminate', 'POST'], [`/api/orgs/acme/agent/request?id=${END}`, 'GET']]);
+ assert.deepEqual(JSON.parse(posts[0].body), { instance: 'ideas', reason: 'restart from the agent drawer' });
+});
+
+test('SP19: a second click while a restart runs does nothing', async t => {
+ const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', scripts: [FAST] });
+ const d = '[data-ws-drawer="acme:coder"]';
+ await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`);
+ // The terminate's answer is held, so the restart is still running while the page is clicked again.
+ await b.evaluate(`window.__answers.push({ hold: new Promise(r => { window.__release = r; }), status: 403, body: { error: 'unavailable', sent: false } })`);
+ await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
+ await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
+ await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`);
+ await wait(`window.__posts.length === 1 && document.querySelector('${d} [data-drawer-restart]').disabled`);
+ // Even a Restart button made clickable again starts nothing: no second question, no second request.
+ await b.evaluate(`(() => { const r = document.querySelector('${d} [data-drawer-restart]'), s = document.querySelector('${d} [data-drawer-stop]'); r.disabled = false; s.disabled = false; r.click(); s.click(); return true; })()`);
+ await b.evaluate('new Promise(r => setTimeout(r, 300))');
+ assert.equal(await b.evaluate(`!!document.querySelector('${d} .ws-drawer-confirm')`), false);
+ assert.equal(await b.evaluate('window.__posts.length'), 1);
+ await b.evaluate('window.__release()');
+ await wait(`/^Not restarted:/.test(${status(d)}) && ${usable(d)}`);
+ assert.equal(await b.evaluate('window.__posts.length'), 1);
+});
+
+// Each refusal the two routes can give says so in one plain line and leaves both buttons usable.
+const ENDED = [{ body: { request: END, runs: ['run-1'], cancelled: [], taken: [] }, runs: [] }, { body: closed(END, 'end') }];
+for (const [label, answers, line] of [
+ ['not the owner', [{ status: 403, body: { error: 'unavailable', sent: false } }],
+ /^Not restarted: this Console is not the owner of Acme Studio, so it does not restart its agents\.$/],
+ ['the bus is stopped', [{ status: 503, body: { error: 'no-bus-host', message: 'no-bus-host: no-bus-host. Nothing changed.', sent: false } }],
+ /^Not restarted: the bus of Acme Studio is not running\. Nothing changed\.$/],
+ ['the end is refused', [{ body: { request: END, runs: ['run-1'], cancelled: [], taken: [] } }, { body: { ...closed(END, 'end', { done: { run: null, transaction: null, refusal: 'instance-kept' } }), reason: 'the instance is kept; unkeep it first' } }],
+ /^Not restarted: coder was not ended \(the instance is kept; unkeep it first\)\.$/],
+ ['the launch is refused', [...ENDED, { status: 409, body: { error: 'capacity-full', message: 'capacity-full: a launch limit is reached. Nothing changed.', sent: false } }],
+ /^coder was ended and not launched: capacity-full: a launch limit is reached\. Nothing changed\.$/],
+ ['the launch request closes refused', [...ENDED, { body: { request: LAUNCH } }, { body: { ...closed(LAUNCH, 'launch', { done: { run: null, transaction: null, refusal: 'no-route' } }), reason: 'the instance has no harness, model and thinking yet; set its route first' } }],
+ /^coder was ended and not launched: the instance has no harness, model and thinking yet; set its route first\.$/],
+ ['its runs never reach 0', [{ body: { request: END, runs: ['run-1'], cancelled: [], taken: [] } }, { body: closed(END, 'end') }],
+ /^Not restarted: coder was asked to end, but its session is still running\. Read the agents again before trying\.$/],
+]) test(`SP19: a refusal says so in the drawer and leaves the buttons usable: ${label}`, async t => {
+ const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', scripts: [FAST] });
+ const d = '[data-ws-drawer="acme:coder"]';
+ await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`);
+ const queued = JSON.stringify(answers);
+ await b.evaluate(`window.__answers.push(...${queued}.map(a => a.runs ? { ...a, then: () => { window.__runs = { acme: { coder: a.runs } }; } } : a))`);
+ await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`);
+ await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`);
+ await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`);
+ await wait(`${status(d)} && !document.querySelector('${d} [data-drawer-restart]').disabled`);
+ assert.match(await b.evaluate(status(d)), line);
+ assert.equal(await b.evaluate(usable(d)), true, 'both buttons are usable again');
+ assert.equal(await b.evaluate(`document.activeElement === document.querySelector('${d} [data-drawer-restart]')`), true, 'focus is back on Restart');
+ const posts = await b.evaluate('window.__posts');
+ assert.equal(posts.some(p => /regenerate/.test(p.url)), false);
+ assert.equal(posts.filter(p => p.url.endsWith('/agent/launch')).length, label.startsWith('the launch') ? 1 : 0);
+ assert.equal(await b.evaluate('window.__answers.length'), 0, 'every queued answer was asked for');
+});
diff --git a/packages/webui/tests/routes-apply-browser.test.mjs b/packages/webui/tests/routes-apply-browser.test.mjs
index ec3edc11f..ae290c3f2 100644
--- a/packages/webui/tests/routes-apply-browser.test.mjs
+++ b/packages/webui/tests/routes-apply-browser.test.mjs
@@ -20,7 +20,8 @@ const END = '10000000-0000-4000-8000-0000000000e1', LAUNCH = '10000000-0000-4000
const DEV = { provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner', name: 'Local operator' };
const route = thinking => ({ harness: 'claude', model: 'opus', thinking, fallback: null });
-test('F3 Settings > Routing: a save lists how the change reaches each agent, and Restart now moves a running one', { timeout: 120000 }, async t => {
+// A real server with the stub bus, on Settings > Routing. `refusal` closes coder's end request with that code.
+async function stage(t, { refusal = null } = {}) {
const root = mkdtempSync(join(tmpdir(), 'f3r-')); t.after(() => rmSync(root, { recursive: true, force: true }));
const entry = (definition, extra) => ({ definition, vars: {}, launched: true, launcher: false, protected: false, kept: false, running: [], alive: [], ...extra });
const instances = {
@@ -52,7 +53,7 @@ test('F3 Settings > Routing: a save lists how the change reaches each agent, and
if (verb === 'instance.launch') { requests.set(LAUNCH, { instance: args.instance, action: 'launch' }); instances[args.instance].running = ['run-2']; return { request: LAUNCH }; }
if (verb === 'instance.request') {
const r = requests.get(args.request);
- return { request: args.request, instance: r.instance, action: r.action, state: 'closed', done: { run: r.action === 'launch' ? 'run-2' : null, transaction: null, refusal: null }, cancelled: null };
+ return { request: args.request, instance: r.instance, action: r.action, state: 'closed', done: { run: r.action === 'launch' ? 'run-2' : null, transaction: null, refusal: r.action === 'end' && r.instance === 'coder' ? refusal : null }, cancelled: null };
}
throw Error(`unexpected ${verb}`);
};
@@ -72,6 +73,11 @@ test('F3 Settings > Routing: a save lists how the change reaches each agent, and
for (const name of ['chief', 'coder', 'assistant', 'reviewer']) await b.evaluate(`(()=>{const s=${cell(name, 'thinking')};s.value='low';s.dispatchEvent(new Event('change',{bubbles:true}));return true;})()`);
await b.evaluate(`document.getElementById('routes-form').requestSubmit();true`);
await wait(`document.querySelector('.routes-apply')`);
+ return { b, wait, asked, items, dir };
+}
+
+test('F3 Settings > Routing: a save lists how the change reaches each agent, and Restart now moves a running one', { timeout: 120000 }, async t => {
+ const { b, wait, asked, items, dir } = await stage(t);
assert.deepEqual(asked, [['routes.set', { revision: REV, routes: { chief: route('low'), coder: route('low'), assistant: route('low'), reviewer: route('low') } }]]);
assert.equal(await b.evaluate(`document.getElementById('routes-receipt').textContent`), 'Routes saved for chief, coder, assistant, reviewer. The next launch of each uses the new route.');
assert.deepEqual(await items(), [
@@ -103,3 +109,29 @@ test('F3 Settings > Routing: a save lists how the change reaches each agent, and
await b.viewport(390, 844);
assert.equal(await b.evaluate(`document.documentElement.scrollWidth<=390`), true, 'no sideways scroll at phone width');
});
+
+// SP19 (#1873): the drawer's Restart shares this chain. The route-change flow keeps its reason, its
+// unprefixed routes and every line it shows, step by step, and its refusal line.
+const WATCH = name => `(()=>{window.__seen=[];const snap=()=>{const s=document.querySelector('[data-agent-restart-status="${name}"]')?.textContent??'';if(s&&s!==window.__seen.at(-1))window.__seen.push(s);};new MutationObserver(snap).observe(document.body,{subtree:true,childList:true,characterData:true});return true;})()`;
+test('SP19: Restart now keeps its reason and its words', { timeout: 120000 }, async t => {
+ const { b, wait, asked } = await stage(t);
+ const posts = [];
+ await b.evaluate(`(()=>{const f=window.fetch;window.__urls=[];window.fetch=(u,o)=>{window.__urls.push(String(u));return f(u,o);};return true;})()`);
+ await b.evaluate(WATCH('coder'));
+ await b.evaluate(`document.querySelector('[data-agent-restart="coder"]').click();true`);
+ await wait(`document.querySelector('[data-agent-restart-status="coder"]')?.textContent==='Restarted coder on the new route (run run-2).'`, 30000);
+ assert.deepEqual(await b.evaluate('window.__seen'), ['Terminating coder…', 'Terminated coder. Waiting for its session to end…', 'Launching coder…', 'Restarted coder on the new route (run run-2).']);
+ assert.deepEqual(asked.filter(([v]) => v === 'instance.end'), [['instance.end', { instance: 'coder', reason: 'route change' }]]);
+ posts.push(...(await b.evaluate('window.__urls')).filter(u => /\/api\/agent\/(terminate|launch|regenerate)/.test(u)));
+ assert.deepEqual(posts, ['/api/agent/terminate', '/api/agent/launch']);
+ assert.equal(await b.evaluate(`document.querySelector('[data-agent-restart="coder"]').textContent`), 'Restart coder now');
+});
+
+test('SP19: Restart now says when the end is refused, in its own words', { timeout: 120000 }, async t => {
+ const { b, wait, asked } = await stage(t, { refusal: 'instance-kept' });
+ await b.evaluate(`document.querySelector('[data-agent-restart="coder"]').click();true`);
+ await wait(`/It was not restarted/.test(document.querySelector('[data-agent-restart-status="coder"]')?.textContent??'')`, 30000);
+ assert.equal(await b.evaluate(`document.querySelector('[data-agent-restart-status="coder"]').textContent`), 'coder: the instance is kept; unkeep it first. It was not restarted.');
+ assert.equal(asked.filter(([v]) => v === 'instance.launch').length, 0);
+ assert.equal(await b.evaluate(`document.querySelector('[data-agent-restart="coder"]').disabled`), false);
+});
--
2.54.0
From 4b833d23e9867b24d5ac5cabab7f6c123f809c78 Mon Sep 17 00:00:00 2001
From: Jason Woltje
No Message: this Console does not send chat in ${esc(orgName)}.
`); // SP19: a restart that is running keeps its buttons even when a repaint reads no run between its end and its launch. - if (change && a.level === 'org' && !a.keep && (running(item) > 0 || restarting.has(id))) acts.push(stopActions(pick, a, orgName, !!window.MosaicAgents?.isThread?.(def))); + if (change && a.level === 'org' && !a.keep && (running(item) > 0 || restarts.get(id)?.busy)) acts.push(stopActions(pick, a, orgName, !!window.MosaicAgents?.isThread?.(def))); // Why Stop is not offered, in words, where this Console could otherwise change the organization's agents. // SP13: "not running" is a reason only once the instances read has given the agent's runs. else if (change) acts.push(`${reading ? 'Its state is being read. Stop is offered once it is read and the agent is running.' @@ -1353,7 +1357,7 @@ : a.level !== 'org' ? 'A copy is not stopped from here.' : a.keep ? `${esc(a.name)} is one of ${esc(orgName)}’s protected agents, so it is not stopped from here.` : 'It is not running, so there is nothing to stop.'}
`); - const st = stopState?.id === id ? stopState : null; + const st = actState(id); const actions = chat || change ? `${esc(st?.text || '')}
This Console only reads ${esc(orgName)}. It can not message or stop its agents.
`; @@ -1393,6 +1397,7 @@ // `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, r] of restarts) if (!r.busy) restarts.delete(k); if (stateOf()?.[DRAWER_MARK] && queryOf().has('agent')) { history.back(); return; } history.replaceState(unmarked(), '', sansAgent()); document.dispatchEvent(new CustomEvent('mosaic-workspace-render')); @@ -1461,12 +1466,14 @@ // SP19: the drawer's Restart. The agents.js chain ends the agent through its own organization's routes // (the drawer's, which on #/agents is not the page's), waits for the request to close and its runs to // reach 0, then launches it; a conversation agent is not launched. It never regenerates. Each step is - // painted in place; a refusal leaves both buttons usable and focus on Restart. + // painted in place; a refusal before the end leaves both buttons usable and focus on Restart. const refusedWhy = (d, orgName) => { const e = d?.result?.error, m = d?.result?.message; 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.`; 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; @@ -1492,28 +1499,35 @@ async function restartAgent(d) { const id = d.dataset.wsDrawer, org = d.dataset.drawerOrgId, name = id.slice(org.length + 1), orgName = d.dataset.drawerOrgName; const thread = d.querySelector('[data-drawer-restart]')?.dataset.drawerThread === 'yes'; - if (restarting.has(id)) return; - restarting.add(id); + 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; + 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)}"]`); if (!now || stopState?.id !== id) return; - const s = now.querySelector('[data-drawer-status]'); if (s) s.textContent = stopState.text; + const now = document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`), r = restarts.get(id); if (!now || !r || stopState?.id === 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 = !!stopState.busy; rb.firstChild.textContent = stopState.busy ? 'Restarting…' : 'Restart'; } - if (sb) sb.disabled = !!stopState.busy; + if (rb) { rb.disabled = r.busy; rb.firstChild.textContent = r.busy ? 'Restarting…' : 'Restart'; } + if (sb) sb.disabled = r.busy; now.querySelector('.ws-drawer-confirm')?.remove(); }; + // The finished line stays in the entry. A refusal before the end changed nothing, so focus goes back + // to Restart. Once the agent was ended its runs changed: the repaint reads the instances again, so the + // buttons follow them (after a refused launch it has none, so Stop and Restart go), and focus goes to + // the drawer's heading, which every repaint keeps. + const after = new Set(['restarted', 'threadEnded', 'launchSignedOut', 'launchUnknown', 'launchRefused', 'launchOpen', 'launchClosed']); + const done = step => { + document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"]`)?.querySelector(after.has(step) ? '[data-focus-key="drawer-h"]' : '[data-drawer-restart]')?.focus({ preventScroll: true }); + if (after.has(step)) document.dispatchEvent(new CustomEvent('mosaic-workspace-render')); + }; const onStatus = ({ step, busy, text }) => { - if (!busy) restarting.delete(id); - // Another drawer's question or action may hold the state now; this chain then leaves it alone. - if (stopState && stopState.id !== id) return; - stopState = busy ? { id, kind: 'restart', busy: true, text } : { id, kind: 'restart', text }; + restarts.set(id, { busy: !!busy, text }); paint(); - if (busy) return; - document.querySelector(`[data-ws-drawer="${CSS.escape(id)}"] [data-drawer-restart]`)?.focus({ preventScroll: true }); - if (step === 'restarted' || step === 'threadEnded') document.dispatchEvent(new CustomEvent('mosaic-workspace-render')); + if (!busy) done(step); }; try { await window.MosaicAgents.restart(name, thread, { org, reason: RESTART_REASON, text: restartWords(name, orgName), onStatus }); } - catch { restarting.delete(id); stopState = { id, kind: 'restart', text: `Not restarted: ${STOP_UNKNOWN}` }; paint(); } + catch { restarts.set(id, { busy: false, text: `Not restarted: ${STOP_UNKNOWN}` }); paint(); done('endUnknown'); } } document.addEventListener('click', e => { const link = e.target.closest?.('[data-ws-drawer-open]'); @@ -1534,11 +1548,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) || restarting.has(id); + const held = (stopState?.id === id && stopState.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: '' }; + stopState = { 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; diff --git a/packages/webui/tests/agent-drawer-browser.test.mjs b/packages/webui/tests/agent-drawer-browser.test.mjs index 064c194df..3ae08cdb9 100644 --- a/packages/webui/tests/agent-drawer-browser.test.mjs +++ b/packages/webui/tests/agent-drawer-browser.test.mjs @@ -732,7 +732,7 @@ const closed = (request, action, extra = {}) => ({ request, instance: 'coder', a // Every distinct state of the drawer's actions, from now on: [status, Restart's label, Restart disabled, Stop disabled]. const WATCH = id => `(() => { window.__seen = []; const snap = () => { const d = document.querySelector('[data-ws-drawer="${id}"]'); if (!d) return; const r = d.querySelector('[data-drawer-restart]'), s = d.querySelector('[data-drawer-stop]'); const v = [d.querySelector('[data-drawer-status]')?.textContent ?? '', r ? r.firstChild.textContent : null, !!r?.disabled, !!s?.disabled]; const l = window.__seen.at(-1); if (!l || l.join('|') !== v.join('|')) window.__seen.push(v); }; snap(); new MutationObserver(snap).observe(document.getElementById('bus-view'), { subtree: true, childList: true, characterData: true, attributes: true }); return true; })()`; const status = d => `(document.querySelector('${d} [data-drawer-status]')?.textContent ?? "")`; -const usable = d => `!document.querySelector('${d} [data-drawer-restart]').disabled && !document.querySelector('${d} [data-drawer-stop]').disabled && !document.querySelector('${d} .ws-drawer-confirm')`; +const usable = d => `document.querySelector('${d} [data-drawer-restart]')?.disabled === false && document.querySelector('${d} [data-drawer-stop]')?.disabled === false && !document.querySelector('${d} .ws-drawer-confirm')`; test('SP19: Restart asks first, then ends and launches the agent in its own organization, and never regenerates', async t => { // The reader was last on Beta Works, so the Console's chosen organization is beta. #/agents shows every @@ -828,11 +828,52 @@ test('SP19: a second click while a restart runs does nothing', async t => { assert.equal(await b.evaluate('window.__posts.length'), 1); }); -// Each refusal the two routes can give says so in one plain line and leaves both buttons usable. +// SP19 review: a restart keeps its own state, so another drawer's question or Stop does not lose its +// line, and its drawer still shows it running when the reader comes back. +test('SP19: a restart keeps its line and its running state across another drawer\'s Stop', 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"]'; + await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`); + await b.evaluate(`window.__answers.push({ hold: new Promise(r => { window.__release = r; }), status: 403, body: { error: 'unavailable', sent: false } })`); + await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`); + await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`); + await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`); + await wait(`window.__posts.length === 1`); + // Ideas asks to stop and is cancelled; back on coder, its restart 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-restart]')`); + assert.deepEqual(await b.evaluate(`[${status(d)}, document.querySelector('${d} [data-drawer-restart]').firstChild.textContent, document.querySelector('${d} [data-drawer-restart]').disabled, document.querySelector('${d} [data-drawer-stop]').disabled]`), + ['Restarting coder: asking it to end…', 'Restarting…', true, true]); + // Ideas' Stop question is open when coder's restart is refused; coder's drawer still says so after. + 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))'); + assert.equal(await b.evaluate(`!!document.querySelector('${i} [data-drawer-stop-confirm]')`), true, 'the other drawer keeps its question'); + 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-restart]')`); + await wait(`${status(d)} === 'Not restarted: this Console is not the owner of Acme Studio, so it does not restart its agents.' && ${usable(d)}`); + assert.equal(await b.evaluate('window.__posts.length'), 1); +}); + +// Each refusal the two routes can give says so in one plain line. Where the agent still runs, both +// buttons are usable again and focus is on Restart; after a refused launch it has no run, so the +// repaint drops Stop and Restart, keeps the line and puts focus on the drawer's heading. const ENDED = [{ body: { request: END, runs: ['run-1'], cancelled: [], taken: [] }, runs: [] }, { body: closed(END, 'end') }]; for (const [label, answers, line] of [ ['not the owner', [{ status: 403, body: { error: 'unavailable', sent: false } }], /^Not restarted: this Console is not the owner of Acme Studio, so it does not restart its agents\.$/], + ['the organization is archived', [{ status: 409, body: { error: 'org-archived', message: 'organization is archived' } }], + /^Not restarted: Acme Studio is archived, so its agents are not changed\. Nothing changed\.$/], ['the bus is stopped', [{ status: 503, body: { error: 'no-bus-host', message: 'no-bus-host: no-bus-host. Nothing changed.', sent: false } }], /^Not restarted: the bus of Acme Studio is not running\. Nothing changed\.$/], ['the end is refused', [{ body: { request: END, runs: ['run-1'], cancelled: [], taken: [] } }, { body: { ...closed(END, 'end', { done: { run: null, transaction: null, refusal: 'instance-kept' } }), reason: 'the instance is kept; unkeep it first' } }], @@ -843,7 +884,7 @@ for (const [label, answers, line] of [ /^coder was ended and not launched: the instance has no harness, model and thinking yet; set its route first\.$/], ['its runs never reach 0', [{ body: { request: END, runs: ['run-1'], cancelled: [], taken: [] } }, { body: closed(END, 'end') }], /^Not restarted: coder was asked to end, but its session is still running\. Read the agents again before trying\.$/], -]) test(`SP19: a refusal says so in the drawer and leaves the buttons usable: ${label}`, async t => { +]) test(`SP19: a refusal says so in the drawer: ${label}`, async t => { const { b, wait } = await setup(t, { hash: '#/agents?agent=acme%3Acoder', scripts: [FAST] }); const d = '[data-ws-drawer="acme:coder"]'; await wait(`${open('acme:coder')} && document.querySelector('${d} [data-drawer-restart]')`); @@ -852,12 +893,20 @@ for (const [label, answers, line] of [ await b.evaluate(`document.querySelector('${d} [data-drawer-restart]').click()`); await wait(`document.querySelector('${d} [data-drawer-restart-yes]')`); await b.evaluate(`document.querySelector('${d} [data-drawer-restart-yes]').click()`); - await wait(`${status(d)} && !document.querySelector('${d} [data-drawer-restart]').disabled`); + const launched = label.startsWith('the launch'); + await wait(launched ? `/ was ended and not launched: /.test(${status(d)}) && !document.querySelector('${d} [data-drawer-restart]')` + : `/^Not restarted: /.test(${status(d)}) && document.querySelector('${d} [data-drawer-restart]')?.disabled === false`); + await b.evaluate('new Promise(r => setTimeout(r, 300))'); assert.match(await b.evaluate(status(d)), line); - assert.equal(await b.evaluate(usable(d)), true, 'both buttons are usable again'); - assert.equal(await b.evaluate(`document.activeElement === document.querySelector('${d} [data-drawer-restart]')`), true, 'focus is back on Restart'); + if (launched) { + assert.deepEqual(await b.evaluate(`[!!document.querySelector('${d} [data-drawer-stop]'), document.querySelector('${d} [data-drawer-nostop]')?.textContent]`), [false, 'It is not running, so there is nothing to stop.']); + assert.equal(await b.evaluate(`document.activeElement === document.querySelector('${d} h2')`), true, `focus is on the drawer heading, not ${await b.evaluate('document.activeElement?.outerHTML.slice(0, 80)')}`); + } else { + assert.equal(await b.evaluate(usable(d)), true, 'both buttons are usable again'); + assert.equal(await b.evaluate(`document.activeElement === document.querySelector('${d} [data-drawer-restart]')`), true, 'focus is back on Restart'); + } const posts = await b.evaluate('window.__posts'); assert.equal(posts.some(p => /regenerate/.test(p.url)), false); - assert.equal(posts.filter(p => p.url.endsWith('/agent/launch')).length, label.startsWith('the launch') ? 1 : 0); + 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'); }); -- 2.54.0 From 9a3004cba44da7c3726fbf1842bf88060ea66982 Mon Sep 17 00:00:00 2001 From: Jason Woltje