From 05be6c62bd39f054cc57fb4ba90b3f7488f7a027 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Wed, 18 Nov 2026 12:35:27 -0600 Subject: [PATCH] feat(webui): Restart in the agent drawer: beside Stop and only where Stop is offered, in Stop's confirm step and status line, it ends the agent through its own organization's /agent/terminate with the reason restart from the agent drawer, waits for the request to close and its runs to reach 0, then launches it through /agent/launch; a conversation agent is ended and not launched; it never regenerates; not owner, bus stopped, end refused, launch refused and runs never reaching 0 each say so in one line and leave the buttons usable; a second click while it runs does nothing. The agents.js restart chain takes org, reason, a text callback and a status callback; the Routing receipt's Restart now keeps its reason and words, pinned by two new tests (#1873, lane sp19-drawer-restart) --- packages/webui/src/public/agents.js | 52 +++--- packages/webui/src/public/workspace.js | 119 +++++++++++--- .../webui/tests/agent-drawer-browser.test.mjs | 150 ++++++++++++++++++ .../webui/tests/routes-apply-browser.test.mjs | 36 ++++- 4 files changed, 311 insertions(+), 46 deletions(-) diff --git a/packages/webui/src/public/agents.js b/packages/webui/src/public/agents.js index b7e5fae37..4734dda6d 100644 --- a/packages/webui/src/public/agents.js +++ b/packages/webui/src/public/agents.js @@ -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 diff --git a/packages/webui/src/public/workspace.js b/packages/webui/src/public/workspace.js index 32e993088..099556133 100644 --- a/packages/webui/src/public/workspace.js +++ b/packages/webui/src/public/workspace.js @@ -1118,8 +1118,12 @@ 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 holds it (no kind is Stop). While either asks or runs, both buttons wait. + let stopState = null; // { id, kind, confirm, busy, text } + // SP19: the drawer agents with a restart running, so a second click on any drawer starts nothing. + const restarting = new Set(); + 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 +1136,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) => `${esc(a.name)}`; - const stopConfirm = (name, who) => `Stop ${esc(who)}? `; - function stopActions(pick, a, orgName) { - const st = stopState?.id === pick.id ? stopState : null; - const who = `${a.name} in ${orgName}`; - return `${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) => `${esc(question)} `; + 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 = stopState?.id === pick.id ? stopState : null, kind = st?.kind || 'stop'; + const who = `${a.name} in ${orgName}`, hold = st?.busy || st?.confirm ? ' disabled' : ''; + const stop = `${st?.confirm && kind === 'stop' ? stopConfirm(a.name, who) : ''}`; + if (!window.MosaicAgents?.restart) return stop; + return `${stop} ${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 +1344,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.'}

`); else if (change) acts.push(`

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); +});