feat(webui): Restart in the agent drawer, through the existing end and launch routes and the drawer agent's own organization (#1873) #1990

Merged
jason.woltje merged 3 commits from sp19-drawer-restart into refactor 2026-11-18 19:43:17 +00:00
5 changed files with 378 additions and 49 deletions

No files matched your search

+30 -22
View File
@@ -193,7 +193,7 @@
catch { return { unknown: true }; }
if (res.type === 'opaqueredirect') return { signedOut: true };
try { result = await res.json(); } catch { return { unknown: true }; }
return { ok: res.ok, result };
return { ok: res.ok, status: res.status, result };
}
// The request's closing read, or a reason the chain stops.
async function closing(request, org) {
@@ -215,31 +215,39 @@
return e ? (Array.isArray(e.running) ? e.running.length : 0) : 0;
} catch { return null; }
}
async function restartAgent(name, thread) {
const org = window.MosaicOrg?.id ?? null;
const r = restarts[name] = { busy: true, text: `Terminating ${name}…` };
const paint = () => paintRestart(name, org);
const stop = text => { r.busy = false; r.text = text; paint(); };
paint();
const asked = await send(pin(org, '/api/agent/terminate'), { instance: name, reason: 'route change' });
if (asked.signedOut) return stop('Sign in again, then retry.');
if (asked.unknown || !asked.ok || !REQUEST_ID.test(asked.result?.request ?? '')) return stop(asked.ok || asked.unknown ? UNKNOWN : refused(asked.result));
// SP19 (#1873): the agent drawer's Restart runs this same chain. `org` is the agent's own organization
// (on #/agents the page has none), `reason` goes with the terminate, `text(step, detail)` may give the
// words for a step (nothing keeps the route-change words below), and `onStatus({ step, busy, text })`
// takes each line in place of the Routing receipt's button. The chain never regenerates.
async function restartAgent(name, thread, { org = window.MosaicOrg?.id ?? null, reason = 'route change', text, onStatus } = {}) {
const r = { busy: true, text: '' };
if (!onStatus) restarts[name] = r;
const paint = step => onStatus ? onStatus({ step, busy: r.busy, text: r.text }) : paintRestart(name, org);
const words = (step, detail, own) => (typeof text === 'function' ? text(step, detail) : undefined) ?? own;
const say = (step, detail, own) => { r.text = words(step, detail, own); paint(step); };
const stop = (step, detail, own) => { r.busy = false; say(step, detail, own); };
say('ending', {}, `Terminating ${name}…`);
const asked = await send(pin(org, '/api/agent/terminate'), { instance: name, reason });
if (asked.signedOut) return stop('signedOut', {}, 'Sign in again, then retry.');
if (asked.unknown || !asked.ok || !REQUEST_ID.test(asked.result?.request ?? '')) return asked.ok || asked.unknown ? stop('endUnknown', {}, UNKNOWN) : stop('endRefused', { status: asked.status, result: asked.result }, refused(asked.result));
const ended = await closing(asked.result.request, org);
if (ended.stop) return stop(ended.stop);
if (ended.done.reason) return stop(`${name}: ${ended.done.reason}. It was not restarted.`);
r.text = `Terminated ${name}. Waiting for its session to end…`; paint();
if (ended.stop) return stop('endOpen', { stop: ended.stop }, ended.stop);
if (ended.done.reason) return stop('endClosed', { reason: ended.done.reason }, `${name}: ${ended.done.reason}. It was not restarted.`);
say('ended', {}, `Terminated ${name}. Waiting for its session to end…`);
let left = false;
for (let i = 0; i < RESTART_WAIT && !left; i++) { await new Promise(res => setTimeout(res, POLL_MS)); left = (await runs(name, org)) === 0; }
if (!left) return stop(`${name} was asked to end but its session is still running. Launch it from Agents once it has ended.`);
if (thread) return stop(`Terminated ${name} at ${new Date().toLocaleTimeString()}. Its next message starts it on the new route.`);
r.text = `Launching ${name}…`; paint();
if (!left) return stop('stillRunning', {}, `${name} was asked to end but its session is still running. Launch it from Agents once it has ended.`);
const time = new Date().toLocaleTimeString();
if (thread) return stop('threadEnded', { time }, `Terminated ${name} at ${time}. Its next message starts it on the new route.`);
say('launching', {}, `Launching ${name}…`);
const launch = await send(pin(org, '/api/agent/launch'), { instance: name });
if (launch.signedOut) return stop('Sign in again. It was terminated and not launched.');
if (launch.unknown || !launch.ok || !REQUEST_ID.test(launch.result?.request ?? '')) return stop(launch.ok || launch.unknown ? `${UNKNOWN} It was terminated.` : `${refused(launch.result)} It was terminated and not launched.`);
if (launch.signedOut) return stop('launchSignedOut', {}, 'Sign in again. It was terminated and not launched.');
if (launch.unknown || !launch.ok || !REQUEST_ID.test(launch.result?.request ?? '')) return launch.ok || launch.unknown ? stop('launchUnknown', {}, `${UNKNOWN} It was terminated.`) : stop('launchRefused', { status: launch.status, result: launch.result }, `${refused(launch.result)} It was terminated and not launched.`);
const started = await closing(launch.result.request, org);
if (started.stop) return stop(started.stop);
if (started.done.reason) return stop(`${name}: ${started.done.reason}. It was terminated and not launched.`);
return stop(`Restarted ${name} on the new route${started.done.done?.run ? ` (run ${started.done.done.run})` : ''}.`);
if (started.stop) return stop('launchOpen', { stop: started.stop }, started.stop);
if (started.done.reason) return stop('launchClosed', { reason: started.done.reason }, `${name}: ${started.done.reason}. It was terminated and not launched.`);
const run = started.done.done?.run ?? null;
return stop('restarted', { run }, `Restarted ${name} on the new route${run ? ` (run ${run})` : ''}.`);
}
document.addEventListener('click', e => {
const b = e.target.closest?.('[data-agent-restart]');
@@ -247,7 +255,7 @@
restartAgent(b.dataset.agentRestart, b.dataset.agentThread === 'yes');
});
window.MosaicAgents = Object.freeze({ section, restartMarkup, isThread: definition => threadDefinitions.has(definition) });
window.MosaicAgents = Object.freeze({ section, restartMarkup, restart: restartAgent, isThread: definition => threadDefinitions.has(definition) });
})();
/* #1873 A2: Settings > Agents, the root and project agent levels. bus.js awaits section() for the
+112 -23
View File
@@ -1118,8 +1118,16 @@
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
// request is open, then the result in words beside the button.
let stopState = null; // { id, confirm, busy, text }
// 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 }
// 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 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
// entry marked in history.state; switching rows replaces it. Close goes Back only from that marked
@@ -1132,11 +1140,16 @@
const sansAgent = () => { const n = queryOf(); n.delete('agent'); const s = n.toString(); return `${/^#\/orgs\/[^/?]+/.exec(location.hash)?.[0] ?? '#'}${pathOf()}${s ? `?${s}` : ''}`; };
// The row's name as a link that opens the drawer: a native link, so Tab reaches it and Enter opens it.
const drawerLink = (q, a) => `<a class="ws-drawer-open" href="${esc(drawerHref(q, `${a.org}:${a.key}`))}" data-ws-drawer-open="${esc(`${a.org}:${a.key}`)}" data-focus-key="${esc(`agent:${a.org}:${a.key}`)}">${esc(a.name)}</a>`;
const stopConfirm = (name, who) => `<span class="ws-drawer-confirm" data-drawer-stop-confirm>Stop ${esc(who)}? <button type="button" class="ws-btn danger" data-drawer-stop-yes data-focus-key="drawer-stop-yes">Stop ${esc(name)}</button> <button type="button" class="ws-btn" data-drawer-stop-no data-focus-key="drawer-stop-no">Cancel</button></span>`;
function stopActions(pick, a, orgName) {
const st = stopState?.id === pick.id ? stopState : null;
const who = `${a.name} in ${orgName}`;
return `<button type="button" class="ws-btn" data-drawer-stop data-focus-key="drawer-stop"${st?.busy || st?.confirm ? ' disabled' : ''}>${st?.busy ? 'Stopping…' : 'Stop'}<span class="ws-sr"> ${esc(who)}</span></button>${st?.confirm ? stopConfirm(a.name, who) : ''}`;
// SP19: Stop and Restart ask in the same confirm step, each under its own data attributes.
const actConfirm = (kind, name, question) => `<span class="ws-drawer-confirm" data-drawer-${kind}-confirm>${esc(question)} <button type="button" class="ws-btn danger" data-drawer-${kind}-yes data-focus-key="drawer-${kind}-yes">${kind === 'stop' ? 'Stop' : 'Restart'} ${esc(name)}</button> <button type="button" class="ws-btn" data-drawer-${kind}-no data-focus-key="drawer-${kind}-no">Cancel</button></span>`;
const stopConfirm = (name, who) => actConfirm('stop', name, `Stop ${who}?`);
const restartConfirm = (name, who, thread) => actConfirm('restart', name, `Restart ${who}? ${thread ? 'It ends its session; its next message starts it again.' : 'It ends its session and launches it again.'}`);
function stopActions(pick, a, orgName, thread) {
const st = actState(pick.id), kind = st?.kind || 'stop';
const who = `${a.name} in ${orgName}`, hold = st?.busy || st?.confirm ? ' disabled' : '';
const stop = `<button type="button" class="ws-btn" data-drawer-stop data-focus-key="drawer-stop"${hold}>${st?.busy && kind === 'stop' ? 'Stopping…' : 'Stop'}<span class="ws-sr"> ${esc(who)}</span></button>${st?.confirm && kind === 'stop' ? stopConfirm(a.name, who) : ''}`;
if (!window.MosaicAgents?.restart) return stop;
return `${stop} <button type="button" class="ws-btn" data-drawer-restart data-drawer-thread="${thread ? 'yes' : 'no'}" data-focus-key="drawer-restart"${hold}>${st?.busy && kind === 'restart' ? 'Restarting…' : 'Restart'}<span class="ws-sr"> ${esc(who)}</span></button>${st?.confirm && kind === 'restart' ? restartConfirm(a.name, who, thread) : ''}`;
}
// SP13 (#1873): the drawer's instances read gives the agent's state. The drawer does not hold the
// page for it: once the page's own reads have answered (`opts.page`), a drawer whose instances read
@@ -1335,7 +1348,8 @@
: a.level !== 'org' ? 'No Message: a copy is not messaged from here.'
: 'No Message: this Console messages only conversation agents, such as the Assistant.'}</p>`);
else if (change) acts.push(`<p class="note" data-drawer-nomessage>No Message: this Console does not send chat in ${esc(orgName)}.</p>`);
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 || 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(`<p class="note" data-drawer-nostop>${reading ? 'Its state is being read. Stop is offered once it is read and the agent is running.'
@@ -1343,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.'}</p>`);
const st = stopState?.id === id ? stopState : null;
const st = actState(id);
const actions = chat || change
? `<div class="ws-drawer-acts" data-drawer-actions>${acts.join(' ')}<p class="ws-drawer-status" id="ws-drawer-status" role="status" data-drawer-status>${esc(st?.text || '')}</p></div>`
: `<p class="note" data-drawer-readonly>This Console only reads ${esc(orgName)}. It can not message or stop its agents.</p>`;
@@ -1383,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'));
@@ -1420,7 +1435,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 +1463,72 @@
}
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 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;
};
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 (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)}"]`), 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 = 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 }) => {
restarts.set(id, { busy: !!busy, text });
paint();
if (!busy) done(step);
};
try { await window.MosaicAgents.restart(name, thread, { org, reason: RESTART_REASON, text: restartWords(name, orgName), onStatus }); }
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]');
if (link) {
@@ -1466,33 +1547,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) || !!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);
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 ----
@@ -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,192 @@ 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 === 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
// 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);
});
// 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' } }],
/^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: ${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()`);
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);
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, launched ? 1 : 0);
assert.equal(await b.evaluate('window.__answers.length'), 0, 'every queued answer was asked for');
});
+3 -2
View File
@@ -218,8 +218,9 @@ test('row 194 N5: agents.js is served as JavaScript and index.html loads it once
const s = await setup(t);
const js = await get(s, '/agents.js');
assert.equal(js.status, 200); assert.match(js.type, /^text\/javascript/);
// F3 adds the agent restart receipt and the thread test that Settings > Routing uses.
assert.match(js.text, /window\.MosaicAgents = Object\.freeze\(\{ section, restartMarkup, isThread: definition => threadDefinitions\.has\(definition\) \}\)/);
// F3 adds the agent restart receipt and the thread test that Settings > Routing uses; SP19 the
// restart chain the agent drawer calls.
assert.match(js.text, /window\.MosaicAgents = Object\.freeze\(\{ section, restartMarkup, restart: restartAgent, isThread: definition => threadDefinitions\.has\(definition\) \}\)/);
assert.match(js.text, /Agent actions are unavailable here\. Use mosaic org instance from the instance CLI\./);
const html = await get(s, '/');
assert.equal(html.text.match(/<script src="\/agents\.js" defer><\/script>/g)?.length, 1);
@@ -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);
});