Compare commits

..
Author SHA1 Message Date
jason.woltje 29daa4c4bf test(webui): settings-backend-a3 proof: the settings-review fixture's accounts answer carries the providers list, since with no list the Model setup page shows no sign-in button (F10 clicked it) (#1873, lane settings-backend-a3) 2026-11-20 02:21:46 -06:00
jason.woltje c8db3665cf fix(bus): settings-backend-a3 review: a provider list entry counts only with what its door needs, a sign-in host or a key base URL, so one missing it is refused provider-not-allowed before any proxy call (no sign-in opened at the proxy that the page cannot cancel), and a key group with no base URL is no provider's (P3-1) (#1873, lane settings-backend-a3) 2026-11-20 02:21:46 -06:00
jason.woltje f2c262cf40 feat(model-proxy,bus,webui): settings-backend A3: the provider list comes from the cliproxy plugin's PROVIDERS (id, label, sign-in kind, the sign-in host for a subscription, the base URL for the key provider); the management client's oauthStart, the bus proxy page's names, login allow list, sign-in host check and key allow list read it, with the same refusals (proxy-client-invalid, provider-not-allowed); the setup status and the accounts answer carry providers as id, label and sign-in kind only; the Model setup page builds the provider select and its help text from them, and with no list, an empty one or a failed read it shows no select and says the providers could not be read; an architecture test holds that no provider id, sign-in host or key base URL is written out in client.mjs, proxy-page.mjs or display.js (#1873, lane settings-backend-a3) 2026-11-20 02:21:45 -06:00
jason.woltje ebfbdb13a0 fix(webui): settings-s5c recheck: the status load says whether it painted the answer, and the result after an off says the list above is read again only then; a status read that answers 200 with null, an empty object or a page that is not JSON now says the list may be out of date, with Read again, instead of claiming the list is new (recheck P3); tests red on c47f9a3bd (#1873, lane settings-s5c) 2026-11-20 02:10:52 -06:00
jason.woltje 4d378fc38b fix(webui): settings-s5c review: an open Turn off question goes when a status read no longer lists that program or cannot list programs, so the buttons are not left disabled (P3-1); a refusal code named like an object property (constructor) shows as its code with the plain refused words, in failText and in the shared explain(), never as page source (P3-2); after an off the result says the list above was read again only when that read worked; when it failed it says the list may be out of date and gives Read again, which reads it and moves focus to the result (P3-3); invalid-request on an off says the program is not in the Console's installed list or that list could not be read (P3-4); the programs box keeps its own spacing inside the settings form (P3-5); tests red without each change (#1873, lane settings-s5c) 2026-11-20 02:10:52 -06:00
jason.woltje ab8633ede8 feat(webui): settings-s5c: Model setup, Advanced, lists the installed programs from the status read and which organizations have each one on, by display name, an organization whose list is null reading Not known in it, never off; Turn off for every organization asks first, naming the program, then POSTs programs/off, words each organization's outcome (bus-down never says stopped, failed:outcome-unknown says it may have changed, an unknown failed code shows the code unless it is shaped like a key), gives busy and a failed request a plain line, reads the status again and moves focus to the result; Technical details reads access health per organization when it opens: Ready only for ok with every key active and no reason, attention, unreadable, a missing or unknown health never Ready, no key id, agent or other count shown, a failed read with Read again; none of it shows or is read for a viewer who is not the instance owner; the old per-instance program read on Advanced is gone (#1873, lane settings-s5c) 2026-11-20 02:10:52 -06:00
16 changed files with 1113 additions and 67 deletions

No files matched your search

+27 -19
View File
@@ -3,7 +3,7 @@ import { randomBytes } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import { sha256, refuse } from '../../model-proxy/src/common.mjs';
import { PROXY_PAGE_CODES } from './proxy-page-vocabulary.mjs';
import { ZAI_URL, MODEL_ID } from '../../plugins/model-provider/cliproxy/index.mjs';
import { MODEL_ID, PROVIDERS, publicProviders } from '../../plugins/model-provider/cliproxy/index.mjs';
export { PROXY_PAGE_VERBS, PROXY_PAGE_CODES } from './proxy-page-vocabulary.mjs';
const object = x => x !== null && typeof x === 'object' && !Array.isArray(x);
function fields(args, names) {
@@ -13,11 +13,16 @@ const priorityOk = n => Number.isInteger(n) && n >= -1000 && n <= 1000;
const identifier = x => typeof x === 'string' && x.length > 0 && x.length <= 512;
const stateOk = x => typeof x === 'string' && /^[a-zA-Z0-9_-]{1,512}$/.test(x);
const keyId = value => sha256(value).slice(0, 12);
const providerName = provider => ({ claude: 'Claude', codex: 'Codex', 'z.ai': 'z.ai', other: 'Other' })[provider];
// #1873 settings-backend-a3: provider names, the login allow list and the key allow list all come
// from the plugin's PROVIDERS. An account the list does not name reads Other.
// An entry counts only with what its door needs: a sign-in host, or a key base URL.
const usable = p => p.signIn === 'oauth' ? typeof p.signInHost === 'string' : p.signIn === 'apikey' && typeof p.baseUrl === 'string';
const listed = (providers, id, signIn) => providers.find(p => p.id === id && p.signIn === signIn && usable(p)) ?? null;
const providerName = (providers, provider) => providers.find(p => p.id === provider)?.label ?? 'Other';
// Credential labels/emails and group names are arbitrary upstream strings. A stable
// generated display name provides identification without reflecting a misplaced token.
function view(id, provider, status, priority) {
return { accountId: keyId(id), provider, displayName: `${providerName(provider)} account ${keyId(id)}`,
function view(providers, id, provider, status, priority) {
return { accountId: keyId(id), provider, displayName: `${providerName(providers, provider)} account ${keyId(id)}`,
status, priority: priorityOk(priority) ? priority : 0 };
}
// #1873 chat-fail F3: one plain line under an account the proxy reports as not working, with
@@ -57,11 +62,12 @@ function accountReason(row, now) {
return NO_REASON;
}
export class ProxyPage {
#client; #tag; #records; #lock; #org; #dirty = false; #now; #timeout; #onChange; #pending = new Map(); #writes = Promise.resolve();
constructor({ client, instanceTag, keyRecords = () => [], now = Date.now, loginTimeoutSeconds = 300, onChange = () => {}, lock = null, org = null }) {
#client; #tag; #records; #lock; #org; #dirty = false; #now; #timeout; #onChange; #providers; #pending = new Map(); #writes = Promise.resolve();
// providers: the plugin's PROVIDERS; a test passes a copy with one taken out.
constructor({ client, instanceTag, keyRecords = () => [], now = Date.now, loginTimeoutSeconds = 300, onChange = () => {}, lock = null, org = null, providers = PROVIDERS }) {
if (!client || !/^[a-zA-Z0-9_-]{1,64}$/.test(instanceTag) || typeof keyRecords !== 'function' || typeof now !== 'function'
|| typeof onChange !== 'function' || !Number.isSafeInteger(loginTimeoutSeconds) || loginTimeoutSeconds <= 0) throw new TypeError('invalid proxy page settings');
this.#lock = lock; this.#org = org;
|| typeof onChange !== 'function' || !Number.isSafeInteger(loginTimeoutSeconds) || loginTimeoutSeconds <= 0 || !Array.isArray(providers)) throw new TypeError('invalid proxy page settings');
this.#lock = lock; this.#org = org; this.#providers = providers;
this.#client = client; this.#tag = instanceTag; this.#records = keyRecords; this.#now = now; this.#timeout = loginTimeoutSeconds * 1000; this.#onChange = onChange;
}
// Serializes read-modify-write provider config within the bus. P2 owns the
@@ -84,10 +90,10 @@ export class ProxyPage {
const rows = [];
for (const row of response.files) {
if (!identifier(row?.id) || !identifier(row?.name)) continue;
const provider = ['claude', 'codex'].includes(row.provider) ? row.provider : 'other';
const provider = listed(this.#providers, row.provider, 'oauth') ? row.provider : 'other';
const status = row.disabled === true ? 'disabled' : row.unavailable === true ? 'unavailable'
: ['ready', 'active', 'error', 'disabled', 'unavailable'].includes(row.status) ? row.status : 'unknown';
rows.push({ ...view(row.id, provider, status, row.priority), source: 'oauth', name: row.name,
rows.push({ ...view(this.#providers, row.id, provider, status, row.priority), source: 'oauth', name: row.name,
...(['unavailable', 'error'].includes(status) ? { reason: accountReason(row, this.#now()) } : {}) });
}
for (const [groupIndex, group] of groups.entries()) {
@@ -95,18 +101,18 @@ export class ProxyPage {
for (const [keyIndex, key] of group.keys.entries()) {
// auth_index is generated by the proxy. Never fall back to hashing api-key.
if (!identifier(key?.auth_index)) continue;
const provider = group['base-url'] === ZAI_URL ? 'z.ai' : 'other';
const provider = this.#providers.find(p => p.signIn === 'apikey' && usable(p) && p.baseUrl === group['base-url'])?.id ?? 'other';
const status = key.disabled === true || group.disabled === true ? 'disabled' : 'active';
const configured = group.models ?? [];
if (!Array.isArray(configured) || configured.length > 32 || configured.some(m => !m || typeof (m.alias || m.name) !== 'string' || !MODEL_ID.test(m.alias || m.name))) refuse('proxy-down');
rows.push({ ...view(key.auth_index, provider, status, key.priority ?? group.priority), source: 'apikey', groupIndex, keyIndex, models: configured.map(m => m.alias || m.name) });
rows.push({ ...view(this.#providers, key.auth_index, provider, status, key.priority ?? group.priority), source: 'apikey', groupIndex, keyIndex, models: configured.map(m => m.alias || m.name) });
}
}
return { rows, groups };
}
#public(row) {
const { accountId, provider, displayName, status, priority } = row;
return { accountId, provider, displayName, status, priority, ...(row.source === 'apikey' && provider === 'z.ai' ? { models: row.models } : {}),
return { accountId, provider, displayName, status, priority, ...(row.source === 'apikey' && listed(this.#providers, provider, 'apikey') ? { models: row.models } : {}),
...(typeof row.reason === 'string' ? { reason: row.reason } : {}) };
}
#session(state, scope, { reportTimeout = false } = {}) {
@@ -131,17 +137,18 @@ export class ProxyPage {
async #request(verb, args, scope) {
if (verb === 'proxy.accounts') {
fields(args, []);
return { accounts: (await this.#accounts()).rows.map(row => this.#public(row)) };
// The provider list rides along for the page's select: id, label and sign-in kind only.
return { accounts: (await this.#accounts()).rows.map(row => this.#public(row)), providers: publicProviders(this.#providers) };
}
if (verb === 'proxy.login.start') {
fields(args, ['provider']);
if (!['claude', 'codex'].includes(args.provider)) refuse('provider-not-allowed');
const oauth = listed(this.#providers, args.provider, 'oauth');
if (!oauth) refuse('provider-not-allowed');
for (const [state, value] of this.#pending) if (value.expires <= this.#now()) this.#pending.delete(state);
if (this.#pending.size >= 128) refuse('proxy-down');
const answer = await (this.#lock ? this.#write(() => this.#client.oauthStart(args.provider)) : this.#client.oauthStart(args.provider));
let url; try { url = new URL(answer.url); } catch { refuse('proxy-down'); }
const host = args.provider === 'claude' ? 'claude.ai' : 'auth.openai.com';
if (url.protocol !== 'https:' || url.hostname !== host || url.username || url.password || url.port
if (url.protocol !== 'https:' || typeof oauth.signInHost !== 'string' || url.hostname !== oauth.signInHost || url.username || url.password || url.port
|| url.href.length > 8192 || !stateOk(answer.state) || url.searchParams.getAll('state').length !== 1
|| url.searchParams.get('state') !== answer.state || this.#pending.has(answer.state)) refuse('proxy-down');
this.#pending.set(answer.state, { business: scope.business, human: scope.human, expires: this.#now() + this.#timeout });
@@ -186,12 +193,13 @@ export class ProxyPage {
}
if (verb === 'proxy.apikey.add') {
fields(args, ['provider', 'key']);
if (args.provider !== 'z.ai') refuse('provider-not-allowed');
const keyed = listed(this.#providers, args.provider, 'apikey');
if (!keyed) refuse('provider-not-allowed');
if (typeof args.key !== 'string' || !/^[\x21-\x7e]{1,4096}$/.test(args.key)) refuse('apikey-invalid');
return this.#write(async () => {
const groups = await this.#client.getUpstreamGroups();
if (!Array.isArray(groups)) refuse('proxy-down');
const group = { name: `mosaic-zai-${randomBytes(6).toString('hex')}`, 'base-url': ZAI_URL,
const group = { name: `mosaic-${keyed.id.replace(/[^a-z0-9]/g, '')}-${randomBytes(6).toString('hex')}`, 'base-url': keyed.baseUrl,
priority: 0, keys: [{ 'api-key': args.key }] };
if (this.#lock && !isDeepStrictEqual(await this.#client.getUpstreamGroups(), groups)) refuse('proxy-down');
this.#beforeMutation('proxy.apikey.add');
@@ -4,6 +4,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { fakeManagement } from './proxy-page-fixture.mjs';
import { PROVIDERS } from '../../plugins/model-provider/cliproxy/index.mjs';
const id = value => createHash('sha256').update(value).digest('hex').slice(0, 12);
const oauth = extra => ({ id: 'oauth-one.json', name: 'oauth-one.json', provider: 'claude', label: 'p4-private-label',
email: 'p4-private-email', token: 'p4-private-token', status: 'ready', priority: 3, ...extra });
@@ -11,7 +12,9 @@ test('accounts have exactly the allowlisted public fields, id from credential id
const s = await fakeManagement(t, { files: [oauth()] });
const result = await s.call('proxy.accounts');
assert.deepEqual(result, { accounts: [{ accountId: id('oauth-one.json'), provider: 'claude',
displayName: `Claude account ${id('oauth-one.json')}`, status: 'ready', priority: 3 }] });
displayName: `Claude account ${id('oauth-one.json')}`, status: 'ready', priority: 3 }],
// settings-backend-a3: the provider list rides along, id, label and sign-in kind only.
providers: PROVIDERS.map(({ id, label, signIn }) => ({ id, label, signIn })) });
for (const value of ['p4-private-label', 'p4-private-email', 'p4-private-token']) {
assert.equal(JSON.stringify(result).includes(value), false);
assert.notEqual(result.accounts[0].accountId, id(value));
@@ -0,0 +1,106 @@
// #1873 settings-backend-a3: the proxy page's provider names, login allow list, sign-in host and key
// allow list all come from the plugin's PROVIDERS. A provider a test copy of the list leaves out is
// refused at each door with the same code as before; one a copy adds is let through. The accounts
// answer carries the list as id, label and sign-in kind only.
import test from 'node:test';
import assert from 'node:assert/strict';
import { ProxyPage } from '../src/proxy-page.mjs';
import { PROVIDERS } from '../../plugins/model-provider/cliproxy/index.mjs';
const owner = { business: 'demo', human: 'owner' };
function setup(options = {}) {
const calls = [], state = { files: [], groups: [] };
const client = Object.fromEntries(['getCredentials', 'oauthStart', 'oauthCallback', 'oauthStatus', 'oauthCancel', 'getUpstreamGroups', 'putUpstreamGroups'].map(name => [name, async (...args) => {
calls.push([name, ...args]);
if (name === 'oauthStart') return { status: 'ok', state: `s-${calls.length}`, url: `https://${options.hosts?.[args[0]] ?? 'nowhere.invalid'}/oauth/authorize?state=s-${calls.length}` };
if (name === 'getCredentials') return { files: state.files };
if (name === 'getUpstreamGroups') return structuredClone(state.groups);
if (name === 'putUpstreamGroups') { state.groups = args[0].map((g, i) => ({ ...g, keys: g.keys.map((k, j) => ({ ...k, auth_index: `idx-${i}-${j}` })) })); return { status: 'ok' }; }
return { status: 'ok' };
}]));
const p = new ProxyPage({ client, instanceTag: 'fixture', ...(options.providers ? { providers: options.providers } : {}) });
return { calls, state, call: (verb, args = {}) => p.request(verb, args, owner) };
}
const hosts = Object.fromEntries(PROVIDERS.filter(p => p.signIn === 'oauth').map(p => [p.id, p.signInHost]));
const door = p => p.signIn === 'oauth' ? ['proxy.login.start', { provider: p.id }] : ['proxy.apikey.add', { provider: p.id, key: 'fixture-key' }];
const otherDoor = p => p.signIn === 'oauth' ? ['proxy.apikey.add', { provider: p.id, key: 'fixture-key' }] : ['proxy.login.start', { provider: p.id }];
test('a3: each provider in PROVIDERS passes its own door and is refused at the other with provider-not-allowed', async () => {
assert.ok(PROVIDERS.some(p => p.signIn === 'oauth') && PROVIDERS.some(p => p.signIn === 'apikey'));
for (const p of PROVIDERS) {
const s = setup({ hosts });
const answer = await s.call(...door(p));
if (p.signIn === 'oauth') assert.equal(new URL(answer.url).hostname, p.signInHost, p.id);
else { assert.deepEqual(answer, { added: true }); assert.equal(s.state.groups.at(-1)['base-url'], p.baseUrl); }
const before = s.calls.length;
await assert.rejects(s.call(...otherDoor(p)), { code: 'provider-not-allowed' }, p.id);
assert.equal(s.calls.length, before, `${p.id}: a refusal reaches no proxy call`);
}
for (const [verb, args] of [['proxy.login.start', { provider: 'other' }], ['proxy.apikey.add', { provider: 'other', key: 'fixture-key' }]]) {
const s = setup({ hosts });
await assert.rejects(s.call(verb, args), { code: 'provider-not-allowed' }); assert.equal(s.calls.length, 0);
}
});
test('a3: a provider taken out of a test copy of the list is refused at its door, reads Other and leaves the providers answer', async () => {
for (const gone of PROVIDERS) {
const s = setup({ hosts, providers: PROVIDERS.filter(p => p !== gone) });
await assert.rejects(s.call(...door(gone)), { code: 'provider-not-allowed' }, gone.id);
assert.equal(s.calls.length, 0, `${gone.id}: refused before any proxy call`);
if (gone.signIn === 'oauth') s.state.files = [{ id: 'one.json', name: 'one.json', provider: gone.id, status: 'ready' }];
else s.state.groups = [{ name: 'g', 'base-url': gone.baseUrl, keys: [{ auth_index: 'idx-0-0' }], models: [{ name: 'm1' }] }];
const answer = await s.call('proxy.accounts');
assert.equal(answer.accounts.length, 1);
assert.equal(answer.accounts[0].provider, 'other', gone.id);
assert.match(answer.accounts[0].displayName, /^Other account /);
assert.equal(Object.hasOwn(answer.accounts[0], 'models'), false, `${gone.id}: an unlisted group shows no models`);
assert.deepEqual(answer.providers.map(p => p.id), PROVIDERS.filter(p => p !== gone).map(p => p.id));
}
});
test('a3: a provider a test copy adds is let through: key group from its base URL, sign-in on its host, name from its label', async () => {
const extra = [{ id: 'fixture.ai', label: 'Fixture AI', signIn: 'apikey', baseUrl: 'https://api.fixture.invalid/v1' },
{ id: 'fixture-sso', label: 'Fixture SSO', signIn: 'oauth', signInHost: 'sso.fixture.invalid' }];
const s = setup({ providers: [...PROVIDERS, ...extra], hosts: { ...hosts, 'fixture-sso': 'sso.fixture.invalid' } });
assert.deepEqual(await s.call('proxy.apikey.add', { provider: 'fixture.ai', key: 'fixture-key' }), { added: true });
assert.equal(s.state.groups[0]['base-url'], 'https://api.fixture.invalid/v1');
assert.match(s.state.groups[0].name, /^mosaic-fixtureai-[0-9a-f]{12}$/);
assert.equal(new URL((await s.call('proxy.login.start', { provider: 'fixture-sso' })).url).hostname, 'sso.fixture.invalid');
s.state.files = [{ id: 'sso.json', name: 'sso.json', provider: 'fixture-sso', status: 'ready' }];
const { accounts } = await s.call('proxy.accounts');
assert.deepEqual(accounts.map(a => [a.provider, a.displayName.replace(/ [0-9a-f]{12}$/, '')]), [['fixture-sso', 'Fixture SSO account'], ['fixture.ai', 'Fixture AI account']]);
assert.deepEqual(accounts[1].models, []);
});
test('a3: the sign-in address must be on the host the list names for that provider', async () => {
const codex = PROVIDERS.find(p => p.id === 'codex');
const moved = PROVIDERS.map(p => p === codex ? { ...p, signInHost: 'elsewhere.invalid' } : p);
const s = setup({ hosts, providers: moved });
await assert.rejects(s.call('proxy.login.start', { provider: 'codex' }), { code: 'proxy-down' });
const t = setup({ hosts: { ...hosts, codex: 'elsewhere.invalid' }, providers: moved });
assert.equal(new URL((await t.call('proxy.login.start', { provider: 'codex' })).url).hostname, 'elsewhere.invalid');
});
test('a3: the accounts answer carries the providers as id, label and sign-in kind only, no URL, host or key', async () => {
const s = setup({ hosts });
await s.call('proxy.apikey.add', { provider: 'z.ai', key: 'a3-canary-key-value' });
const answer = await s.call('proxy.accounts');
assert.deepEqual(answer.providers, PROVIDERS.map(({ id, label, signIn }) => ({ id, label, signIn })));
for (const p of answer.providers) assert.deepEqual(Object.keys(p).sort(), ['id', 'label', 'signIn']);
const text = JSON.stringify(answer.providers);
for (const word of ['a3-canary-key-value', 'https://', 'api.z.ai', 'claude.ai', 'auth.openai.com', 'baseUrl', 'signInHost']) assert.equal(text.includes(word), false, word);
});
// Review P3-1: an entry missing what its door needs is refused before any proxy call, so no sign-in
// is opened at the proxy that the page could not cancel; a key group with no base URL is no provider's.
test('a3: an entry with no sign-in host or no key base URL is refused before any proxy call and names no group', async () => {
const bare = [{ id: 'nohost', label: 'No Host', signIn: 'oauth' }, { id: 'nourl', label: 'No URL', signIn: 'apikey' }];
const s = setup({ providers: [...PROVIDERS, ...bare], hosts: { ...hosts, nohost: 'nohost.invalid' } });
await assert.rejects(s.call('proxy.login.start', { provider: 'nohost' }), { code: 'provider-not-allowed' });
await assert.rejects(s.call('proxy.apikey.add', { provider: 'nourl', key: 'fixture-key' }), { code: 'provider-not-allowed' });
assert.equal(s.calls.length, 0);
s.state.groups = [{ name: 'g', keys: [{ auth_index: 'idx-0-0' }], models: [{ name: 'm1' }] }];
s.state.files = [{ id: 'one.json', name: 'one.json', provider: 'nohost', status: 'ready' }];
const { accounts } = await s.call('proxy.accounts');
assert.deepEqual(accounts.map(a => a.provider), ['other', 'other']);
assert.equal(accounts.some(a => Object.hasOwn(a, 'models')), false);
});
+4 -1
View File
@@ -11,6 +11,7 @@ import { releaseState, initState, fenceState, initLockStatus, clearInitLock, app
import { secretValues } from './redact.mjs';
import { discoverModules, hasModule } from '../../plugins/src/loader.mjs';
import { readPluginLock } from '../../plugins/src/pinned.mjs';
import { PROVIDERS, publicProviders } from '../../plugins/model-provider/cliproxy/index.mjs';
export const proxyCode = (error, fallback) => (/^proxy-[a-z-]+$/.test(error?.code ?? '') ? error.code : fallback);
const failure = code => Object.assign(new Error(code), { code });
@@ -79,7 +80,7 @@ const isoTime = value => (typeof value === 'string' && /^[0-9]{4}-[0-9]{2}-[0-9]
// reads it ({document, revision}), read only. `harnesses()` lists the installed harness programs.
// `rootAgents()` reads the root agent file (loadRootAgents); with none given, or one that throws,
// no organization that has the program on is written (unreadable).
export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir = null, unit = null, fetch = fetchPinned, buses, orgs = async () => [], riders = async () => [], harnesses = () => installedHarnesses(dataRoot), rootAgents = null, ownerModels = async () => ({ proxy: false, riding: false, models: [] }), move = null, now = () => new Date(), env = process.env, pin = PIN }) {
export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir = null, unit = null, fetch = fetchPinned, buses, orgs = async () => [], riders = async () => [], harnesses = () => installedHarnesses(dataRoot), rootAgents = null, ownerModels = async () => ({ proxy: false, riding: false, models: [] }), move = null, now = () => new Date(), env = process.env, pin = PIN, providers = PROVIDERS }) {
const port = () => { try { return initState(configDir, dataRoot).settings?.port ?? null; } catch { return null; } };
const control = unit ?? createUnitControl({ instance, unitDir, port, env });
let job = { state: 'idle', step: null, receipt: null, error: null };
@@ -273,6 +274,8 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
initLock: lock,
fetch: fetchJob,
restart: restarted ? { confirmed: true, observedAt: restarted.observedAt, pid: restarted.after.pid } : null,
// #1873 settings-backend-a3: the page's provider select, from the plugin. Id, label and sign-in kind only.
providers: publicProviders(providers),
busy,
receipts: recentReceipts(dataRoot),
organizations,
+7 -5
View File
@@ -3,17 +3,19 @@ import http from 'node:http';
import { ProxyError, refuse, sha256, regularBytes, validManagementKey } from './common.mjs';
import { lstatSync } from 'node:fs';
import { join } from 'node:path';
import { PROVIDERS } from '../../plugins/model-provider/cliproxy/index.mjs';
const KEY_PATH = '/v8/management/config/access/api-keys';
const validKeys = value => Array.isArray(value) && value.length <= 100000 && value.every(k => typeof k === 'string' && k.length > 0 && k.length <= 4096 && !/[\r\n\x00]/.test(k));
export class ManagementClient {
#base; #key; #receipt; #timeout;
constructor({ baseUrl, key, receipt = () => {}, timeout = 5000 }) {
#base; #key; #receipt; #timeout; #providers;
// providers: the plugin's PROVIDERS; a test passes a copy with one taken out.
constructor({ baseUrl, key, receipt = () => {}, timeout = 5000, providers = PROVIDERS }) {
let u; try { u = new URL(baseUrl); } catch { refuse('proxy-client-invalid'); }
if (u.protocol !== 'http:' || u.hostname !== '127.0.0.1' || !u.port || Number(u.port) < 1024 || u.port === '8317'
|| u.username || u.password || u.pathname !== '/' || u.search || u.hash
|| !validManagementKey(key)
|| typeof receipt !== 'function' || !Number.isSafeInteger(timeout) || timeout <= 0) refuse('proxy-client-invalid');
this.#base = u.origin; this.#key = key; this.#receipt = receipt; this.#timeout = timeout;
|| typeof receipt !== 'function' || !Number.isSafeInteger(timeout) || timeout <= 0 || !Array.isArray(providers)) refuse('proxy-client-invalid');
this.#base = u.origin; this.#key = key; this.#receipt = receipt; this.#timeout = timeout; this.#providers = providers;
}
#request(method, endpoint, payload, onStatus) {
// node:http addresses the fixed numeric loopback directly. An ambient fetch
@@ -107,7 +109,7 @@ export class ManagementClient {
}
patchCredential(name, priority) { return this.#page('PATCH', '/v8/management/credentials/fields', { name, priority }, 200); }
oauthStart(provider) {
if (!['claude', 'codex'].includes(provider)) refuse('proxy-client-invalid');
if (!this.#providers.some(p => p.id === provider && p.signIn === 'oauth')) refuse('proxy-client-invalid');
return this.#page('GET', `/v8/management/oauth/auth-url?provider=${provider}`);
}
oauthCallback(redirect_url) { return this.#page('POST', '/v8/management/oauth/callback', { redirect_url }); }
@@ -0,0 +1,73 @@
// #1873 settings-backend-a3: the management client's sign-in allow list and the setup status's
// provider field both come from the plugin's PROVIDERS. oauthStart refuses the key provider and any
// provider a test copy of the list leaves out, before any request. The status field carries id,
// label and sign-in kind only: no base URL, no sign-in host, no key text.
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { ManagementClient } from '../src/client.mjs';
import { createProxyAdmin } from '../src/admin-control.mjs';
import { PROVIDERS } from '../../plugins/model-provider/cliproxy/index.mjs';
const code = name => error => error.code === name;
async function server(t) {
const asked = [];
const s = http.createServer((q, r) => { asked.push(new URL(q.url, 'http://x').searchParams.get('provider')); r.setHeader('content-type', 'application/json'); r.end(JSON.stringify({ status: 'ok', state: 's', url: 'https://claude.ai/x?state=s' })); });
await new Promise(r => s.listen(0, '127.0.0.1', r)); t.after(() => new Promise(r => s.close(r)));
return { asked, baseUrl: `http://127.0.0.1:${s.address().port}` };
}
test('a3: oauthStart asks the proxy for each sign-in provider in PROVIDERS and refuses the key provider before any request', async t => {
const { asked, baseUrl } = await server(t);
const c = new ManagementClient({ baseUrl, key: 'a3-management' });
for (const p of PROVIDERS.filter(p => p.signIn === 'oauth')) await c.oauthStart(p.id);
assert.deepEqual(asked, PROVIDERS.filter(p => p.signIn === 'oauth').map(p => p.id));
const keyed = PROVIDERS.filter(p => p.signIn === 'apikey');
assert.ok(keyed.length > 0);
for (const p of keyed) await assert.rejects(async () => c.oauthStart(p.id), code('proxy-client-invalid'), p.id);
for (const id of ['other', '', 'claude&x=1', undefined]) await assert.rejects(async () => c.oauthStart(id), code('proxy-client-invalid'));
assert.equal(asked.length, PROVIDERS.filter(p => p.signIn === 'oauth').length, 'no refused provider reached the proxy');
});
test('a3: oauthStart refuses a sign-in provider a test copy of the list leaves out, and asks for one it adds', async t => {
const { asked, baseUrl } = await server(t);
for (const gone of PROVIDERS.filter(p => p.signIn === 'oauth')) {
const c = new ManagementClient({ baseUrl, key: 'a3-management', providers: PROVIDERS.filter(p => p !== gone) });
await assert.rejects(async () => c.oauthStart(gone.id), code('proxy-client-invalid'), gone.id);
}
assert.deepEqual(asked, []);
const c = new ManagementClient({ baseUrl, key: 'a3-management', providers: [...PROVIDERS, { id: 'fixture-sso', label: 'Fixture SSO', signIn: 'oauth', signInHost: 'sso.fixture.invalid' }] });
await c.oauthStart('fixture-sso');
assert.deepEqual(asked, ['fixture-sso']);
assert.throws(() => new ManagementClient({ baseUrl, key: 'a3-management', providers: null }), code('proxy-client-invalid'));
});
function admin(t, extra = {}) {
const root = fs.mkdtempSync(join(tmpdir(), 'a3-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
fs.mkdirSync(configDir, { mode: 0o700 }); fs.mkdirSync(dataRoot, { mode: 0o700 });
const unit = { unit: 'mosaic-proxy-a3.service', status: async () => ({ unit: 'mosaic-proxy-a3.service', installed: false, active: 'inactive', healthy: false }) };
return createProxyAdmin({ dataRoot, configDir, unit, buses: async () => ({ stopped: true, running: [] }), fetch: async () => ({}), now: () => new Date(0),
orgs: async () => [], harnesses: () => [], rootAgents: () => ({ state: 'absent', agents: {}, assistant: null }), ...extra });
}
test('a3: the status lists the providers as id, label and sign-in kind only, in the plugin\'s order', async t => {
const status = await admin(t).status();
assert.deepEqual(status.providers, PROVIDERS.map(({ id, label, signIn }) => ({ id, label, signIn })));
for (const p of status.providers) assert.deepEqual(Object.keys(p).sort(), ['id', 'label', 'signIn']);
const text = JSON.stringify(status.providers);
for (const word of ['https://', 'api.z.ai', 'claude.ai', 'auth.openai.com', 'baseUrl', 'signInHost']) assert.equal(text.includes(word), false, word);
});
test('a3: the status field holds no key text, even from a list entry that carries a key, and a provider left out is gone', async t => {
const canary = 'a3-status-canary-key-0123456789';
const list = [...PROVIDERS.filter(p => p.id !== 'codex'), { id: 'fixture.ai', label: 'Fixture AI', signIn: 'apikey', baseUrl: `https://${canary}.invalid/`, key: canary, apiKey: canary }];
const status = await admin(t, { providers: list }).status();
assert.deepEqual(status.providers.map(p => p.id), ['claude', 'z.ai', 'fixture.ai']);
assert.equal(JSON.stringify(status.providers).includes(canary), false);
assert.equal(JSON.stringify(status).includes(canary), false);
});
@@ -1,6 +1,18 @@
// Provider configuration and transport declarations owned by the proxy module.
export const interfaceVersion = 1;
export const ZAI_URL = 'https://api.z.ai/api/anthropic';
// #1873 settings-backend-a3: the one list of providers an account can be added for. The bus proxy
// page, the management client and the Console's provider select all read it; a provider not here
// is refused. `id` is the value the page sends and an account row carries. An OAuth provider names
// the host its sign-in address must be on; the key provider names the base URL its key group uses.
// The setup status and the accounts read pass on only id, label and sign-in kind.
export const PROVIDERS = Object.freeze([
Object.freeze({ id: 'claude', label: 'Claude', signIn: 'oauth', signInHost: 'claude.ai' }),
Object.freeze({ id: 'codex', label: 'ChatGPT / Codex', signIn: 'oauth', signInHost: 'auth.openai.com' }),
Object.freeze({ id: 'z.ai', label: 'z.ai', signIn: 'apikey', baseUrl: ZAI_URL }),
]);
// What a page may see of the list: no URL, no host, nothing else.
export const publicProviders = (list = PROVIDERS) => list.map(({ id, label, signIn }) => ({ id, label, signIn }));
export const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/;
const MODEL = MODEL_ID;
const MAX_MODELS = 10000;
+250 -30
View File
@@ -603,13 +603,13 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
+ '<details id="proxy-account-order"><summary>Account order</summary><div class="inside"><p class="small muted">Higher priority is used first. Credential values are never shown.</p><ul id="proxy-order" class="rows proxy-order"></ul></div></details>'
+ '<details id="proxy-offered"><summary>Models offered</summary><div class="inside" id="proxy-offered-list"></div></details>'
+ '<details id="proxy-add-box"><summary>Add an account</summary><div class="inside">'
+ '<form id="proxy-login-start" class="settings-form"><fieldset data-write disabled><div class="field"><label for="proxy-provider">Provider</label>'
+ '<select id="proxy-provider" name="provider"><option value="claude">Claude (subscription)</option><option value="codex">ChatGPT / Codex (subscription)</option><option value="z.ai">z.ai (API key)</option></select>'
+ '<p class="help small muted">Claude and ChatGPT / Codex: you sign in on the provider\'s site in a new tab. Nothing you type there comes to this page. z.ai: you paste an API key from your z.ai account.</p></div>'
+ '<div class="form-foot"><button type="submit" id="proxy-login-go">Sign in to Claude</button></div></fieldset></form>'
+ '<form id="proxy-apikey" class="settings-form" hidden><fieldset data-write disabled><div class="field"><label for="proxy-apikey-key" id="proxy-apikey-label">z.ai API key</label>'
+ '<form id="proxy-login-start" class="settings-form"><fieldset data-write disabled><div class="field"><label for="proxy-provider" hidden>Provider</label>'
// settings-backend-a3: the options and this help text come from the plugin's provider list (setProviders).
+ '<select id="proxy-provider" name="provider" hidden></select><p id="proxy-provider-help" class="help small muted">Reading providers…</p></div>'
+ '<div class="form-foot"><button type="submit" id="proxy-login-go" hidden>Sign in</button></div></fieldset></form>'
+ '<form id="proxy-apikey" class="settings-form" hidden><fieldset data-write disabled><div class="field"><label for="proxy-apikey-key" id="proxy-apikey-label">API key</label>'
+ '<input id="proxy-apikey-key" name="key" type="password" autocomplete="off" spellcheck="false" maxlength="4096" required>'
+ '<p class="help small muted">Mosaic checks it with z.ai, keeps it in your model service, and never shows it again.</p></div>'
+ '<p class="help small muted">Mosaic checks it with <span id="proxy-apikey-provider">the provider</span>, keeps it in your model service, and never shows it again.</p></div>'
+ '<div class="form-foot"><button type="submit">Check and add</button><button type="button" id="proxy-apikey-cancel">Cancel</button></div></fieldset><p id="proxy-apikey-message" role="status"></p></form>'
+ '</div></details>'
+ '<div id="proxy-signin" hidden><ol id="proxy-signin-progress" class="progress" aria-label="Sign-in progress"></ol>'
@@ -627,8 +627,12 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
+ '<ul id="proxy-ride-skips" class="proxy-ride-list"></ul><ul id="proxy-ride-fixtures" class="proxy-ride-list"></ul></div>';
const triage = '<p><a id="proxy-setup-triage" class="btn" href="#/settings/triage">Set up Triage</a></p>';
const advanced = '<details id="proxy-setup-advanced" data-admin hidden><summary>Advanced: programs, port, timeouts</summary><div class="inside">'
+ '<div class="settings-form"><p class="lbl">Programs that drive models</p><ul id="proxy-setup-programs" class="model-list"></ul>'
+ '<p class="help small muted">Each organization switches these on or off on its own Models page. Claude subscription models run only in Claude Code. Turning a program off for every organization is not built yet.</p></div>'
// settings-s5c: the installed programs and which organizations have each one on, from the status
// read; one program can be turned off in every organization that can do without it.
+ '<div class="settings-form proxy-programs"><h4 id="proxy-setup-programs-title" class="lbl">Programs that drive models</h4>'
+ '<p class="help small muted">Each organization turns these on or off on its own Models page. Claude subscription models run only in Claude Code. Turn off for every organization skips an organization that still uses the program or has no other program on.</p>'
+ '<ul id="proxy-setup-programs" class="proxy-programs-list" aria-labelledby="proxy-setup-programs-title"><li class="muted">Not read yet.</li></ul>'
+ '<div id="proxy-setup-programs-result" class="proxy-programs-result" tabindex="-1" hidden></div></div>'
+ '<form id="proxy-setup-init" class="settings-form"><fieldset data-setup-write disabled><legend>Service key</legend>'
+ '<p class="small muted">Mosaic makes the service key on this machine, keeps it where setup keeps keys and never shows it.</p></fieldset>'
+ '<fieldset data-setup-write disabled><legend>Settings (leave empty for the defaults)</legend>'
@@ -644,6 +648,11 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
+ '<ol id="proxy-setup-history" aria-labelledby="proxy-setup-history-title"></ol>'
+ '<p class="proxy-setup-history-foot"><button type="button" id="proxy-setup-history-all" aria-expanded="false" aria-controls="proxy-setup-history" hidden>Show all</button>'
+ '<button type="button" id="proxy-setup-history-older" hidden>Show older</button><button type="button" id="proxy-setup-history-retry" hidden>Read again</button></p></div>'
// settings-s5c: access health per organization (GET /api/proxy/admin/access), read when this box opens.
+ '<div class="proxy-setup-access"><h4 id="proxy-setup-access-title">Access</h4><p class="small muted">Whether each organization\'s agents can reach your models. You never see a key.</p>'
+ '<p id="proxy-setup-access-message" class="small muted" role="status">Not read yet.</p>'
+ '<ul id="proxy-setup-access" class="rows proxy-access" aria-labelledby="proxy-setup-access-title"></ul>'
+ '<p class="proxy-setup-history-foot"><button type="button" id="proxy-setup-access-retry" hidden>Read again</button></p></div>'
+ '<details id="proxy-setup-tech-lines" class="proxy-setup-lines"><summary>The service\'s last lines</summary><div class="inside" data-log></div></details>'
+ '<div class="proxy-setup-unit"><h4>Service controls</h4><p class="small muted">Install renders the unit the same way as <code>mosaic proxy unit install</code>.</p>'
+ '<div class="proxy-setup-buttons"><button type="button" data-unit="install" data-setup-write disabled>Install</button><button type="button" data-unit="start" data-setup-write disabled>Start</button><button type="button" data-unit="restart" data-setup-write disabled>Restart</button><button type="button" data-unit="stop" data-setup-write disabled>Stop</button><button type="button" id="proxy-setup-render">Show unit file</button></div>'
@@ -678,7 +687,8 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
const cell = value => { const td = document.createElement('td'); td.textContent = value ?? '—'; return td; };
const el = (tag, text, className) => { const e = document.createElement(tag); if (text !== undefined) e.textContent = text; if (className) e.className = className; return e; };
// The provider select is this page's one list of providers: rows and buttons take their names
// and kinds (subscription or API key) from its option labels.
// and kinds (subscription or API key) from its option labels. Its options come from the plugin's
// list (setProviders), read with the setup status for the instance owner, with the accounts for anyone else.
const providerSelect = $('proxy-provider');
const providerLabel = p => [...providerSelect.options].find(o => o.value === p)?.textContent ?? String(p ?? 'Unknown');
const providerShort = p => providerLabel(p).replace(/\s*\([^)]*\)$/, '');
@@ -792,6 +802,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
}
async function refresh() {
const accounts = await call('accounts');
if (!proxyAdmin) setProviders(accounts?.providers);
accountList = Array.isArray(accounts?.accounts) ? accounts.accounts : [];
accountsDown = null;
paintAccounts(); paintOrder();
@@ -838,9 +849,28 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
$('proxy-offered').addEventListener('toggle', () => { if ($('proxy-offered').open) readOffered(); });
// Add an account: the provider picks a sign-in or an API key.
function paintProvider() {
const p = providerSelect.value, apikey = keyed(p);
const go = $('proxy-login-go'); go.textContent = `Sign in to ${providerShort(p)}`; go.hidden = apikey;
const p = providerSelect.value, apikey = Boolean(p) && keyed(p);
const go = $('proxy-login-go'); go.textContent = `Sign in to ${providerShort(p)}`; go.hidden = apikey || !p;
$('proxy-apikey').hidden = !apikey; $('proxy-apikey-label').textContent = `${providerShort(p)} API key`;
$('proxy-apikey-provider').textContent = providerShort(p);
}
// settings-backend-a3: no list, or an empty one, leaves no select and one line saying so.
let providerKey = null;
function setProviders(list) {
const items = Array.isArray(list) ? list.filter(p => typeof p?.id === 'string' && p.id && typeof p.label === 'string' && ['oauth', 'apikey'].includes(p.signIn)) : [];
const key = JSON.stringify(items.map(p => [p.id, p.label, p.signIn]));
if (key === providerKey) return; providerKey = key;
const kept = providerSelect.value;
providerSelect.replaceChildren(...items.map(p => el('option', `${p.label} (${p.signIn === 'oauth' ? 'subscription' : 'API key'})`)));
items.forEach((p, i) => { providerSelect.options[i].value = p.id; });
if (items.some(p => p.id === kept)) providerSelect.value = kept;
providerSelect.hidden = !items.length; for (const label of providerSelect.labels) label.hidden = !items.length;
const oauth = items.filter(p => p.signIn === 'oauth').map(p => p.label);
$('proxy-provider-help').textContent = !items.length ? 'The providers could not be read, so no account can be added here.'
: [oauth.length ? `${new Intl.ListFormat('en').format(oauth)}: you sign in on the provider's site in a new tab. Nothing you type there comes to this page.` : '',
...items.filter(p => p.signIn === 'apikey').map(p => `${p.label}: you paste an API key from your ${p.label} account.`)].filter(Boolean).join(' ');
paintProvider();
if (accountList) { paintAccounts(); paintOrder(); }
}
providerSelect.addEventListener('change', paintProvider);
function paintSignin() {
@@ -953,7 +983,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
'not-configured': 'Model service setup is not available on this Console.',
'outcome-unknown': 'The outcome is unknown. Check the status before retrying.',
};
const explain = code => `${REASONS[code] ?? 'The action was refused.'} (${code})`;
const explain = code => `${Object.hasOwn(REASONS, code) ? REASONS[code] : 'The action was refused.'} (${code})`;
async function admin(path, args) {
const response = await fetch('/api/proxy/admin/' + path, { cache: 'no-store', credentials: 'same-origin', redirect: 'manual',
method: args === undefined ? 'GET' : 'POST',
@@ -976,7 +1006,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
// A failed read says what the answer's code means here; a request that got no answer says so. A code
// shaped like a Mosaic key is not shown, even though it passes admin()'s letters-and-hyphens check.
const failText = (error, words) => !error?.code ? (error instanceof TypeError ? 'The Console did not answer.' : String(error?.message ?? 'The Console did not answer.'))
: /ms[kotp][-_]/i.test(error.code) ? 'The Console refused the read.' : words[error.code] ? `${words[error.code]} (${error.code})` : error.message;
: /ms[kotp][-_]/i.test(error.code) ? 'The Console refused the read.' : Object.hasOwn(words, error.code) ? `${words[error.code]} (${error.code})` : error.message;
const retryButton = (id, action) => { const button = el('button', 'Read again'); button.type = 'button'; if (id) button.id = id; button.addEventListener('click', action); return button; };
// The service's last lines: one read paints every box. The lines show as the answer has them:
// the route removes key-shaped text; this page adds nothing and takes nothing away.
@@ -1117,7 +1147,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
// Show older shows what it reads: the list stays open from then on.
$('proxy-setup-history-older').addEventListener('click', () => { if (!hist.loading && hist.next !== null) { hist.expanded = true; readHistory(false); } });
$('proxy-setup-history-retry').addEventListener('click', () => readHistory(!hist.read));
$('proxy-setup-tech').addEventListener('toggle', () => { if (techOpen() && enabled) { readKey(); readHistory(true); } });
$('proxy-setup-tech').addEventListener('toggle', () => { if (techOpen() && enabled) { readKey(); readHistory(true); readAccess(); } });
$('proxy-setup-tech-lines').addEventListener('toggle', () => { if ($('proxy-setup-tech-lines').open && enabled) readLog(); });
function row(dl, term, text) { const dt = document.createElement('dt'), dd = document.createElement('dd'); dt.textContent = term; dd.textContent = text; dl.append(dt, dd); }
function paintState() {
@@ -1368,18 +1398,206 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
if (s.rotateGraceMinutes !== undefined) row(dl, 'Old key kept after a new one', s.rotateGraceMinutes === null ? 'The default' : `${human(s.rotateGraceMinutes)} minutes`);
}
}
// Programs that drive models: the harnesses this Console offers an organization, read on open.
let programsRead = false;
$('proxy-setup-advanced').addEventListener('toggle', async () => {
if (!$('proxy-setup-advanced').open || programsRead) return; programsRead = true;
const list = $('proxy-setup-programs'); list.replaceChildren(el('li', 'Reading…', 'muted'));
// settings-s5c: Programs that drive models, from the status read's programs field (owner only: only
// the owner's page reads the status). A list the read could not give reads as not known, never as off.
// Program names come from the read; this page holds no list of them.
const KEYISH = /ms[kotp][-_]/i;
const programName = v => typeof v === 'string' && /^[a-z][a-z0-9-]{0,31}$/.test(v) && !KEYISH.test(v) ? v : null;
const orgLabel = id => shownName(orgName(id)) ?? shownName(id) ?? 'An organization Mosaic can\'t name';
let offAsk = null, offBusy = false, offView = null, offFocus = null;
function programsState() {
const p = state?.programs;
if (!p || typeof p !== 'object') return { error: 'The programs could not be read.' };
if (!Array.isArray(p.installed)) return { error: 'The installed programs could not be read.' };
const names = [...new Set(p.installed.map(programName).filter(Boolean))], hidden = p.installed.some(n => !programName(n));
const orgs = Array.isArray(p.organizations) ? p.organizations.filter(o => o && typeof o === 'object') : null;
return { names, hidden, orgs };
}
function programLine(name, orgs) {
if (!orgs) return 'Which organizations have it on could not be read.';
if (!orgs.length) return 'No organization to check.';
const on = [], off = [], unknown = [];
for (const o of orgs) {
const label = orgLabel(o.id);
if (!Array.isArray(o.on)) unknown.push(label); else if (o.on.includes(name)) on.push(label); else off.push(label);
}
const parts = [];
parts.push(on.length ? `On in ${listNames(on)}.` : 'On in no organization.');
if (off.length) parts.push(`Off in ${listNames(off)}.`);
if (unknown.length) parts.push(`Not known in ${listNames(unknown)}: ${unknown.length === 1 ? 'its list' : 'their lists'} could not be read.`);
return parts.join(' ');
}
function paintPrograms() {
const list = $('proxy-setup-programs'), had = document.activeElement;
// A repaint while a control here holds focus puts focus back on the same control.
const keep = had && list.contains(had) ? (had.id ? '#' + had.id : had.dataset.programOff ? `[data-program-off="${had.dataset.programOff}"]` : null) : null;
const view = programsState();
// A read that no longer lists the program being asked about drops the question.
if (offAsk !== null && (view.error || !view.names.includes(offAsk))) offAsk = null;
if (view.error) { list.replaceChildren(el('li', view.error, 'muted')); return; }
const items = view.names.map(name => {
const li = el('li'); li.dataset.program = name;
const head = el('div', '', 'proxy-program-head');
head.append(el('span', name, 'proxy-program-name'));
const off = el('button', 'Turn off for every organization'); off.type = 'button'; off.dataset.programOff = name;
off.setAttribute('aria-label', `Turn off ${name} for every organization`);
off.disabled = !sendOk || offBusy || offAsk !== null;
off.addEventListener('click', () => askOff(name));
head.append(off); li.append(head, el('p', programLine(name, view.orgs), 'small proxy-program-orgs'));
if (offAsk === name) {
const box = el('div', '', 'proxy-program-confirm'); box.setAttribute('role', 'group'); box.setAttribute('aria-labelledby', 'proxy-setup-programs-ask');
const ask = el('p', `Turn off ${name} in every organization? Mosaic skips an organization where something still uses ${name} or where it is the only program on. Turning it on again is done on each organization's Models page.`);
ask.id = 'proxy-setup-programs-ask';
const yes = el('button', `Turn off ${name}`, 'danger'); yes.type = 'button'; yes.id = 'proxy-setup-programs-yes'; yes.disabled = !sendOk || offBusy;
yes.addEventListener('click', () => programsOff(name));
const no = el('button', 'Cancel'); no.type = 'button'; no.id = 'proxy-setup-programs-no';
no.addEventListener('click', () => { offAsk = null; paintPrograms(); root.querySelector(`[data-program-off="${name}"]`)?.focus(); });
const foot = el('p', '', 'proxy-setup-history-foot'); foot.append(yes, no);
box.append(ask, foot); li.append(box);
}
return li;
});
if (!view.names.length) items.push(el('li', 'No programs are installed.', 'muted'));
if (view.hidden) items.push(el('li', 'One or more programs have a name this page does not show.', 'muted'));
list.replaceChildren(...items);
if (keep) root.querySelector(keep)?.focus();
}
function askOff(name) {
if (!sendOk || offBusy) return;
offAsk = name; paintPrograms(); $('proxy-setup-programs-yes')?.focus();
}
// What each organization's outcome means, in plain words (settings-backend-a2 build report).
function offOutcome(outcome) {
const words = {
off: 'Turned off.',
'already-off': 'It was already off. Nothing changed.',
'in-use': 'Kept on. Something there still uses it: a role route, a fallback or an agent.',
'last-program': 'Kept on. It is the only program on there.',
'bus-down': 'Not changed. Its programs could not be read.',
unreadable: 'Not changed. Something Mosaic needed to check could not be read.',
'failed:revision-conflict': 'Not changed. It changed while Mosaic was checking. Try again.',
'failed:outcome-unknown': 'May have changed. The change did not answer in time.',
};
if (typeof outcome !== 'string') return 'Not known. The answer did not say what happened.';
if (Object.hasOwn(words, outcome)) return words[outcome];
if (outcome.startsWith('failed:')) {
const code = outcome.slice(7);
return /^[a-z0-9][a-z0-9-]{0,63}$/.test(code) && !KEYISH.test(code) ? `Not changed. It refused the change (${code}).` : 'Not changed. It refused the change, with a code this page does not show.';
}
return 'Not known. The answer did not say what happened.';
}
const OFF_WORDS = {
'invalid-request': 'The Console refused the request: the program is not in its installed list, or that list could not be read.',
'human-required': 'Only the instance owner can turn a program off.',
'proxy-admin-busy': 'Another setup action is running. Wait for it to finish, then try again.',
};
function paintOffResult() {
const box = $('proxy-setup-programs-result');
if (!offView) { box.hidden = true; box.replaceChildren(); return; }
box.hidden = false;
if (offView.working) { box.className = 'proxy-programs-result'; box.replaceChildren(el('p', `Turning off ${offView.name}…`, 'small muted')); return; }
// Whether the list above was read again after the answer: it says so, and never claims a list it did not get.
const reread = () => {
if (offView.reread === 'ok') return [el('p', 'The list above is read again and shows what is on now.', 'small proxy-programs-reread')];
if (offView.reread === 'failed') {
const foot = el('p', '', 'proxy-setup-history-foot'); foot.append(retryButton('proxy-setup-programs-reread', () => rereadPrograms(true)));
return [el('p', 'The list above could not be read again, so it may be out of date.', 'small proxy-programs-reread'), foot];
}
return [el('p', 'Reading the list again…', 'small muted proxy-programs-reread')];
};
if (offView.line) { box.className = `proxy-programs-result banner ${offView.kind === 'busy' ? 'ref' : 'err'}`; box.replaceChildren(el('p', offView.line), ...reread()); return; }
box.className = 'proxy-programs-result banner';
const title = el('p', `Turn off ${offView.name}: what happened in each organization.`, 'proxy-programs-result-title');
const ul = el('ul', '', 'proxy-programs-outcomes');
for (const r of offView.results) {
const li = el('li'); li.dataset.outcome = typeof r?.outcome === 'string' && /^[a-z:-]{1,80}$/.test(r.outcome) && !KEYISH.test(r.outcome) ? r.outcome : 'unknown';
li.append(el('span', orgLabel(r?.id), 'proxy-outcome-org'), document.createTextNode(': '), el('span', offOutcome(r?.outcome)));
ul.append(li);
}
box.replaceChildren(title, offView.results.length ? ul : el('p', 'No organization was in the answer.', 'small muted'), ...reread());
}
// Read the status again after a turn-off answer, after a read already under way. load() keeps the
// old state when its read fails, so a new state object is the sign the list was read again.
async function rereadPrograms(fromButton) {
const view = offView; if (!view) return;
view.reread = 'reading'; paintOffResult();
while (loading) await pause(50);
const painted = await load();
if (offView !== view) return;
view.reread = painted ? 'ok' : 'failed'; paintOffResult();
const box = $('proxy-setup-programs-result');
if (fromButton || document.activeElement === document.body || !document.activeElement) (view.reread === 'failed' ? $('proxy-setup-programs-reread') : box)?.focus();
}
async function programsOff(name) {
if (!sendOk || offBusy) return;
offBusy = true; offAsk = null; offView = { name, working: true }; paintPrograms(); paintOffResult();
const box = $('proxy-setup-programs-result'); box.focus();
let view;
try {
const r = await fetch('/api/proxy/plugins', { cache: 'no-store', redirect: 'manual' }); const v = r.ok ? await r.json() : null;
const names = Array.isArray(v?.available?.harness) ? v.available.harness.filter(n => typeof n === 'string') : null;
if (!names) throw Error();
list.replaceChildren(...(names.length ? names.map(n => el('li', n)) : [el('li', 'No programs are installed.', 'muted')]));
} catch { programsRead = false; list.replaceChildren(el('li', 'The programs could not be read.', 'muted')); }
});
const value = await admin('programs/off', { name });
if (!value || typeof value !== 'object' || !Array.isArray(value.results)) throw Object.assign(new Error('The answer could not be read.'), { code: 'outcome-unknown' });
view = { name, results: value.results };
addReceipt(value.receipt);
} catch (error) {
if (error?.code === 'proxy-admin-busy') view = { name, kind: 'busy', line: `${name} was not turned off. ${OFF_WORDS['proxy-admin-busy']}` };
else if (error?.code === 'invalid-request' || error?.code === 'human-required') view = { name, line: `${name} was not turned off. ${failText(error, OFF_WORDS)}` };
else view = { name, line: `Turning off ${name} may not have finished, so some organizations may have changed. ${failText(error, OFF_WORDS)}` };
}
offView = view; offBusy = false; paintOffResult(); paintPrograms();
box.focus();
// After any answer, read the status again.
await rereadPrograms(false);
}
// settings-s5c: access health per organization, read when Technical details opens (owner only).
// Ready only for health ok whose every stack-managed key is active; never a key, a key id or the
// count of other keys, which holds other organizations' keys and is not a warning.
const ACCESS_WORDS = { 'human-required': 'Only the instance owner can read access.', 'outcome-unknown': 'The host could not read access.', 'not-configured': 'Model service setup is not available on this Console.' };
let accessRound = 0, accessView = null;
function accessHealth(o) {
const unknown = ['badge-muted', 'Not known', 'The answer did not say.'];
if (!o || typeof o !== 'object') return unknown;
const { health, reason, keys } = o;
if (health === 'ok') return reason === undefined && Array.isArray(keys) && keys.length > 0 && keys.every(k => k && typeof k === 'object' && k.state === 'active')
? ['badge-ok', 'Ready', null] : ['badge-muted', 'Not known', 'The answer did not agree with itself.'];
if (health === 'attention') return reason === 'proxy-uncertain'
? ['badge-attn', 'Not sure', 'The model service did not answer clearly, so Mosaic can\'t tell whether its access works.']
: ['badge-attn', 'Needs attention', 'Some of its access is not active.'];
if (health === 'missing') return ['badge-attn', 'None yet', 'No agent here has access to your models yet.'];
if (health === 'not-riding') return ['badge-muted', 'Not used', 'It does not use your models.'];
if (health === 'unreadable') return ['badge-danger', 'Could not be read', reason === 'bus-down' ? 'Its bus did not answer.' : reason === 'no-proxy-client' ? 'Its bus has no model service client set up.' : reason === 'unreadable' ? 'Its answer about access could not be read.' : null];
return unknown;
}
function paintAccess() {
const list = $('proxy-setup-access'), message = $('proxy-setup-access-message'), retry = $('proxy-setup-access-retry');
retry.hidden = !accessView?.error;
if (!accessView) { message.className = 'small muted'; message.textContent = 'Not read yet.'; list.replaceChildren(); return; }
if (accessView.reading) { message.className = 'small muted'; message.textContent = 'Reading…'; return; }
if (accessView.error) { message.className = 'banner err'; message.textContent = `Access could not be read. ${accessView.error}`; list.replaceChildren(); return; }
const orgs = accessView.organizations;
message.className = 'small muted'; message.textContent = orgs.length ? '' : 'There is no organization to check.';
list.replaceChildren(...orgs.map(o => {
const [badge, word, why] = accessHealth(o), li = el('li');
li.dataset.access = word === 'Ready' ? 'ready' : 'not-ready';
li.append(el('span', orgLabel(o?.id)), el('span', word, `badge ${badge}`));
if (why) li.append(el('p', why, 'small muted account-reason'));
return li;
}));
}
async function readAccess() {
if (!enabled) return;
const round = ++accessRound, refocus = document.activeElement?.id === 'proxy-setup-access-retry';
accessView = { ...(accessView ?? {}), reading: true, error: null }; paintAccess();
let view;
try {
const value = await admin('access');
if (!value || typeof value !== 'object' || !Array.isArray(value.organizations)) throw Object.assign(new Error('The answer could not be read.'), { code: 'outcome-unknown' });
view = { organizations: value.organizations };
} catch (error) { view = { error: failText(error, ACCESS_WORDS) }; }
if (round !== accessRound || !enabled) return;
accessView = view; paintAccess();
if (refocus) { if (view.error) $('proxy-setup-access-retry').focus(); else { const m = $('proxy-setup-access-title'); m.tabIndex = -1; m.focus(); } }
}
$('proxy-setup-access-retry').addEventListener('click', readAccess);
// #1873 ride-default: Ride all and the fixture move. The server decides each organization again;
// this code only words the answer. Every write asks first, in plain words, what changes.
const RIDE_REASONS = {
@@ -1458,7 +1676,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
};
$('proxy-ride-go').addEventListener('click', () => { if (!$('proxy-ride-go').disabled) rideAll(); });
function paint() {
paintState(); paintControls(); paintService(); paintRestart(); paintOrgsCard(); paintTriageCard(); paintAccountCard();
paintState(); paintControls(); paintService(); paintRestart(); paintOrgsCard(); paintTriageCard(); paintAccountCard(); paintPrograms();
const job = state.fetch;
if (job.state === 'running') say(`Downloading: ${STEPS[job.step] ?? job.step ?? 'starting'}…`);
else if (job.state === 'failed' && seenFetch !== 'failed') { say(`Fetch failed. ${explain(job.error)}`, 'error'); seenFetch = 'failed'; }
@@ -1469,11 +1687,13 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
document.dispatchEvent(new CustomEvent('mosaic-proxy-status', { detail: state }));
focusStep();
}
// True once the answer is painted, so a caller can say the list on the page is the new one.
async function load() {
if (!enabled || loading) return; loading = true;
try { state = await admin('status'); causeRound++; if (state.next?.[0] === 'accounts' && triageSet === null) await readTriage(); paint(); if (state.init.initialized) await accountsReady(); }
catch (error) { say(error.message, 'error'); }
if (!enabled || loading) return false; loading = true; let painted = false;
try { state = await admin('status'); setProviders(state.providers); causeRound++; if (state.next?.[0] === 'accounts' && triageSet === null) await readTriage(); paint(); painted = true; if (state.init.initialized) await accountsReady(); }
catch (error) { say(error.message, 'error'); if (providerKey === null) setProviders(null); }
finally { loading = false; }
return painted;
}
async function act(label, action) {
if (!sendOk || state?.busy || chain?.running) return;
@@ -1587,7 +1807,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
if (proxyAdmin) { root.querySelectorAll('[data-admin]').forEach(part => { part.hidden = false; }); setup.start(config); }
paintAccountCard();
return refresh();
}).then(() => message('')).catch(error => { message(error.message);
}).then(() => message('')).catch(error => { message(error.message); if (!proxyAdmin && providerKey === null) setProviders(null);
// #1873: on the setup page a stopped proxy hides the account parts like an unconfigured one,
// and the setup load brings them back once the service answers.
// Any failed read hides them, not only proxy-down: a proxy that is initialized but not yet answering
+9
View File
@@ -122,6 +122,15 @@ table.s1-table td code{font-size:12.5px;white-space:nowrap}
/* settings-s5b: the setup history (GET /api/proxy/admin/history), the service key and the service's lines. */
#proxy-setup-history{list-style:none;padding-left:0;overflow-wrap:anywhere;font-size:13px;margin:0 0 8px}#proxy-setup-history li{padding:2px 0}
.proxy-setup-history-foot{display:flex;flex-wrap:wrap;gap:8px;margin:0}.proxy-setup-history-foot button,[data-log] button,#proxy-setup-keymade-retry{min-height:44px}
/* settings-s5c: Programs that drive models under Advanced, and Access under Technical details. */
.settings-form.proxy-programs{margin-bottom:20px;gap:8px}.proxy-programs-list{list-style:none;margin:8px 0 0;padding:0}.proxy-programs-list>li{padding:10px 0;border-top:1px solid var(--line);min-width:0}
.proxy-program-head{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:8px 12px}.proxy-program-name{font-weight:600;color:var(--strong)}
.proxy-program-head button,.proxy-program-confirm button,#proxy-setup-access-retry{min-height:44px}.proxy-program-orgs{margin:4px 0 0;overflow-wrap:anywhere}
.proxy-program-confirm{margin:8px 0 0;padding:10px 12px;border:1px solid color-mix(in srgb,var(--danger) 50%,var(--line));border-radius:var(--r);background:color-mix(in srgb,var(--danger) 6%,var(--surface))}.proxy-program-confirm>p:first-child{margin:0 0 8px;overflow-wrap:anywhere}
.proxy-program-confirm button.danger{color:var(--danger);border-color:color-mix(in srgb,var(--danger) 60%,var(--line))}
.proxy-programs-result{margin:12px 0 0;display:block}.proxy-programs-result[hidden]{display:none}.proxy-programs-result:focus-visible,#proxy-setup-access-title:focus-visible{outline:2px solid var(--focus);outline-offset:2px}.proxy-programs-result>p{margin:0}.proxy-programs-result>.proxy-programs-reread{margin-top:8px}.proxy-programs-result-title{font-weight:600;color:var(--strong)}
.proxy-programs-outcomes{margin:6px 0 0;padding-left:18px;overflow-wrap:anywhere}.proxy-programs-outcomes li{padding:2px 0}.proxy-outcome-org{font-weight:600}
.proxy-setup-access{margin:12px 0}.proxy-setup-access h4{margin:0 0 2px}.proxy-access li>.badge{justify-self:start}.proxy-setup-access .rows{margin-top:4px}#proxy-setup-access-message:empty{display:none}
[data-log] .setup-log{margin:8px 0}[data-log] p{margin:0 0 8px}#proxy-setup-history-message:empty{display:none}
/* #1873 settings slice 1 (D3, D4): the kept restart list and Technical details. */
.proxy-setup-restart{margin:0 0 12px}
@@ -10,3 +10,21 @@ test('Console production module graph cannot import the model-proxy client', asy
platform: 'node', format: 'esm', splitting: true, outdir: '/unused-proxy-architecture', write: false, metafile: true, logLevel: 'silent' });
assert.equal(Object.keys(result.metafile.inputs).some(file => file.endsWith('/model-proxy/src/client.mjs')), false);
});
// #1873 settings-backend-a3: the provider list lives in the cliproxy plugin's PROVIDERS. The
// management client, the bus proxy page and the settings page read it; none of them writes the
// provider ids, sign-in hosts or key base URL out as its own list.
test('a3: no provider id, sign-in host or key base URL is written out in client.mjs, proxy-page.mjs or display.js', async () => {
const { readFileSync } = await import('node:fs');
const { PROVIDERS } = await import('../../plugins/model-provider/cliproxy/index.mjs');
const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const words = PROVIDERS.flatMap(p => [p.id, p.signInHost, p.baseUrl]).filter(Boolean);
assert.ok(words.length >= PROVIDERS.length + 2);
const quoted = new RegExp(`['"\`](${words.map(escape).join('|')})['"\`]`);
const keyed = new RegExp(`[{,]\\s*(${PROVIDERS.map(p => escape(p.id)).join('|')})\\s*:`);
for (const file of ['../../model-proxy/src/client.mjs', '../../bus/src/proxy-page.mjs', '../src/public/display.js']) {
const text = readFileSync(new URL(file, import.meta.url), 'utf8');
assert.equal(quoted.exec(text)?.[0], undefined, `${file} writes a provider value out`);
assert.equal(keyed.exec(text)?.[0], undefined, `${file} keys an object by provider id`);
assert.equal(/<option value=/.test(text), false, `${file} writes a provider option out`);
}
});
+37 -4
View File
@@ -6,8 +6,9 @@ import http from 'node:http';
import { readFileSync, existsSync } from 'node:fs';
import { resolve, extname } from 'node:path';
import { browser } from './browser.mjs';
async function setup(t, readonly = false, refusal = null) {
const state = { routes: [], loginStatus: 'wait', receivedKey: false, release: null, priority: 0, models: ['fixture-old'] };
import { publicProviders } from '../../plugins/model-provider/cliproxy/index.mjs';
async function setup(t, readonly = false, refusal = null, providers = publicProviders()) {
const state = { routes: [], loginStatus: 'wait', receivedKey: false, keyProvider: null, release: null, priority: 0, models: ['fixture-old'] };
const server = http.createServer(async (req, res) => {
const send = value => { res.setHeader('content-type', 'application/json'); res.end(JSON.stringify(value)); };
if (req.url === '/api/config') return send({ send: !readonly, devOwner: true });
@@ -16,10 +17,10 @@ async function setup(t, readonly = false, refusal = null) {
if (refusal && req.url.endsWith(refusal)) { res.statusCode = 503; return send({ error: 'not-configured' }); }
const chunks = []; for await (const c of req) chunks.push(c);
const args = chunks.length ? JSON.parse(Buffer.concat(chunks)) : {};
if (req.url.endsWith('/accounts')) return send({ accounts: [{ accountId: 'a'.repeat(12), provider: 'claude', displayName: '<img src=x onerror="window.injected=true">', status: 'ready', priority: state.priority }, { accountId: 'c'.repeat(12), provider: 'z.ai', displayName: 'Fixture z.ai account', status: 'active', priority: 0, models: state.models }] });
if (req.url.endsWith('/accounts')) return send({ accounts: [{ accountId: 'a'.repeat(12), provider: 'claude', displayName: '<img src=x onerror="window.injected=true">', status: 'ready', priority: state.priority }, { accountId: 'c'.repeat(12), provider: 'z.ai', displayName: 'Fixture z.ai account', status: 'active', priority: 0, models: state.models }], ...(providers === 'none' ? {} : { providers }) });
if (req.url.endsWith('/keys')) return send({ keys: [{ keyId: 'b'.repeat(12), management: 'sentinel', agent: null, issuedAt: '2026-11-07T02:24:02.021Z', state: null }] });
if (req.url.endsWith('/apikey/add')) {
state.receivedKey = args.key === 'p4-browser-key';
state.receivedKey = args.key === 'p4-browser-key'; state.keyProvider = args.provider;
await new Promise(r => { state.release = r; }); return send({ added: true });
}
if (req.url.endsWith('/login/start')) return send({ url: 'https://claude.ai/oauth/authorize?state=p4-state', state: 'p4-state' });
@@ -113,3 +114,35 @@ test('settings-s4: Model setup shows no client keys table and reads no keys (des
assert.doesNotMatch(await b.evaluate('document.body.innerText'),/Client keys|Accounts and client keys/);
assert.equal(state.routes.some(r=>r.startsWith('/api/proxy/keys')),false);
});
// #1873 settings-backend-a3: anyone but the instance owner reads no setup status, so the select comes
// from the providers the accounts answer carries (the plugin's list as id, label and sign-in kind).
const selectNow = b => b.evaluate(`(() => { const s = document.querySelector("#proxy-provider"); return { options: [...s.options].map(o => [o.value, o.textContent]),
hidden: s.hidden, help: document.querySelector("#proxy-provider-help").textContent, go: document.querySelector("#proxy-login-go").hidden }; })()`);
test('settings-backend-a3: the select is built from the accounts answer\'s providers, and a key goes to the provider picked', { timeout: 60000 }, async t => {
const { b, state, wait } = await setup(t);
assert.deepEqual((await selectNow(b)).options, publicProviders().map(p => [p.id, `${p.label} (${p.signIn === 'oauth' ? 'subscription' : 'API key'})`]));
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-accounts li[data-account]")].map(li => [li.children[0].textContent, li.children[1].firstChild.textContent])'),
[['Claude', 'Subscription'], ['z.ai', 'API key']], 'a row takes its provider name and kind from the list');
await b.evaluate('(() => { const s = document.querySelector("#proxy-provider"); s.value = "z.ai"; s.dispatchEvent(new Event("change")); document.querySelector("#proxy-apikey input").value = "p4-browser-key"; document.querySelector("#proxy-apikey").requestSubmit(); return true; })()');
for (let n = 0; n < 100 && !state.release; n++) await new Promise(r => setTimeout(r, 20));
assert.equal(state.keyProvider, 'z.ai'); state.release();
await wait('document.querySelector("#proxy-message").textContent.includes("added")');
});
test('settings-backend-a3: a provider the accounts answer leaves out is not in the select', { timeout: 60000 }, async t => {
const { b } = await setup(t, false, null, publicProviders().filter(p => p.id !== 'claude'));
const now = await selectNow(b);
assert.deepEqual(now.options, [['codex', 'ChatGPT / Codex (subscription)'], ['z.ai', 'z.ai (API key)']]);
assert.equal(await b.evaluate('document.querySelector("#proxy-login-go").textContent'), 'Sign in to ChatGPT / Codex');
});
for (const [name, providers] of [['no providers', 'none'], ['an empty list', []]]) {
test(`settings-backend-a3: an accounts answer with ${name} shows no select and says the providers could not be read`, { timeout: 60000 }, async t => {
const { b } = await setup(t, false, null, providers);
assert.deepEqual(await selectNow(b), { options: [], hidden: true, help: 'The providers could not be read, so no account can be added here.', go: true });
assert.equal(await b.evaluate('document.querySelector("#proxy-apikey").hidden'), true);
});
}
test('settings-backend-a3: an accounts read that fails says the providers could not be read', { timeout: 60000 }, async t => {
const { b, wait } = await setup(t, false, '/accounts');
await wait('!/^Reading/.test(document.querySelector("#proxy-provider-help").textContent)');
assert.deepEqual(await selectNow(b), { options: [], hidden: true, help: 'The providers could not be read, so no account can be added here.', go: true });
});
@@ -5,6 +5,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { w15Fixture } from './w15-fixture.mjs';
import { publicProviders } from '../../plugins/model-provider/cliproxy/index.mjs';
const T = '2026-11-11T12:00:00.000Z';
const base = {
@@ -15,7 +16,7 @@ const base = {
fetch: { state: 'idle' }, restart: null, busy: null,
organizations: [{ id: 'acme', proxy: 'shared', catalogue: null }],
ownProxy: { available: false, state: 'not built', reason: 'The configuration has one proxy per instance.' },
next: ['fetch'],
next: ['fetch'], providers: publicProviders(),
};
const fetched = { ...base, release: { ...base.release, fetched: true, verified: true }, next: ['init'] };
const fenced = { ...base, release: fetched.release, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] },
@@ -1,12 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {w15Fixture} from './w15-fixture.mjs';
import {publicProviders} from '../../plugins/model-provider/cliproxy/index.mjs';
const rev='a'.repeat(64), long='a'.repeat(64);
const instances={revision:rev,launch:true,instances:{pm:{definition:'coder',launched:true,kept:false,running:['run-1'],protected:false,endProtected:false},[long]:{definition:'coder',launched:true,kept:false,running:[long],protected:false,endProtected:false}},definitions:{coder:{accepted:true,services:[]}},noHire:[],retired:[]};
const launch={revision:rev,models:{opus:{provider:'anthropic',model:'opus'}},limits:{},usage:{},assistants:{assistant:{definition:'assistant',vars:{},tracker:null}}};
const routes={revision:rev,harnesses:['claude-code','codex'],models:['opus'],levels:{'claude-code':['high','xhigh'],codex:['high','xhigh']},instances:{pm:{harness:'claude-code',model:'opus',thinking:'high'}}};
const scenario={'/api/config':{devOwner:true,send:true,decide:true,edit:true},'/api/settings':{launch,notifier:{binding:null}},'/api/bus/instances':{rows:[instances]},'/api/bus/routes':{rows:[routes]},'/api/bus/names':{rows:[{instance:'assistant',name:'Piper'}]},'/api/bus/limits':{rows:[]},'/api/bus/usage':{rows:[]},'/api/proxy/accounts':{accounts:[{accountId:'fixture',displayName:'Fixture',provider:'claude',status:'ready',priority:100}]},'/api/proxy/keys':{keys:[]}};
const scenario={'/api/config':{devOwner:true,send:true,decide:true,edit:true},'/api/settings':{launch,notifier:{binding:null}},'/api/bus/instances':{rows:[instances]},'/api/bus/routes':{rows:[routes]},'/api/bus/names':{rows:[{instance:'assistant',name:'Piper'}]},'/api/bus/limits':{rows:[]},'/api/bus/usage':{rows:[]},'/api/proxy/accounts':{accounts:[{accountId:'fixture',displayName:'Fixture',provider:'claude',status:'ready',priority:100}],providers:publicProviders()},'/api/proxy/keys':{keys:[]}};
async function page(t,section,width=1440,options={}) {
const x=await w15Fixture(t,{scenario}); const {b,f,wait}=x;
if(options.poll)await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`(()=>{const original=setTimeout;window.setTimeout=(fn,ms,...args)=>{if(ms===10000)window.__pollRefresh=fn;return original(fn,ms,...args)}})()`});
@@ -7,6 +7,7 @@
// Part B is the single-business Console with every API answer explicit (w15-fixture.mjs).
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { publicProviders } from '../../plugins/model-provider/cliproxy/index.mjs';
import { fileURLToPath } from 'node:url';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
@@ -57,7 +58,7 @@ async function orgFixture() {
// The instance owner's flags on /api/config and the model service status, by path suffix (display.js
// scopes some reads under /api/orgs/<id>/). Everything else is the real server.
const SERVICE_UP = { next: ['accounts'], init: { initialized: true, files: [] }, release: { fetched: true, verified: true, version: '8.0.42', panelVersion: '1.26.7' },
unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', port: 18432, listening: true, healthy: true }, fence: { set: false }, initLock: { present: false, blockers: [] }, fetch: { state: 'idle' }, organizations: [], ride: [] };
unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', port: 18432, listening: true, healthy: true }, fence: { set: false }, initLock: { present: false, blockers: [] }, fetch: { state: 'idle' }, organizations: [], ride: [], providers: publicProviders() };
const ownerStub = (service = SERVICE_UP, extra = {}) => `(() => {
const real = window.fetch.bind(window); window.__s4 = ${JSON.stringify({ service, accounts: [], routes: null, posts: {}, ...extra })}; window.__writes = [];
const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
@@ -205,12 +206,53 @@ test('settings-s4 review N8: no paused mark while the service runs and only a fe
// ---- Part B: Model setup ---------------------------------------------------------------------
const T = '2026-11-11T12:00:00.000Z';
// #1873 settings-backend-a3: the provider select and its help text come from status.providers, the
// plugin's list as id, label and sign-in kind. No list, or an empty one, leaves no select and one line.
const selectNow = b => b.evaluate(`(() => { const s = document.querySelector("#proxy-provider"); return { options: [...s.options].map(o => [o.value, o.textContent]),
hidden: s.hidden, labels: [...s.labels].map(l => l.hidden), help: document.querySelector("#proxy-provider-help").textContent, go: document.querySelector("#proxy-login-go").hidden }; })()`);
const READING = '!/^Reading/.test(document.querySelector("#proxy-provider-help")?.textContent ?? "Reading")';
test('settings-backend-a3: the provider select\'s options are status.providers, with the help text built from them', { timeout: 90000 }, async t => {
const { b, wait } = await orgSetup(t, { path: '/#/settings/model-setup' });
await wait(READING);
const now = await selectNow(b);
assert.deepEqual(now.options, SERVICE_UP.providers.map(p => [p.id, `${p.label} (${p.signIn === 'oauth' ? 'subscription' : 'API key'})`]));
assert.deepEqual([now.hidden, now.labels, now.go], [false, [false], false]);
assert.equal(now.help, "Claude and ChatGPT / Codex: you sign in on the provider's site in a new tab. Nothing you type there comes to this page. z.ai: you paste an API key from your z.ai account.");
assert.equal(await b.evaluate('document.querySelector("#proxy-login-go").textContent'), 'Sign in to Claude');
await b.evaluate('(() => { const s = document.querySelector("#proxy-provider"); s.value = "z.ai"; s.dispatchEvent(new Event("change")); return true; })()');
assert.deepEqual(await b.evaluate('[document.querySelector("#proxy-apikey").hidden, document.querySelector("#proxy-login-go").hidden, document.querySelector("#proxy-apikey-label").textContent, document.querySelector("#proxy-apikey-provider").textContent]'),
[false, true, 'z.ai API key', 'z.ai']);
});
test('settings-backend-a3: a provider the status leaves out is gone from the select and its help text', { timeout: 90000 }, async t => {
const { b, wait } = await orgSetup(t, { path: '/#/settings/model-setup', service: { ...SERVICE_UP, providers: SERVICE_UP.providers.filter(p => p.id !== 'codex') } });
await wait(READING);
const now = await selectNow(b);
assert.deepEqual(now.options, [['claude', 'Claude (subscription)'], ['z.ai', 'z.ai (API key)']]);
assert.equal(now.help, "Claude: you sign in on the provider's site in a new tab. Nothing you type there comes to this page. z.ai: you paste an API key from your z.ai account.");
});
for (const [name, providers] of [['no providers field', undefined], ['an empty list', []], ['a list of nothing usable', [{ id: 'x' }, null, 'claude']]]) {
test(`settings-backend-a3: a status with ${name} shows no select and says the providers could not be read`, { timeout: 90000 }, async t => {
const { providers: _, ...rest } = SERVICE_UP;
const { b, wait } = await orgSetup(t, { path: '/#/settings/model-setup', service: providers === undefined ? rest : { ...rest, providers } });
await wait(READING);
const now = await selectNow(b);
assert.deepEqual(now, { options: [], hidden: true, labels: [true], help: 'The providers could not be read, so no account can be added here.', go: true });
assert.equal(await b.evaluate('document.querySelector("#proxy-apikey").hidden'), true);
});
}
test('settings-backend-a3: a status read that fails (an answer that is no status) says the providers could not be read', { timeout: 90000 }, async t => {
const { b, wait } = await orgSetup(t, { path: '/#/settings/model-setup', service: null });
await wait(READING);
assert.deepEqual(await selectNow(b), { options: [], hidden: true, labels: [true], help: 'The providers could not be read, so no account can be added here.', go: true });
});
const fresh = {
release: { fetched: false, verified: false, version: '8.0.42', panelVersion: '1.26.7' },
init: { initialized: false, partial: false, files: [] },
unit: { unit: 'mosaic-proxy.service', installed: false, active: 'inactive' },
fence: { set: false }, initLock: { present: false, clearable: false, blockers: [] }, fetch: { state: 'idle' }, restart: null, busy: null,
organizations: [{ id: 'acme', proxy: 'shared', catalogue: null }], ownProxy: { available: false, state: 'not built', reason: 'One proxy per instance.' }, next: ['fetch'],
providers: publicProviders(),
};
const fetched = { ...fresh, release: { ...fresh.release, fetched: true, verified: true }, fetch: { state: 'done', receipt: { op: 'fetch', time: T, version: '8.0.42' } }, next: ['init'] };
const configured = { ...fetched, init: { initialized: true, partial: false, settings: { port: 18432 }, files: [] }, next: ['unit-install'] };
@@ -149,13 +149,13 @@ test('settings-s5b: Technical details shows when the service key was made, the s
assert.equal(await text('#proxy-setup-history-all'), 'Show all');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-history-older").hidden'), true);
// The lines: read when their box opens, shown as the answer has them, with what was removed.
assert.deepEqual(await reads(), ['GET service-key', 'GET history?limit=25']);
assert.deepEqual(await reads(), ['GET service-key', 'GET history?limit=25', 'GET access']);
await b.evaluate('document.querySelector("#proxy-setup-tech-lines").open = true; true');
await wait('document.querySelector("#proxy-setup-tech-lines pre.setup-log")');
assert.equal(await text('#proxy-setup-tech-lines summary'), 'The service\'s last lines');
assert.equal(await text('#proxy-setup-tech-lines pre.setup-log'), LOG_OK.lines.join('\n'));
assert.equal(await text('#proxy-setup-tech-lines [data-log] p'), 'Mosaic removes anything that looks like a key. It removed something from 1 line. 2 lines were left out.');
assert.deepEqual(await reads(), ['GET service-key', 'GET history?limit=25', 'GET log?lines=20']);
assert.deepEqual(await reads(), ['GET service-key', 'GET history?limit=25', 'GET access', 'GET log?lines=20']);
// Read again reads the lines once more.
await click('#proxy-setup-tech-lines [data-log] button');
await wait('window.__admin.filter(r => r === "GET log?lines=20").length === 2 && document.querySelector("#proxy-setup-tech-lines pre.setup-log")');
@@ -229,7 +229,7 @@ test('settings-s5b: each failed read shows its line with Read again, and Read ag
await b.evaluate('(() => { const r = document.querySelector("#proxy-setup-tech-lines [data-log] button"); r.focus(); r.click(); return true; })()');
await wait('document.querySelector("#proxy-setup-tech-lines pre.setup-log")');
assert.equal(await b.evaluate('document.activeElement?.closest("[data-log]") !== null && document.activeElement.textContent === "Read again"'), true);
assert.deepEqual(await reads(), ['GET service-key', 'GET history?limit=25', 'GET service-key', 'GET history?limit=25', 'GET log?lines=20', 'GET log?lines=20']);
assert.deepEqual(await reads(), ['GET service-key', 'GET history?limit=25', 'GET access', 'GET service-key', 'GET history?limit=25', 'GET log?lines=20', 'GET log?lines=20']);
});
// ---- Owner only -------------------------------------------------------------------------------
@@ -293,7 +293,7 @@ test('settings-s5b: history pages back one page at a time, shows each entry once
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-history-older").hidden'), true);
assert.equal(await b.evaluate('document.activeElement?.id'), 'proxy-setup-history-all');
assert.equal(await text('#proxy-setup-history-message'), '');
assert.deepEqual(await reads(), ['GET service-key', 'GET history?limit=25', 'GET history?limit=25&before=3', 'GET history?limit=25&before=1']);
assert.deepEqual(await reads(), ['GET service-key', 'GET history?limit=25', 'GET access', 'GET history?limit=25&before=3', 'GET history?limit=25&before=1']);
// Closing and opening Technical details starts from the newest page again.
await b.evaluate('document.querySelector("#proxy-setup-tech").open = false; true');
await new Promise(r => setTimeout(r, 100));
@@ -0,0 +1,515 @@
// #1873 settings-s5c (DESIGN.md, mockup models-advanced): Model setup, Advanced, lists the installed
// programs from the status read's programs field and which organizations have each one on; one
// program can be turned off in every organization (POST /api/proxy/admin/programs/off), and the page
// words each organization's outcome. Technical details reads access health per organization
// (GET /api/proxy/admin/access) when it opens. All of it is the instance owner's: a page without
// proxyAdmin shows none of it and sends no /api/proxy/admin/ request.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { fileURLToPath } from 'node:url';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
const LIST = [
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
{ id: 'gamma', label: 'Gamma Home', theme: 'rosewood', busHealthy: true },
{ id: 'lab', label: 'Lab Bench', theme: 'cobalt', busHealthy: true },
];
const VIEW = {
business: 'acme', revision: 'a'.repeat(64), harnesses: ['pi'], models: ['fixture-deterministic'],
providerModels: { 'fixture-deterministic': { module: 'fixture', upstream: 'fixture', model: 'fixture-deterministic' } },
levels: { pi: ['off', 'low'] }, instances: {}, catalogue: { status: 'ready', observedAt: new Date().toISOString(), models: [], notices: [] },
};
async function orgFixture() {
const { checkRootAgents } = await import('../../organization/src/index.mjs');
const rolesDir = fileURLToPath(new URL('../../../roles', import.meta.url));
const root = { state: 'ok', ...checkRootAgents({ agentsVersion: 1, agents: {} }, { rolesDir }) };
const empty = () => Promise.resolve([]);
const member = org => ({
id: org.id, doc: { appearance: { theme: org.theme }, roles: { chief: { definition: 'chief-of-staff' } }, projects: {} },
status: async () => ({ healthy: true, pid: 4242, boot: null }),
options: () => ({ bus: { inbox: empty, agents: empty, 'thread.claims': empty, tasks: empty, usage: () => Promise.resolve({}), limits: () => Promise.resolve({}), decisions: empty }, chat: { threads: empty, projects: empty } }),
});
const organizations = {
list: async () => LIST,
members: async () => LIST.map(member),
resolve: async id => {
const org = LIST.find(o => o.id === id); if (!org) return null;
return {
busHealthy: true,
reads: { business: async () => ({ business: { id, human: 'jason', projects: [], appearance: { theme: org.theme } } }), settings: async () => ({ business: id, release: 'fixture', notifier: {} }), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
bus: { messages: async () => ({ messages: [], unread: 0, total: 0 }), agents: empty, 'thread.claims': empty, inbox: empty, tasks: empty, usage: async () => ({}), routes: async () => ({ ...VIEW, business: id }), instances: async () => ({ business: id, revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {}, instances: {} }) },
chat: { projects: empty, threads: empty },
};
},
};
return { organizations, agentLevels: { loadRoot: () => root, rolesDir, ctx: { configDir: '/cfg', dataRoot: '/data', instance: 'test' } } };
}
// Program names are the read's, not a list the page holds: one of them is made up.
const PROGRAMS = { installed: ['pi', 'zeta-runner'], organizations: [{ id: 'acme', on: ['pi', 'zeta-runner'] }, { id: 'gamma', on: null }, { id: 'lab', on: ['pi'] }] };
const SERVICE_UP = { next: ['accounts'], init: { initialized: true, partial: false, problem: null, settings: { port: 18432, rotateGraceMinutes: 30, firstOutputSeconds: 90 }, files: [] },
release: { fetched: true, verified: true, version: '8.0.42', panelVersion: '1.26.7' },
unit: { unit: 'mosaic-proxy.service', installed: true, active: 'active', port: 18432, listening: true, healthy: true }, fence: { set: false }, initLock: { present: false, blockers: [] }, fetch: { state: 'idle' },
organizations: [], ride: [], programs: PROGRAMS };
const AFTER = { ...SERVICE_UP, programs: { ...PROGRAMS, organizations: [{ id: 'acme', on: ['pi'] }, { id: 'gamma', on: null }, { id: 'lab', on: ['pi'] }] } };
const ACCESS = { organizations: [
{ id: 'acme', health: 'ok', keys: [{ keyId: 'kid-AAAA1111', agent: 'chief', state: 'active', issuedAt: null }], other: 4242, sentinel: 1 },
{ id: 'gamma', health: 'attention', reason: 'proxy-uncertain', keys: [] },
{ id: 'lab', health: 'attention', keys: [{ keyId: 'kid-BBBB2222', agent: 'chief', state: 'active', issuedAt: null }, { keyId: 'kid-CCCC3333', agent: 'writer', state: 'expired', issuedAt: null }], other: 4242 },
{ id: 'north', health: 'missing', keys: [], other: 4242 },
{ id: 'south', health: 'not-riding', keys: [] },
{ id: 'east', health: 'unreadable', reason: 'bus-down', keys: [] },
{ id: 'west', health: 'unreadable', reason: 'no-proxy-client', keys: [] },
{ id: 'up', health: 'unreadable', reason: 'unreadable', keys: [] },
{ id: 'down', keys: [{ keyId: 'kid-DDDD4444', agent: 'chief', state: 'active', issuedAt: null }] },
{ id: 'left', health: 'ok', reason: 'proxy-uncertain', keys: [{ keyId: 'kid-EEEE5555', agent: 'chief', state: 'active', issuedAt: null }] },
{ id: 'right', health: 'ok', keys: [] },
{ id: 'top', health: 'great', keys: [] },
] };
// The owner's flags (or not), the status (a list: each read takes the next one and the last one stays),
// and the admin reads and writes by name. window.__admin records every /api/proxy/admin/ request,
// window.__writes every write anywhere under /proxy/.
const stub = ({ owner = true, status = SERVICE_UP, admin = {} } = {}) => `(() => {
const real = window.fetch.bind(window);
window.__s5c = ${JSON.stringify({ owner, status: Array.isArray(status) ? status : [status], admin })}; window.__admin = []; window.__writes = [];
const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
const next = list => Array.isArray(list) ? (list.length > 1 ? list.shift() : list[0]) : list;
window.fetch = async (input, init = {}) => {
const url = new URL(typeof input === 'string' ? input : input.url, location.href), path = url.pathname, method = (init.method || 'GET').toUpperCase();
const at = path.indexOf('/proxy/admin/');
if (at >= 0) {
const name = path.slice(at + 13) + url.search; window.__admin.push(method + ' ' + name);
if (method !== 'GET') window.__writes.push({ path, body: init.body ?? null });
if (name === 'status') { const s = next(__s5c.status); if (s === null || typeof s !== 'object') return json(s); if (typeof s.raw === 'string') return new Response(s.raw, { status: 200, headers: { 'content-type': 'text/html' } }); return s.status ? json(s.body, s.status) : json(s); }
const a = next(__s5c.admin[method === 'GET' ? name : method + ' ' + name]);
if (!a) return json({ error: 'fixture-unexpected-api' }, 403);
if (a.throws) throw new TypeError('Failed to fetch');
return a.status ? json(a.body, a.status) : json(a);
}
if (method !== 'GET' && /\\/proxy\\//.test(path)) { window.__writes.push({ path, body: init.body ?? null }); return json({ error: 'stub' }, 500); }
if (method !== 'GET') return real(input, init);
if (/\\/api\\/(orgs\\/[^/]+\\/)?config$/.test(path)) { const c = await (await real(input, init)).json(); return json({ ...c, orgSetup: true, proxyAdmin: __s5c.owner, proxyAdminSend: __s5c.owner }); }
if (path.endsWith('/proxy/plugins')) return json({ revision: 'b'.repeat(64), available: { harness: ['pi'], 'model-provider': ['fixture', 'cliproxy'] }, plugins: { harness: ['pi'], 'model-provider': ['fixture'] } });
if (path.endsWith('/proxy/accounts')) return json({ accounts: [] });
if (path.endsWith('/proxy/keys')) return json({ keys: [] });
if (path.endsWith('/triage/route')) return json({ route: null });
return real(input, init);
};
})();`;
async function setup(t, { path = '/#/settings/model-setup', viewport = [1440, 900], ...options } = {}) {
const { organizations, agentLevels } = await orgFixture();
const server = await startServer({ port: 0, sso: createDevOwner(), organizations, agentLevels, triage: null, send: async () => ({}), log: () => {} });
t.after(() => close(server));
const b = await browser({ machine: false }); t.after(() => b.close());
await b.viewport(...viewport);
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: stub(options) });
await b.navigate(`http://127.0.0.1:${server.address().port}${path}`);
const wait = expression => b.evaluate(`(async()=>{for(let i=0;i<250;i++){if(${expression})return true;await new Promise(r=>setTimeout(r,30))}throw Error("wait failed: "+${JSON.stringify(expression)}+" HASH "+location.hash)})()`);
const text = sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.textContent ?? null`);
const click = sel => b.evaluate(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) throw Error("no ${sel.replace(/"/g, '')}"); el.click(); return true; })()`);
const admin = () => b.evaluate('window.__admin');
return { b, wait, text, click, admin };
}
const READY = 'document.querySelector("#proxy-setup-state dd") && !document.querySelector("#setup-step-service").hidden && !document.querySelector("#proxy-setup-advanced").hidden';
const openAdvanced = b => b.evaluate('(() => { document.querySelector("#proxy-setup-advanced").open = true; return true; })()');
const openTech = b => b.evaluate('(() => { document.querySelector("#proxy-setup-tech").open = true; return true; })()');
const programs = b => b.evaluate('[...document.querySelectorAll("#proxy-setup-programs > li")].map(li => ({ name: li.dataset.program ?? null, text: li.querySelector(".proxy-program-orgs")?.textContent ?? li.textContent }))');
const outcomes = b => b.evaluate('[...document.querySelectorAll("#proxy-setup-programs-result li")].map(li => li.textContent)');
const access = b => b.evaluate('[...document.querySelectorAll("#proxy-setup-access li")].map(li => ({ text: li.textContent, ready: li.dataset.access }))');
const KEY_TEXT = /ms[kotp]-[A-Za-z0-9_-]{4,}/i;
// Technical details' other reads, so a shot shows them as they read.
const T = n => new Date(Date.UTC(2026, 10, 19, 9, n)).toISOString();
const TECH = { 'service-key': { madeAt: T(3), renewedAt: null, renewal: 'not-built', problem: null }, 'history?limit=25': { entries: [{ op: 'unit.start', time: T(4), user: 'jason' }, { op: 'init', time: T(2), user: 'jason' }], next: null } };
const OFF_PI = { name: 'pi', results: [{ id: 'acme', outcome: 'in-use' }, { id: 'gamma', outcome: 'bus-down' }, { id: 'lab', outcome: 'last-program' }], receipt: null };
// ---- The list -------------------------------------------------------------------------------
test('settings-s5c: Advanced lists the installed programs from the status read and which organizations have each one on, by display name', { timeout: 90000 }, async t => {
const { b, wait, admin } = await setup(t);
await wait(READY); await openAdvanced(b);
await wait('document.querySelectorAll("#proxy-setup-programs > li[data-program]").length === 2');
assert.deepEqual(await programs(b), [
{ name: 'pi', text: 'On in Acme Studio and Lab Bench. Not known in Gamma Home: its list could not be read.' },
{ name: 'zeta-runner', text: 'On in Acme Studio. Off in Lab Bench. Not known in Gamma Home: its list could not be read.' },
]);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-setup-programs .proxy-program-name")].map(n => n.textContent)'), ['pi', 'zeta-runner']);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-program-off]")].map(n => n.getAttribute("aria-label"))'), ['Turn off pi for every organization', 'Turn off zeta-runner for every organization']);
assert.doesNotMatch(await b.evaluate('document.querySelector("#proxy-setup-advanced").textContent'), /Turning a program off for every organization is not built/);
// Opening Advanced reads nothing more: the list is the status read's.
assert.deepEqual((await admin()).filter(r => r !== 'GET status'), []);
});
test('settings-s5c: a null list reads as not known, never off; a list the read could not give says so', { timeout: 90000 }, async t => {
{
const status = { ...SERVICE_UP, programs: { installed: ['pi'], organizations: [{ id: 'gamma', on: null }, { id: 'acme', on: ['pi'] }] } };
const { b, wait } = await setup(t, { status });
await wait(READY); await openAdvanced(b);
await wait('document.querySelector("#proxy-setup-programs > li[data-program]")');
const [pi] = await programs(b);
assert.equal(pi.text, 'On in Acme Studio. Not known in Gamma Home: its list could not be read.');
assert.doesNotMatch(pi.text, /Off in/);
}
for (const [programsField, line] of [
[{ installed: ['pi'], organizations: null }, 'Which organizations have it on could not be read.'],
[{ installed: null, organizations: [] }, 'The installed programs could not be read.'],
[undefined, 'The programs could not be read.'],
[{ installed: [], organizations: [] }, 'No programs are installed.'],
]) {
const { b, wait } = await setup(t, { status: { ...SERVICE_UP, programs: programsField } });
await wait(READY); await openAdvanced(b);
await wait(`document.querySelector("#proxy-setup-programs")?.textContent.includes(${JSON.stringify(line)})`);
assert.doesNotMatch(await b.evaluate('document.querySelector("#proxy-setup-programs").textContent'), /Off in|On in no/);
}
});
// ---- Turn off for every organization ----------------------------------------------------------
test('settings-s5c: the confirm names the program, and Cancel sends nothing', { timeout: 90000 }, async t => {
const { b, wait, text, click, admin } = await setup(t, { admin: { 'POST programs/off': OFF_PI } });
await wait(READY); await openAdvanced(b);
await wait('document.querySelector("[data-program-off=pi]")');
await click('[data-program-off=pi]');
await wait('document.querySelector("#proxy-setup-programs-yes")');
assert.match(await text('#proxy-setup-programs-ask'), /^Turn off pi in every organization\?/);
assert.equal(await text('#proxy-setup-programs-yes'), 'Turn off pi');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-programs-yes").closest("li").dataset.program'), 'pi');
assert.equal(await b.evaluate('document.activeElement?.id'), 'proxy-setup-programs-yes');
await click('#proxy-setup-programs-no');
await wait('!document.querySelector("#proxy-setup-programs-yes")');
await new Promise(r => setTimeout(r, 300));
assert.deepEqual(await b.evaluate('window.__writes'), []);
assert.deepEqual((await admin()).filter(r => r !== 'GET status'), []);
assert.equal(await b.evaluate('document.activeElement?.dataset.programOff'), 'pi', 'focus goes back to the button');
// Confirming sends the one name.
await click('[data-program-off=pi]'); await wait('document.querySelector("#proxy-setup-programs-yes")');
await click('#proxy-setup-programs-yes');
await wait('document.querySelectorAll("#proxy-setup-programs-result li").length === 3');
assert.deepEqual(await b.evaluate('window.__writes.map(w => [w.path.replace(/^.*(\\/proxy\\/admin\\/)/, "$1"), JSON.parse(w.body)])'), [['/proxy/admin/programs/off', { name: 'pi' }]]);
});
test('settings-s5c: each outcome id renders its line, by display name', { timeout: 90000 }, async t => {
const results = [
{ id: 'acme', outcome: 'off' }, { id: 'gamma', outcome: 'already-off' }, { id: 'lab', outcome: 'in-use' },
{ id: 'o4', outcome: 'last-program' }, { id: 'o5', outcome: 'bus-down' }, { id: 'o6', outcome: 'unreadable' },
{ id: 'o7', outcome: 'failed:revision-conflict' }, { id: 'o8', outcome: 'failed:outcome-unknown' }, { id: 'o9', outcome: 'failed:plugins-refused' },
{ id: 'o10', outcome: 'sideways' }, { id: 'o11' },
];
const { b, wait, click } = await setup(t, { admin: { 'POST programs/off': { name: 'zeta-runner', results, receipt: null } } });
await wait(READY); await openAdvanced(b);
await wait('document.querySelector("[data-program-off=zeta-runner]")');
await click('[data-program-off=zeta-runner]'); await wait('document.querySelector("#proxy-setup-programs-yes")'); await click('#proxy-setup-programs-yes');
await wait('document.querySelectorAll("#proxy-setup-programs-result li").length === 11');
assert.equal(await b.evaluate('document.querySelector(".proxy-programs-result-title").textContent'), 'Turn off zeta-runner: what happened in each organization.');
const lines = await outcomes(b);
await wait('/The list above is read again and shows what is on now\./.test(document.querySelector("#proxy-setup-programs-result").textContent)');
assert.deepEqual(lines, [
'Acme Studio: Turned off.',
'Gamma Home: It was already off. Nothing changed.',
'Lab Bench: Kept on. Something there still uses it: a role route, a fallback or an agent.',
'o4: Kept on. It is the only program on there.',
'o5: Not changed. Its programs could not be read.',
'o6: Not changed. Something Mosaic needed to check could not be read.',
'o7: Not changed. It changed while Mosaic was checking. Try again.',
'o8: May have changed. The change did not answer in time.',
'o9: Not changed. It refused the change (plugins-refused).',
'o10: Not known. The answer did not say what happened.',
'o11: Not known. The answer did not say what happened.',
]);
// bus-down does not say the organization is stopped.
assert.doesNotMatch(lines[4], /stop|not running|down/i);
});
test('settings-s5c: busy and a failed request each render a plain line, and the status is read again after each', { timeout: 90000 }, async t => {
const answers = [
{ status: 409, body: { error: 'proxy-admin-busy' } },
{ status: 500, body: { error: 'outcome-unknown' } },
{ status: 400, body: { error: 'invalid-request' } },
{ throws: true },
];
const { b, wait, click, admin } = await setup(t, { admin: { 'POST programs/off': answers } });
await wait(READY); await openAdvanced(b);
const lines = [];
for (let i = 0; i < answers.length; i++) {
await wait('document.querySelector("[data-program-off=pi]") && !document.querySelector("[data-program-off=pi]").disabled');
const before = (await admin()).filter(r => r === 'GET status').length;
await click('[data-program-off=pi]'); await wait('document.querySelector("#proxy-setup-programs-yes")'); await click('#proxy-setup-programs-yes');
await wait(`window.__admin.filter(r => r === "POST programs/off").length === ${i + 1} && window.__admin.lastIndexOf("GET status") > window.__admin.lastIndexOf("POST programs/off") && /The list above is read again/.test(document.querySelector("#proxy-setup-programs-result").textContent)`);
assert.equal((await admin()).filter(r => r === 'GET status').length, before + 1);
lines.push([await b.evaluate('document.querySelector("#proxy-setup-programs-result").className'), await b.evaluate('document.querySelector("#proxy-setup-programs-result").textContent')]);
}
assert.deepEqual(lines, [
['proxy-programs-result banner ref', 'pi was not turned off. Another setup action is running. Wait for it to finish, then try again.The list above is read again and shows what is on now.'],
['proxy-programs-result banner err', 'Turning off pi may not have finished, so some organizations may have changed. The outcome is unknown. Check the status before retrying. (outcome-unknown)The list above is read again and shows what is on now.'],
['proxy-programs-result banner err', 'pi was not turned off. The Console refused the request: the program is not in its installed list, or that list could not be read. (invalid-request)The list above is read again and shows what is on now.'],
['proxy-programs-result banner err', 'Turning off pi may not have finished, so some organizations may have changed. The Console did not answer.The list above is read again and shows what is on now.'],
]);
});
test('settings-s5c: after an off the page reads the status again and shows the new list; focus goes to the result', { timeout: 90000 }, async t => {
const { b, wait, click, admin } = await setup(t, { status: [SERVICE_UP, SERVICE_UP, AFTER], admin: { 'POST programs/off': { name: 'zeta-runner', results: [{ id: 'acme', outcome: 'off' }, { id: 'gamma', outcome: 'bus-down' }, { id: 'lab', outcome: 'already-off' }], receipt: null } } });
await wait(READY); await openAdvanced(b);
await wait('document.querySelector("[data-program-off=zeta-runner]")');
const before = (await admin()).filter(r => r === 'GET status').length;
await click('[data-program-off=zeta-runner]'); await wait('document.querySelector("#proxy-setup-programs-yes")');
await b.evaluate('document.querySelector("#proxy-setup-programs-yes").focus(); document.querySelector("#proxy-setup-programs-yes").click(); true');
await wait('document.querySelectorAll("#proxy-setup-programs-result li").length === 3');
await wait(`window.__admin.filter(r => r === "GET status").length > ${before}`);
const order = await admin();
assert.ok(order.lastIndexOf('GET status') > order.indexOf('POST programs/off'), JSON.stringify(order));
await wait('document.querySelector("li[data-program=zeta-runner] .proxy-program-orgs")?.textContent.startsWith("On in no organization.")');
assert.equal((await programs(b))[1].text, 'On in no organization. Off in Acme Studio and Lab Bench. Not known in Gamma Home: its list could not be read.');
await new Promise(r => setTimeout(r, 300));
assert.equal(await b.evaluate('document.activeElement?.id'), 'proxy-setup-programs-result');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-programs-result").tabIndex'), -1);
});
test('settings-s5c: focus goes to the result after a busy answer too', { timeout: 90000 }, async t => {
const { b, wait, click } = await setup(t, { admin: { 'POST programs/off': { status: 409, body: { error: 'proxy-admin-busy' } } } });
await wait(READY); await openAdvanced(b);
await wait('document.querySelector("[data-program-off=pi]")');
await click('[data-program-off=pi]'); await wait('document.querySelector("#proxy-setup-programs-yes")'); await click('#proxy-setup-programs-yes');
await wait('/was not turned off/.test(document.querySelector("#proxy-setup-programs-result").textContent)');
await new Promise(r => setTimeout(r, 300));
assert.equal(await b.evaluate('document.activeElement?.id'), 'proxy-setup-programs-result');
});
test('settings-s5c: when the status read after an off fails, or answers with no status, the result says the list may be out of date, and Read again reads it', { timeout: 180000 }, async t => {
// A refusal, and three answers that are 200 but not a status: null, an empty object, a page that is not JSON.
for (const down of [{ status: 503, body: { error: 'outcome-unknown' } }, null, {}, { raw: '<html><body>Gateway</body></html>' }]) {
const { b, wait, click, admin } = await setup(t, { admin: { 'POST programs/off': { name: 'zeta-runner', results: [{ id: 'acme', outcome: 'failed:outcome-unknown' }], receipt: null } } });
await wait(READY); await openAdvanced(b);
await wait('document.querySelector("[data-program-off=zeta-runner]")');
const before = (await admin()).filter(r => r === 'GET status').length;
await b.evaluate(`window.__s5c.status = ${JSON.stringify([down, AFTER])}; true`);
await click('[data-program-off=zeta-runner]'); await wait('document.querySelector("#proxy-setup-programs-yes")'); await click('#proxy-setup-programs-yes');
await wait('document.querySelector("#proxy-setup-programs-reread")');
const shown = await b.evaluate('document.querySelector("#proxy-setup-programs-result").textContent');
assert.match(shown, /The list above could not be read again, so it may be out of date\./);
assert.doesNotMatch(shown, /shows what is on now/);
// The old list still shows, and still says so only as what was last read.
assert.match((await programs(b))[1].text, /^On in Acme Studio\./);
await b.evaluate('document.querySelector("#proxy-setup-programs-reread").focus(); document.querySelector("#proxy-setup-programs-reread").click(); true');
await wait('/The list above is read again and shows what is on now\./.test(document.querySelector("#proxy-setup-programs-result").textContent)');
assert.equal((await admin()).filter(r => r === 'GET status').length, before + 2);
assert.equal((await programs(b))[1].text, 'On in no organization. Off in Acme Studio and Lab Bench. Not known in Gamma Home: its list could not be read.');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-programs-reread")'), null);
assert.equal(await b.evaluate('document.activeElement?.id'), 'proxy-setup-programs-result');
}
});
test('settings-s5c: a status read that drops the program being asked about, or cannot list programs, drops the question and frees the buttons', { timeout: 90000 }, async t => {
const RUNNING = { ...SERVICE_UP, fetch: { state: 'running', step: 'download' } };
for (const dropped of [{ ...SERVICE_UP, programs: { ...PROGRAMS, installed: ['pi'] } }, { ...SERVICE_UP, programs: null }, { ...SERVICE_UP, programs: { ...PROGRAMS, installed: ['pi'] } }]) {
const { b, wait, click } = await setup(t, { status: [RUNNING, RUNNING, RUNNING, RUNNING, dropped] });
await wait(READY); await openAdvanced(b);
await wait('document.querySelector("[data-program-off=zeta-runner]")');
await click('[data-program-off=zeta-runner]'); await wait('document.querySelector("#proxy-setup-programs-yes")');
assert.equal(await b.evaluate('document.querySelector("[data-program-off=pi]").disabled'), true);
await wait('!document.querySelector("li[data-program=zeta-runner]")');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-programs-yes")'), null);
if (dropped.programs) {
assert.equal(await b.evaluate('document.querySelector("[data-program-off=pi]").disabled'), false);
await click('[data-program-off=pi]'); await wait('document.querySelector("#proxy-setup-programs-yes")');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-programs-yes").closest("li").dataset.program'), 'pi');
}
}
});
test('settings-s5c: a refusal code named like an object property shows as its code, never as page source', { timeout: 90000 }, async t => {
const refused = { status: 400, body: { error: 'constructor' } };
const { b, wait, click, text } = await setup(t, { admin: { access: refused, 'POST programs/off': refused } });
await wait(READY); await openAdvanced(b); await openTech(b);
await wait('!document.querySelector("#proxy-setup-access-retry").hidden && document.querySelector("[data-program-off=pi]")');
await click('[data-program-off=pi]'); await wait('document.querySelector("#proxy-setup-programs-yes")'); await click('#proxy-setup-programs-yes');
await wait('/may not have finished/.test(document.querySelector("#proxy-setup-programs-result").textContent)');
const page = await b.evaluate('document.querySelector("#proxy-setup").textContent');
assert.doesNotMatch(page, /function|native code|\[object/);
assert.match(await text('#proxy-setup-access-message'), /^Access could not be read\. /);
});
// ---- Access ----------------------------------------------------------------------------------
test('settings-s5c: Technical details reads access when it opens and words each health; only ok with every key active reads Ready', { timeout: 90000 }, async t => {
const { b, wait, admin } = await setup(t, { admin: { access: ACCESS } });
await wait(READY);
await new Promise(r => setTimeout(r, 300));
assert.equal((await admin()).includes('GET access'), false, 'access is not read before Technical details opens');
await openTech(b);
await wait(`document.querySelectorAll("#proxy-setup-access li").length === ${ACCESS.organizations.length}`);
assert.equal((await admin()).filter(r => r === 'GET access').length, 1);
assert.deepEqual(await access(b), [
{ text: 'Acme StudioReady', ready: 'ready' },
{ text: 'Gamma HomeNot sureThe model service did not answer clearly, so Mosaic can\'t tell whether its access works.', ready: 'not-ready' },
{ text: 'Lab BenchNeeds attentionSome of its access is not active.', ready: 'not-ready' },
{ text: 'northNone yetNo agent here has access to your models yet.', ready: 'not-ready' },
{ text: 'southNot usedIt does not use your models.', ready: 'not-ready' },
{ text: 'eastCould not be readIts bus did not answer.', ready: 'not-ready' },
{ text: 'westCould not be readIts bus has no model service client set up.', ready: 'not-ready' },
{ text: 'upCould not be readIts answer about access could not be read.', ready: 'not-ready' },
{ text: 'downNot knownThe answer did not say.', ready: 'not-ready' },
{ text: 'leftNot knownThe answer did not agree with itself.', ready: 'not-ready' },
{ text: 'rightNot knownThe answer did not agree with itself.', ready: 'not-ready' },
{ text: 'topNot knownThe answer did not say.', ready: 'not-ready' },
]);
const shown = await b.evaluate('document.querySelector(".proxy-setup-access").textContent');
assert.equal((shown.match(/Ready/g) ?? []).length, 1);
assert.doesNotMatch(shown, /kid-|4242|sentinel|chief|writer|expired/);
assert.doesNotMatch(await b.evaluate('document.querySelector(".proxy-setup-access").textContent'), /bus is (stopped|down)|stopped/i);
});
test('settings-s5c: a failed access read shows a plain line with Read again, and Read again reads it', { timeout: 90000 }, async t => {
const { b, wait, text, admin } = await setup(t, { admin: { access: [{ status: 503, body: { error: 'outcome-unknown' } }, { status: 200, body: { organizations: 'nope' } }, ACCESS] } });
await wait(READY); await openTech(b);
await wait('!document.querySelector("#proxy-setup-access-retry").hidden');
assert.equal(await text('#proxy-setup-access-message'), 'Access could not be read. The host could not read access. (outcome-unknown)');
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-access-message").className'), 'banner err');
assert.equal(await b.evaluate('document.querySelectorAll("#proxy-setup-access li").length'), 0);
await b.evaluate('document.querySelector("#proxy-setup-access-retry").focus(); document.querySelector("#proxy-setup-access-retry").click(); true');
await wait('window.__admin.filter(r => r === "GET access").length === 2'); await new Promise(r => setTimeout(r, 400));
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-access-retry").hidden'), false);
assert.equal(await text('#proxy-setup-access-message'), 'Access could not be read. The host could not read access. (outcome-unknown)');
assert.equal(await b.evaluate('document.querySelectorAll("#proxy-setup-access li").length'), 0, 'a shape the page does not know never reads as Ready');
assert.equal(await b.evaluate('document.activeElement?.id'), 'proxy-setup-access-retry');
await b.evaluate('document.querySelector("#proxy-setup-access-retry").focus(); document.querySelector("#proxy-setup-access-retry").click(); true');
await wait(`document.querySelectorAll("#proxy-setup-access li").length === ${ACCESS.organizations.length}`);
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-access-retry").hidden'), true);
assert.equal(await b.evaluate('document.activeElement?.id'), 'proxy-setup-access-title', 'focus lands on the answer');
assert.equal((await admin()).filter(r => r === 'GET access').length, 3);
});
// ---- Owner only ------------------------------------------------------------------------------
test('settings-s5c: a page that is not the instance owner\'s shows none of it and sends no request to programs or access', { timeout: 90000 }, async t => {
// The owner's page, as the control.
{
const { b, wait } = await setup(t, { admin: { access: ACCESS } });
await wait(READY); await openAdvanced(b); await openTech(b);
await wait(`document.querySelectorAll("[data-program-off]").length === 2 && document.querySelectorAll("#proxy-setup-access li").length === ${ACCESS.organizations.length}`);
}
const { b, wait } = await setup(t, { owner: false, admin: { access: ACCESS, 'POST programs/off': OFF_PI } });
await wait('window.MosaicProxy && document.querySelector("#proxy-setup") && document.querySelector("#settings-page-title")');
await new Promise(r => setTimeout(r, 800));
await b.evaluate('document.querySelectorAll("#proxy-setup details").forEach(d => { d.open = true; }); true');
await new Promise(r => setTimeout(r, 800));
const sent = await b.evaluate('window.__admin');
assert.deepEqual(sent, []);
assert.equal(sent.some(r => /programs|access/.test(r)), false);
const shown = sel => b.evaluate(`(() => { const e = document.querySelector(${JSON.stringify(sel)}); return !!e && e.getClientRects().length > 0; })()`);
for (const sel of ['#proxy-setup-programs', '#proxy-setup-programs-result', '#proxy-setup-access', '#proxy-setup-access-message', '#proxy-setup-access-retry', '.proxy-setup-access'])
assert.equal(await shown(sel), false, `${sel} is not shown`);
assert.equal(await b.evaluate('document.querySelectorAll("[data-program-off], #proxy-setup-access li").length'), 0);
assert.doesNotMatch(await b.evaluate('document.body.innerText'), /Turn off for every organization|Programs that drive models|Access/);
});
// ---- No key text -----------------------------------------------------------------------------
test('settings-s5c: no key text reaches the page, even from a fixture answer that holds it in an unexpected field', { timeout: 90000 }, async t => {
const K = s => `${s}-abcdefghijklmnop`;
const status = { ...SERVICE_UP, programs: { installed: ['pi', K('msk')], organizations: [{ id: 'acme', on: ['pi', K('msk')] }, { id: K('mso'), on: ['pi'] }] } };
const off = { name: 'pi', receipt: { time: 'x', op: 'programs.off', name: K('mst'), results: [] }, results: [{ id: K('msp'), outcome: 'off' }, { id: 'acme', outcome: `failed:${K('msk')}` }, { id: 'gamma', outcome: K('mso') }] };
const accessAnswer = { organizations: [
{ id: K('msk'), health: 'ok', keys: [{ keyId: K('msk'), agent: K('msp'), state: 'active', issuedAt: null }] },
{ id: 'acme', health: K('mso'), reason: K('mst'), keys: [], other: 3 },
{ id: 'gamma', health: 'unreadable', reason: K('msk'), keys: [{ keyId: K('mst') }] },
] };
const { b, wait, click } = await setup(t, { status, admin: { access: accessAnswer, 'POST programs/off': off } });
await wait(READY); await openAdvanced(b); await openTech(b);
await wait('document.querySelectorAll("#proxy-setup-access li").length === 3 && document.querySelector("[data-program-off=pi]")');
await click('[data-program-off=pi]'); await wait('document.querySelector("#proxy-setup-programs-yes")'); await click('#proxy-setup-programs-yes');
await wait('document.querySelectorAll("#proxy-setup-programs-result li").length === 3');
const page = await b.evaluate('document.querySelector("#proxy-setup").textContent + "\\n" + document.body.innerText + "\\n" + [...document.querySelectorAll("#proxy-setup [aria-label], #proxy-setup [data-program], #proxy-setup [data-program-off], #proxy-setup [data-outcome]")].map(e => [e.getAttribute("aria-label"), e.dataset.program, e.dataset.programOff, e.dataset.outcome].join(" ")).join("\\n")');
assert.doesNotMatch(page, KEY_TEXT);
// What the page shows in their place.
assert.equal(await b.evaluate('document.querySelectorAll("#proxy-setup-programs > li[data-program]").length'), 1);
assert.match(await b.evaluate('document.querySelector("#proxy-setup-programs").textContent'), /One or more programs have a name this page does not show\./);
assert.match((await programs(b))[0].text, /^On in Acme Studio and An organization Mosaic can't name\.$/);
assert.deepEqual(await outcomes(b), [
'An organization Mosaic can\'t name: Turned off.',
'Acme Studio: Not changed. It refused the change, with a code this page does not show.',
'Gamma Home: Not known. The answer did not say what happened.',
]);
assert.deepEqual(await access(b), [
{ text: 'An organization Mosaic can\'t nameReady', ready: 'ready' },
{ text: 'Acme StudioNot knownThe answer did not say.', ready: 'not-ready' },
{ text: 'Gamma HomeCould not be read', ready: 'not-ready' },
]);
});
test('settings-s5c: a refusal whose code is shaped like a key is not shown', { timeout: 90000 }, async t => {
const refused = { status: 400, body: { error: 'msk-abcdefghijklmnop' } };
const { b, wait, click } = await setup(t, { admin: { access: refused, 'POST programs/off': refused } });
await wait(READY); await openAdvanced(b); await openTech(b);
await wait('!document.querySelector("#proxy-setup-access-retry").hidden && document.querySelector("[data-program-off=pi]")');
await click('[data-program-off=pi]'); await wait('document.querySelector("#proxy-setup-programs-yes")'); await click('#proxy-setup-programs-yes');
await wait('/turned off|may not have finished/.test(document.querySelector("#proxy-setup-programs-result").textContent)');
const page = await b.evaluate('document.querySelector("#proxy-setup").textContent + "\\n" + document.body.innerText');
assert.doesNotMatch(page, KEY_TEXT);
assert.equal(await b.evaluate('document.querySelector("#proxy-setup-access-message").textContent'), 'Access could not be read. The Console refused the read.');
});
// ---- Shots ------------------------------------------------------------------------------------
test('shots', { timeout: 900000, skip: !process.env.MOSAIC_UX_SHOTS }, async t => {
const { mkdir, writeFile } = await import('node:fs/promises');
const { join } = await import('node:path');
const dir = process.env.MOSAIC_UX_SHOTS; await mkdir(dir, { recursive: true });
const settle = () => new Promise(r => setTimeout(r, 1000));
const mixed = { name: 'zeta-runner', results: [{ id: 'acme', outcome: 'off' }, { id: 'gamma', outcome: 'bus-down' }, { id: 'lab', outcome: 'failed:outcome-unknown' }], receipt: null };
const off = async (b, wait, name) => {
await wait(`document.querySelector("[data-program-off=${name}]")`);
await b.evaluate(`document.querySelector("[data-program-off=${name}]").click(); true`);
await wait('document.querySelector("#proxy-setup-programs-yes")');
};
const SHOTS = [
{ name: 'advanced-programs', after: async b => openAdvanced(b), ready: 'document.querySelector("[data-program-off]")' },
{ name: 'advanced-confirm', after: async (b, wait) => { await openAdvanced(b); await off(b, wait, 'zeta-runner'); } },
{ name: 'advanced-result', options: { status: [SERVICE_UP, SERVICE_UP, AFTER], admin: { 'POST programs/off': mixed } },
after: async (b, wait) => { await openAdvanced(b); await off(b, wait, 'zeta-runner'); await b.evaluate('document.querySelector("#proxy-setup-programs-yes").click(); true'); await wait('document.querySelectorAll("#proxy-setup-programs-result li").length === 3'); } },
{ name: 'advanced-busy', options: { admin: { 'POST programs/off': { status: 409, body: { error: 'proxy-admin-busy' } } } },
after: async (b, wait) => { await openAdvanced(b); await off(b, wait, 'pi'); await b.evaluate('document.querySelector("#proxy-setup-programs-yes").click(); true'); await wait('/was not turned off/.test(document.querySelector("#proxy-setup-programs-result").textContent)'); } },
{ name: 'technical-access', options: { admin: { ...TECH, access: ACCESS } },
after: async (b, wait) => { await openTech(b); await wait(`document.querySelectorAll("#proxy-setup-access li").length === ${ACCESS.organizations.length}`); } },
{ name: 'technical-access-failed', options: { admin: { ...TECH, access: { status: 503, body: { error: 'outcome-unknown' } } } },
after: async (b, wait) => { await openTech(b); await wait('!document.querySelector("#proxy-setup-access-retry").hidden'); } },
];
const report = [];
for (const shot of SHOTS) for (const scheme of ['light', 'dark']) for (const width of [390, 1440]) {
const { b, wait } = await setup(t, { ...(shot.options ?? {}), viewport: [width, width === 390 ? 844 : 900] });
await b.call('Emulation.setScrollbarsHidden', { hidden: true });
await b.call('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });
await wait(`(${READY}) && !!window.MosaicAppearance`);
await b.evaluate(`window.MosaicAppearance.ready.then(() => window.MosaicAppearance.set({ mode: ${JSON.stringify(scheme)} }))`);
await shot.after(b, wait);
if (shot.ready) await wait(shot.ready);
await settle();
const sideways = await b.evaluate('document.documentElement.scrollWidth > document.documentElement.clientWidth');
const noRing = [], seen = new Set();
for (let i = 0; i < 200; i++) {
await b.call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 });
await b.call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 });
const r = await b.evaluate(`(() => { const e = document.activeElement; if (!e || e === document.body) return null; const cs = getComputedStyle(e);
const ring = (cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) || (cs.boxShadow && cs.boxShadow !== 'none');
return { key: e.id || e.dataset.programOff || e.getAttribute('href') || e.tagName + ':' + (e.textContent || '').trim().slice(0, 30), ring }; })()`);
if (!r || seen.has(r.key)) break; seen.add(r.key);
if (!r.ring) noRing.push(r.key);
}
// The result box takes focus from code, not Tab: check its ring too.
const resultRing = await b.evaluate(`(() => { const e = document.querySelector("#proxy-setup-programs-result"); if (e.hidden) return null; e.focus(); const cs = getComputedStyle(e);
return (cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) || (cs.boxShadow && cs.boxShadow !== 'none'); })()`);
if (resultRing === false) noRing.push('proxy-setup-programs-result');
await b.evaluate('document.activeElement?.blur(); window.scrollTo(0, 0); true'); await settle();
const file = `${shot.name}-${width}-${scheme}.png`;
let metrics = await b.call('Page.getLayoutMetrics'), size = metrics.cssContentSize || metrics.contentSize;
await b.viewport(width, Math.ceil(size.height)); await settle();
metrics = await b.call('Page.getLayoutMetrics'); size = metrics.cssContentSize || metrics.contentSize;
const { data } = await b.call('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true, clip: { x: 0, y: 0, width: Math.ceil(size.width), height: Math.ceil(size.height), scale: 1 } });
await writeFile(join(dir, file), Buffer.from(data, 'base64'));
report.push({ page: shot.name, width, scheme, shot: file, sideways, noRing });
await b.close();
}
await writeFile(join(dir, 'measure.json'), JSON.stringify(report, null, 1));
for (const r of report) {
assert.equal(r.sideways, false, `${r.shot} scrolls sideways`);
assert.deepEqual(r.noRing, [], `${r.shot}: controls with no visible focus ring`);
}
});