Files
stack/packages/webui/src/public/proxy.js
T
jason.woltje 1b6cac2bdf feat(webui): restart the Console, the org bus and agents from the WebUI (F3)
Self-service operation from the WebUI, for a dev instance first.

- Settings > Console > Restart Console. A foreground `mosaic console
  start` now supervises the webui: the child exits 75 after answering a
  restart and the supervisor relaunches it with the same argv. Org buses
  keep running. /api/config carries a per-process boot id, so the open
  page polls until a new process answers and then reloads. A detached
  Console has no supervisor and answers 409.
- Restart bus on every "Restart needed" receipt and on the bus-down
  banner: POST /api/orgs/<id>/restart/bus restarts a running bus or
  starts a stopped one, then shows a done receipt with the time.
- Settings > Routing: after a save, the page lists how the change
  reaches each agent (next start, session end, thread idle) and offers
  "Restart <agent> now" for a running one. A session is terminated with
  the reason "route change" and launched again; a thread is terminated.
- Organization settings: the signed-in owner's settings, routing,
  agent, plug-in and Model proxy writes now reach the selected org's
  bus instead of answering 403. Org mode exists only under
  --dev-local-owner. Proxy setup stays a terminal step; a dev-only note
  names the two commands.

Every control needs the signed-in owner session, the page's exact
Origin and Sec-Fetch-Site: same-origin. The tester listener, granted
users, API tokens, agents and bus roles are refused before any work.
Each use is written to <dataRoot>/console/actions.jsonl (0600, no
symlinks) with who, when, what and the outcome. The Console and bus
restart trails fail closed. No change to credential handling, the
broker, the bus tenant boundary or v2 schemas.
2026-11-09 13:37:28 -06:00

109 lines
6.7 KiB
JavaScript

// P4 page: credentials and OAuth state exist only during the current operation.
// No browser storage, request/body logging, key reveal, or automatic write retry.
(() => {
'use strict';
const $ = id => document.getElementById(id);
let canWrite = false, login = null, poll = null, busy = false;
const message = (text, loginOnly = false) => { $(loginOnly ? 'proxy-login-message' : 'proxy-message').textContent = text; };
const cell = value => { const td = document.createElement('td'); td.textContent = value ?? '—'; return td; };
async function call(path, args) {
const response = await fetch('/api/proxy/' + path, { cache: 'no-store', credentials: 'same-origin',
method: args === undefined ? 'GET' : 'POST',
...(args === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(args) }),
});
const value = await response.json();
if (!response.ok) {
if (response.status === 401) throw new Error('Sign in to the Console again.');
if (value.error === 'not-configured') throw new Error('The model proxy is not configured for this instance.');
if (value.error === 'login-state-unknown') throw new Error('This sign-in has ended. Start a new sign-in.');
if (value.error === 'apikey-invalid') throw new Error('Enter a nonempty API key, with no spaces or line breaks.');
throw new Error('The operation could not be confirmed. Nothing was retried. Refresh before trying again.');
}
return value;
}
function endLogin() {
clearTimeout(poll); poll = null; login = null;
$('proxy-authorize').removeAttribute('href'); $('proxy-authorize').hidden = true;
$('proxy-login-submit').elements.redirect_url.value = '';
}
async function status() {
if (!login) return;
const active = login;
try {
const result = await call('login/status', { state: active.state });
if (active !== login) return;
if (result.status === 'wait') { message('Waiting for account sign-in…', true); poll = setTimeout(status, 2000); return; }
endLogin();
if (result.status === 'ok') { message('Account signed in.', true); await refresh(); }
else message(result.reason === 'login-timeout' ? 'Sign-in timed out. Start again.' : 'Account sign-in failed. Start again.', true);
} catch (error) { if (active === login) { endLogin(); message(error.message, true); } }
}
async function refresh() {
const [accounts, keys] = await Promise.all([call('accounts'), call('keys')]);
const rows = accounts.accounts.map(account => {
const row = document.createElement('tr');
row.append(cell(account.displayName), cell(account.provider), cell(account.status));
const td = document.createElement('td'), form = document.createElement('form');
const input = document.createElement('input'); input.type = 'number'; input.min = '-1000'; input.max = '1000'; input.step = '1'; input.value = account.priority;
input.setAttribute('aria-label', `Priority for ${account.displayName}`); input.disabled = !canWrite;
const save = document.createElement('button'); save.type = 'submit'; save.textContent = 'Set priority'; save.disabled = !canWrite;
form.append(input, save); form.addEventListener('submit', async event => {
event.preventDefault(); if (!canWrite || busy || !input.checkValidity()) return;
busy = true; save.disabled = true;
try { await call('priority/set', { accountId: account.accountId, priority: Number(input.value) }); message('Priority saved.'); await refresh(); }
catch (error) { message(error.message); }
finally { busy = false; save.disabled = !canWrite; }
});
td.append(form); row.append(td); return row;
});
$('proxy-accounts').replaceChildren(...rows);
if (!rows.length) { const row = document.createElement('tr'); const td = cell('No accounts configured.'); td.colSpan = 4; row.append(td); $('proxy-accounts').append(row); }
$('proxy-keys').replaceChildren(...keys.keys.map(key => {
const row = document.createElement('tr'); row.append(cell(key.keyId), cell(key.management), cell(key.agent), cell(key.issuedAt), cell(key.state)); return row;
}));
}
$('proxy-refresh').addEventListener('click', () => refresh().then(() => message('Accounts and client keys refreshed.')).catch(e => message(e.message)));
$('proxy-login-start').addEventListener('submit', async event => {
event.preventDefault(); if (!canWrite || busy || login) return;
busy = true;
try {
login = await call('login/start', { provider: event.currentTarget.elements.provider.value });
$('proxy-authorize').href = login.url; $('proxy-authorize').hidden = false;
window.open(login.url, '_blank', 'noopener,noreferrer');
message('Complete account sign-in in the new tab, or use the sign-in link.', true);
poll = setTimeout(status, 2000);
} catch (error) { message(error.message, true); }
finally { busy = false; }
});
$('proxy-login-submit').addEventListener('submit', async event => {
event.preventDefault(); if (!canWrite || busy || !login) return;
const input = event.currentTarget.elements.redirect_url, redirect_url = input.value; input.value = '';
busy = true;
try { await call('login/submit', { redirect_url }); message('Address submitted. Waiting for sign-in confirmation…', true); }
catch (error) { message(error.message, true); }
finally { busy = false; }
});
$('proxy-login-cancel').addEventListener('click', async () => {
if (!canWrite || busy || !login) return;
busy = true; clearTimeout(poll);
try { await call('login/cancel', { state: login.state }); endLogin(); message('Sign-in cancelled.', true); }
catch (error) { endLogin(); message(error.message, true); }
finally { busy = false; }
});
$('proxy-apikey').addEventListener('submit', async event => {
event.preventDefault(); if (!canWrite || busy) return;
const input = event.currentTarget.elements.key, key = input.value; input.value = '';
busy = true;
try { await call('apikey/add', { provider: 'z.ai', key }); message('API key added.'); await refresh(); }
catch (error) { message(error.message); }
finally { busy = false; }
});
window.addEventListener('pagehide', () => { endLogin(); $('proxy-apikey').elements.key.value = ''; });
fetch('/api/config', { cache: 'no-store' }).then(r => r.json()).then(config => {
canWrite = (config.send === true || config.settingsSend === true) && config.tester !== true && config.user !== true;
document.querySelectorAll('[data-write]').forEach(fieldset => { fieldset.disabled = !canWrite; });
$('proxy-readonly').hidden = canWrite;
return refresh();
}).then(() => message('Accounts and client keys loaded.')).catch(error => message(error.message));
})();