Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d752e75359 | ||
|
|
dde3ee4140 | ||
|
|
acb228d56f | ||
|
|
d01701a9ce |
No files matched your search
@@ -1,10 +1,15 @@
|
||||
// In-memory only; a new loader is made for every refresh so disabled or refused
|
||||
// modules can never inherit a loader's last-good authority.
|
||||
import { createLoader } from '../../plugins/src/loader.mjs';
|
||||
import { readOffered } from '../../model-proxy/src/models-offered.mjs';
|
||||
const validId = s => typeof s === 'string' && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(s);
|
||||
const validModel = s => typeof s === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/.test(s);
|
||||
const disabled = () => ({ status: 'disabled', observedAt: null, models: [], notices: [] });
|
||||
export function createModelCatalogue({ client, settings, pluginDataRoot = null, now = Date.now, makeLoader = createLoader, proxyLock = null }) {
|
||||
// #1873 models-offered: the owner's on/off file, read on every catalogue read so a Console write
|
||||
// counts at the next read. No data root (tests, a fixture bus) means no file: every model stays on.
|
||||
const offeredNow = () => pluginDataRoot ? readOffered(pluginDataRoot) : { state: 'absent', offered: null, revision: null };
|
||||
const offeredMark = o => o.state === 'damaged' ? 'damaged' : o.revision;
|
||||
const cache = new Map(), flights = new Map(); let generation = 0, writing = 0;
|
||||
function invalidate() { generation++; cache.clear(); }
|
||||
function begin() { writing++; invalidate(); }
|
||||
@@ -15,7 +20,7 @@ export function createModelCatalogue({ client, settings, pluginDataRoot = null,
|
||||
if (!Array.isArray(names) || names.length > 32 || names.some(n => !validId(n)) || new Set(names).size !== names.length) throw Error();
|
||||
return false;
|
||||
}
|
||||
async function refresh(id, previous) {
|
||||
async function refresh(id, previous, offered) {
|
||||
try {
|
||||
if (off(id)) return disabled();
|
||||
const names = [...settings(id)['model-provider']];
|
||||
@@ -27,11 +32,11 @@ export function createModelCatalogue({ client, settings, pluginDataRoot = null,
|
||||
const c = client();
|
||||
const proxy = method => async (...args) => { if (!c) throw Error('model proxy not configured'); return c[method](...args); };
|
||||
const answers = await Promise.all(loader.snapshot('model-provider').map(async ({ name, module }) => {
|
||||
const answer = await module.catalogue({ listAccounts: proxy('getCredentials'), listModels: proxy('getCredentialModels'), listGroups: proxy('getUpstreamGroups'), now: () => new Date(now()).toISOString() });
|
||||
const answer = await module.catalogue({ listAccounts: proxy('getCredentials'), listModels: proxy('getCredentialModels'), listGroups: proxy('getUpstreamGroups'), now: () => new Date(now()).toISOString(), offered });
|
||||
if (answer?.status === 'unavailable' && answer.reason === 'model-key-collision') throw Object.assign(Error(), { code: 'model-key-collision' });
|
||||
if (answer?.status !== 'ready' || !Array.isArray(answer.models) || answer.models.length > 10000 || !Array.isArray(answer.notices) || answer.notices.length > 100) throw Error();
|
||||
for (const m of answer.models) {
|
||||
if (!validId(m.key) || m.module !== name || !validId(m.upstream) || !validId(m.provider) || !validModel(m.model) || typeof m.label !== 'string' || m.label.length > 300 || /[\x00-\x1f\x7f]/.test(m.label) || typeof m.available !== 'boolean' || ![null, 'unverified'].includes(m.reason) || !Array.isArray(m.harnesses) || m.harnesses.length > 32 || m.harnesses.some(h => !validId(h))) throw Error();
|
||||
if (!validId(m.key) || m.module !== name || !validId(m.upstream) || !validId(m.provider) || !validModel(m.model) || typeof m.label !== 'string' || m.label.length > 300 || /[\x00-\x1f\x7f]/.test(m.label) || typeof m.available !== 'boolean' || ![null, 'unverified', 'model-off'].includes(m.reason) || (m.isNew !== undefined && m.isNew !== true) || !Array.isArray(m.harnesses) || m.harnesses.length > 32 || m.harnesses.some(h => !validId(h))) throw Error();
|
||||
}
|
||||
if (answer.notices.some(n => typeof n !== 'string' || n.length > 300 || /[\x00-\x1f\x7f]/.test(n))) throw Error();
|
||||
return answer;
|
||||
@@ -50,14 +55,15 @@ export function createModelCatalogue({ client, settings, pluginDataRoot = null,
|
||||
if (writing) return unavailable();
|
||||
try { if (off(id)) { cache.delete(id); return disabled(); } } catch { return { status: 'unavailable', observedAt: null, models: [], notices: [] }; }
|
||||
const existing = cache.get(id);
|
||||
const fingerprint = JSON.stringify([settings(id)['model-provider'], sharedGeneration]);
|
||||
const offered = offeredNow();
|
||||
const fingerprint = JSON.stringify([settings(id)['model-provider'], sharedGeneration, offeredMark(offered)]);
|
||||
if (!fresh && existing && existing.fingerprint === fingerprint && now() - existing.time < 30000) return structuredClone(existing.value);
|
||||
const flightKey = `${id}:${fingerprint}:${generation}`;
|
||||
let flight = flights.get(flightKey);
|
||||
if (!flight || fresh) {
|
||||
const at = generation;
|
||||
flight = refresh(id, existing?.value).then(value => {
|
||||
if (generation !== at || JSON.stringify([settings(id)?.['model-provider'], proxyLock?.generation()]) !== fingerprint) return null;
|
||||
flight = refresh(id, existing?.value, offered.offered).then(value => {
|
||||
if (generation !== at || JSON.stringify([settings(id)?.['model-provider'], proxyLock?.generation(), offeredMark(offeredNow())]) !== fingerprint) return null;
|
||||
if (cache.size >= 128 && !cache.has(id)) cache.delete(cache.keys().next().value);
|
||||
cache.set(id, { time: now(), fingerprint, value }); return value;
|
||||
}).catch(() => null);
|
||||
|
||||
@@ -83,6 +83,8 @@ group("proxy-init-busy proxy-init-lock-held proxy-init-lock-absent", "R4: init l
|
||||
group("proxy-key-transport", "R1/R6: a pasted key travels only over loopback or HTTPS", "Use the generated key, which never leaves the host, or open the Console over HTTPS or on this machine to paste one.");
|
||||
group("proxy-restart-required proxy-restart-unconfirmed proxy-lock-uncertain", "R4/R6: fence clears only after a confirmed proxy restart", "Restart the proxy from the Proxy page or with mosaic proxy fence clear --restart, so the new process is confirmed on the proxy port, then clear the fence. A fence file with no readable time cannot be proven against: restart the proxy service yourself and run mosaic proxy fence clear --proxy-restarted.");
|
||||
group("proxy-admin-busy", "R4: one proxy setup action at a time", "Wait for the running fetch, init or unit action to finish (the Proxy page status shows it), then retry.");
|
||||
// #1873 models-offered (A9, Jason 2026-11-20): the owner's per-provider model lists on the Model setup page.
|
||||
group("models-offered-conflict models-in-use", "R1/R4: the owner's offered models change one saved list at a time, and never silently under a running organization", "Reload the model list and make the change again. To switch off a model in use, confirm it in place, then give each organization and agent named another model on its Models page.");
|
||||
group("proxy-key-mismatch", "R1: a pasted management key is confirmed before init", "Type the same key in both fields, or leave them empty to have the bus generate the key.");
|
||||
group("proxy-lock-busy proxy-lock-invalid", "R4: one proxy key write at a time", "Wait for the running proxy write to finish and retry. An invalid lock file needs the owner to inspect the proxy state directory.");
|
||||
group("proxy-not-configured proxy-unit-usage proxy-unit-exists proxy-unit-dropin proxy-unit-copy proxy-unit-path proxy-unit-missing proxy-unit-unhealthy proxy-unit-failed", "R1/R4: proxy user unit is explicit creation", "Initialize the proxy first, then install the unit from the Proxy page or with mosaic proxy unit install. An existing unit or drop-in is never replaced; remove it by hand. An unhealthy unit: read its journal by unit name and restart it.");
|
||||
|
||||
@@ -95,3 +95,45 @@ test('shared generation invalidates cached catalogues and an uncertain fence mak
|
||||
version++; assert.equal((await service.read('one')).status, 'ready'); assert.equal(calls, 2);
|
||||
uncertain = true; assert.equal((await service.read('one')).status, 'unavailable');
|
||||
});
|
||||
|
||||
// #1873 models-offered (A9): the owner's on/off file under the instance data root.
|
||||
test('the catalogue reads the offered file from the plugin data root at every read: a write counts at once, a new model is New and off, a damaged file turns every model off, harnesses never change', async t => {
|
||||
const { mkdtempSync, rmSync, writeFileSync, mkdirSync, chmodSync } = await import('node:fs');
|
||||
const { tmpdir } = await import('node:os'); const { join } = await import('node:path');
|
||||
const { writeOffered } = await import('../../model-proxy/src/models-offered.mjs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'mo-cat-')); t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
let calls = 0;
|
||||
const names = [{ name: 'glm-5' }];
|
||||
const client = { getCredentials: async () => ({ files: [] }), getCredentialModels: async () => ({ models: [] }),
|
||||
getUpstreamGroups: async () => { calls++; return [{ 'base-url': 'https://api.z.ai/api/anthropic', keys: [{}], models: [...names] }]; } };
|
||||
const service = createModelCatalogue({ client: () => client, settings: () => ({ 'model-provider': ['cliproxy'] }), pluginDataRoot: root, now: () => 1000 });
|
||||
const view = c => c.models.map(m => [m.model, m.available, m.reason, m.isNew ?? false, m.harnesses.join(',')]);
|
||||
assert.deepEqual(view(await service.read('one')), [['glm-5', true, null, false, 'claude-code,pi']], 'no file: every model as listed');
|
||||
writeOffered(root, { version: 1, providers: { 'z.ai': { on: [], seen: ['glm-5'] } } });
|
||||
assert.deepEqual(view(await service.read('one')), [['glm-5', false, 'model-off', false, 'claude-code,pi']], 'a write counts at the next read, inside the cache window');
|
||||
assert.equal(calls, 2);
|
||||
writeOffered(root, { version: 1, providers: { 'z.ai': { on: ['glm-5'], seen: ['glm-5'] } } });
|
||||
names.push({ name: 'glm-6' });
|
||||
assert.deepEqual(view(await service.read('one')), [['glm-5', true, null, false, 'claude-code,pi'], ['glm-6', false, 'model-off', true, 'claude-code,pi']]);
|
||||
const before = calls;
|
||||
await service.read('one'); assert.equal(calls, before, 'an unchanged file keeps the cache');
|
||||
const file = join(root, 'state', 'models-offered.json');
|
||||
for (const [text, mode] of [['{"version":1,"providers":{"z.ai":{"on":["glm-5"],"seen":["glm-5"],"harness":"pi"}}}', 0o600], ['not json', 0o600], ['{"version":1,"providers":{"z.ai":{"on":["glm-5"],"seen":["glm-5"]}}}', 0o644]]) {
|
||||
writeFileSync(file, text); chmodSync(file, mode);
|
||||
const out = await service.read('one');
|
||||
assert.equal(out.status, 'ready', text);
|
||||
assert.deepEqual(out.models.map(m => [m.available, m.reason]), [[false, 'model-off'], [false, 'model-off']], `damaged (${text}, ${mode.toString(8)}): every model off, never all on`);
|
||||
}
|
||||
rmSync(file); mkdirSync(file);
|
||||
assert.ok((await service.read('one')).models.every(m => m.available === false && m.reason === 'model-off'), 'a directory in place of the file is damaged');
|
||||
});
|
||||
|
||||
test('a provider answer whose isNew is anything but absent or true makes the catalogue unavailable', async () => {
|
||||
let isNew;
|
||||
const model = () => ({ key: 'fixture-model', module: 'fixture-check', upstream: 'fixture', provider: 'fixture', model: 'fixture-model', label: 'Fixture', available: true, reason: null, harnesses: ['pi'], ...(isNew === undefined ? {} : { isNew }) });
|
||||
const module = { catalogue: async () => ({ status: 'ready', models: [model()], notices: [] }) };
|
||||
const makeLoader = () => ({ load: async () => ({ refused: [] }), snapshot: () => [{ name: 'fixture-check', module }] });
|
||||
const service = createModelCatalogue({ client: () => null, settings: () => ({ 'model-provider': ['fixture-check'] }), makeLoader });
|
||||
for (const good of [undefined, true]) { isNew = good; assert.equal((await service.read('one', { fresh: true })).status, 'ready', String(good)); }
|
||||
for (const bad of [false, 'yes', 1, null, {}]) { isNew = bad; assert.equal((await service.read('one', { fresh: true })).status, 'unavailable', JSON.stringify(bad)); }
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import { accountImpact } from './account-impact.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';
|
||||
import { offeredControl } from './models-offered.mjs';
|
||||
|
||||
export const proxyCode = (error, fallback) => (/^proxy-[a-z-]+$/.test(error?.code ?? '') ? error.code : fallback);
|
||||
const failure = code => Object.assign(new Error(code), { code });
|
||||
@@ -247,6 +248,8 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
|
||||
return ['accounts'];
|
||||
}
|
||||
return {
|
||||
// #1873 models-offered (A9): models() and modelsSet(), the owner's per-provider on/off lists.
|
||||
...offeredControl({ dataRoot, riders, receipt, exclusive, rootAgents }),
|
||||
unit: control.unit,
|
||||
async status() {
|
||||
// The job is read before the release: a fetch that ends during the awaits below then reads
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
// #1873 models-offered (A9, Jason 2026-11-20): which proxy models the instance owner offers, per
|
||||
// provider. One state file, <dataRoot>/state/models-offered.json:
|
||||
//
|
||||
// { "version": 1, "providers": { "<provider id>": { "on": [modelId...], "seen": [modelId...] } } }
|
||||
//
|
||||
// It holds model ids and provider ids only: no harness, no key, no label. Where a model may run
|
||||
// always comes from the plugin's catalogue(), so this file can switch a model off but can never
|
||||
// widen where it runs.
|
||||
//
|
||||
// The bus reads it (model-catalogue.mjs passes it to catalogue() as `offered`); only the Console
|
||||
// writes it (admin-control.mjs, under the admin lock, with a receipt). A file that is not a regular
|
||||
// file owned by this user with no group or other bits, or that does not parse to the shape above,
|
||||
// reads as damaged, and the catalogue then offers nothing. It never falls back to all on.
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { MODEL_ID, offeredLabel, offeredProvider } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
|
||||
export const OFFERED_VERSION = 1;
|
||||
export const MAX_ON = 256;
|
||||
// A provider's seen list keeps every id it has ever listed, so it may grow past MAX_ON; this bounds
|
||||
// the file instead.
|
||||
const MAX_SEEN = 10000;
|
||||
const MAX_PROVIDERS = 32;
|
||||
const MAX_BYTES = 4 * 1024 * 1024;
|
||||
const PROVIDER_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
||||
|
||||
export const offeredFile = dataRoot => path.join(dataRoot, 'state', 'models-offered.json');
|
||||
// The revision a write must name: a hash of the file's text, or of nothing when there is no file.
|
||||
export const offeredRevision = text => createHash('sha256').update(text ?? '').digest('hex').slice(0, 16);
|
||||
|
||||
const plain = v => !!v && typeof v === 'object' && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype;
|
||||
const idList = (list, max) => Array.isArray(list) && list.length <= max && list.every(id => typeof id === 'string' && MODEL_ID.test(id)) && new Set(list).size === list.length;
|
||||
|
||||
// The parsed shape, or null when anything is off. Unknown fields refuse, so a harness or a key can
|
||||
// never ride along in the file.
|
||||
export function parseOffered(doc) {
|
||||
if (!plain(doc) || Object.keys(doc).some(k => k !== 'version' && k !== 'providers') || doc.version !== OFFERED_VERSION || !plain(doc.providers)) return null;
|
||||
const ids = Object.keys(doc.providers);
|
||||
if (ids.length > MAX_PROVIDERS) return null;
|
||||
const providers = {};
|
||||
for (const id of ids) {
|
||||
const entry = doc.providers[id];
|
||||
if (!PROVIDER_ID.test(id) || !plain(entry) || Object.keys(entry).some(k => k !== 'on' && k !== 'seen')) return null;
|
||||
if (!idList(entry.on, MAX_ON) || !idList(entry.seen, MAX_SEEN)) return null;
|
||||
const seen = new Set(entry.seen);
|
||||
if (entry.on.some(m => !seen.has(m))) return null;
|
||||
providers[id] = { on: [...entry.on], seen: [...entry.seen] };
|
||||
}
|
||||
return { version: OFFERED_VERSION, providers };
|
||||
}
|
||||
|
||||
// { state: 'absent' | 'ok' | 'damaged', offered, revision }. `offered` is null when absent and
|
||||
// 'damaged' when damaged, which catalogue() reads as all off. `uid` is a test seam.
|
||||
export function readOffered(dataRoot, { uid = process.getuid() } = {}) {
|
||||
let fd;
|
||||
try { fd = fs.openSync(offeredFile(dataRoot), fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK); }
|
||||
catch (error) {
|
||||
if (error?.code === 'ENOENT') return { state: 'absent', offered: null, revision: offeredRevision(null) };
|
||||
return { state: 'damaged', offered: 'damaged', revision: null };
|
||||
}
|
||||
try {
|
||||
const stat = fs.fstatSync(fd);
|
||||
if (!stat.isFile() || stat.uid !== uid || (stat.mode & 0o077) || stat.nlink !== 1 || stat.size > MAX_BYTES) return { state: 'damaged', offered: 'damaged', revision: null };
|
||||
const text = fs.readFileSync(fd, 'utf8');
|
||||
let offered = null;
|
||||
try { offered = parseOffered(JSON.parse(text)); } catch { offered = null; }
|
||||
if (!offered) return { state: 'damaged', offered: 'damaged', revision: null };
|
||||
return { state: 'ok', offered, revision: offeredRevision(text) };
|
||||
} catch {
|
||||
return { state: 'damaged', offered: 'damaged', revision: null };
|
||||
} finally { fs.closeSync(fd); }
|
||||
}
|
||||
|
||||
// The whole file, written by a 0600 temp file in the same directory, fsync, rename, fsync of the
|
||||
// directory. The caller holds the admin lock and has checked the revision. Answers the new revision.
|
||||
export function writeOffered(dataRoot, offered) {
|
||||
const doc = parseOffered(offered);
|
||||
if (!doc) throw Object.assign(new Error('models-invalid'), { code: 'models-invalid' });
|
||||
const dir = path.join(dataRoot, 'state');
|
||||
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
const text = JSON.stringify(doc, null, 2) + '\n';
|
||||
const temp = path.join(dir, `.models-offered.${randomBytes(6).toString('hex')}.tmp`);
|
||||
const fd = fs.openSync(temp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
|
||||
try {
|
||||
fs.fchmodSync(fd, 0o600);
|
||||
fs.writeFileSync(fd, text);
|
||||
fs.fsyncSync(fd);
|
||||
} catch (error) { fs.closeSync(fd); try { fs.unlinkSync(temp); } catch { /* gone */ } throw error; }
|
||||
fs.closeSync(fd);
|
||||
try { fs.renameSync(temp, offeredFile(dataRoot)); } catch (error) { try { fs.unlinkSync(temp); } catch { /* gone */ } throw error; }
|
||||
const dfd = fs.openSync(dir, fs.constants.O_RDONLY);
|
||||
try { fs.fsyncSync(dfd); } finally { fs.closeSync(dfd); }
|
||||
return offeredRevision(text);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The Console's read and write for the instance owner (admin-control.mjs spreads this in).
|
||||
// `riders()` lists the active organizations as Ride all reads them; each that lists cliproxy is
|
||||
// asked for its routes, which carry its catalogue (every cliproxy model, on or off) and which
|
||||
// model each instance and fallback uses. `receipt` and `exclusive` are the admin's own.
|
||||
const failure = (code, extra = {}) => Object.assign(new Error(code), { code, ...extra });
|
||||
const ORG_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
||||
const REVISION = /^[a-f0-9]{16}$/;
|
||||
const RECEIPT_LIST = 32;
|
||||
const AGENT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
||||
|
||||
// Every launch.models key a document names for an agent, with the agent it sits under: each `model`
|
||||
// or `fallback.model` string anywhere in it outside `plugins` and `launch` (a launch.models entry's
|
||||
// own `model` is the upstream id, not a key). Broader than the routes view on purpose, the way
|
||||
// admin-control.mjs harnessesNamed is: role vars, project agents, definitions and any later place
|
||||
// count, so a switch-off asks wherever the file still names the model. Null when not a document.
|
||||
export function modelsNamed(document) {
|
||||
if (document === null || typeof document !== 'object' || Array.isArray(document)) return null;
|
||||
const found = [];
|
||||
const walk = (value, depth, owner) => {
|
||||
if (depth > 32 || value === null || typeof value !== 'object') return;
|
||||
if (Array.isArray(value)) { for (const item of value) walk(item, depth + 1, owner); return; }
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
if ((key === 'model' || key === 'fallback.model') && typeof item === 'string') found.push({ instance: owner, key: item, fallback: key === 'fallback.model' });
|
||||
else walk(item, depth + 1, key === 'vars' || key === 'define' || key === 'narrow' ? owner : (AGENT_NAME.test(key) ? key : null));
|
||||
}
|
||||
};
|
||||
for (const [key, value] of Object.entries(document)) if (key !== 'plugins' && key !== 'launch') walk(value, 1, null);
|
||||
return found;
|
||||
}
|
||||
// The same for the root agents an organization takes (every one but the root assistant and those
|
||||
// that exclude it, as admin-control.mjs rootHarnessesNamed reads them). `root` is what
|
||||
// loadRootAgents answered; anything not in that shape answers null (unreadable).
|
||||
export function rootModelsNamed(root, orgId) {
|
||||
if (root === null || typeof root !== 'object' || root.agents === null || typeof root.agents !== 'object' || Array.isArray(root.agents)) return null;
|
||||
const taken = {};
|
||||
for (const [name, entry] of Object.entries(root.agents)) {
|
||||
if (entry === null || typeof entry !== 'object' || !Array.isArray(entry.excludeOrgs)) return null;
|
||||
if (entry.definition === 'assistant' || entry.excludeOrgs.includes(orgId)) continue;
|
||||
taken[name] = entry.vars ?? {};
|
||||
}
|
||||
return modelsNamed({ agents: taken, definitions: root.definitions ?? {} });
|
||||
}
|
||||
|
||||
export function offeredControl({ dataRoot, riders, receipt, exclusive, rootAgents = null, uid = process.getuid() }) {
|
||||
const readFile = () => {
|
||||
const file = readOffered(dataRoot, { uid });
|
||||
if (file.state === 'damaged') throw failure('outcome-unknown');
|
||||
return file;
|
||||
};
|
||||
// Every provider's present models, in catalogue order, and who uses which. A model is in use when
|
||||
// a model or fallback model key resolves (the organization's model table, or the bus's legacy
|
||||
// mapping) to that cliproxy upstream and model id. The keys come from the routes view's instances,
|
||||
// from every place the organization file names one (project agents too) and from the root agents
|
||||
// the organization takes. `unanswered` names each organization whose usage is unknown: its file
|
||||
// could not be read, its bus did not answer, its catalogue (and so its legacy mapping) was not
|
||||
// ready, or the root agent file could not be read. A write that switches a model off treats each
|
||||
// one as a possible user.
|
||||
async function survey() {
|
||||
let list;
|
||||
try { list = await riders(); } catch { throw failure('outcome-unknown'); }
|
||||
const named = (Array.isArray(list) ? list : []).filter(r => typeof r?.id === 'string' && ORG_ID.test(r.id));
|
||||
const riding = named.filter(r => r.cliproxy === true);
|
||||
if (!riding.length) throw failure('not-configured');
|
||||
const unanswered = new Set(named.filter(r => typeof r.cliproxy !== 'boolean').map(r => r.id));
|
||||
let root;
|
||||
try { root = typeof rootAgents === 'function' ? await rootAgents() : undefined; } catch { root = undefined; }
|
||||
const answers = await Promise.all(riding.map(async r => {
|
||||
let routes = null, named = null;
|
||||
try { routes = await r.call('routes'); } catch { routes = null; }
|
||||
try { named = typeof r.file === 'function' ? modelsNamed((await r.file())?.document) : null; } catch { named = null; }
|
||||
const fromRoot = root === undefined ? null : rootModelsNamed(root, r.id);
|
||||
return { id: r.id, routes, named: named && fromRoot ? [...named, ...fromRoot] : null };
|
||||
}));
|
||||
const providers = new Map(), usedBy = new Map();
|
||||
let ready = false;
|
||||
for (const { id, routes } of answers) {
|
||||
const c = routes?.catalogue;
|
||||
if (c?.status !== 'ready' || !Array.isArray(c.models)) { unanswered.add(id); continue; }
|
||||
ready = true;
|
||||
for (const m of c.models) {
|
||||
if (m?.module !== 'cliproxy' || typeof m.upstream !== 'string' || typeof m.model !== 'string' || !MODEL_ID.test(m.model)) continue;
|
||||
const provider = offeredProvider(m.upstream);
|
||||
if (!providers.has(provider)) providers.set(provider, []);
|
||||
if (!providers.get(provider).includes(m.model)) providers.get(provider).push(m.model);
|
||||
}
|
||||
}
|
||||
if (!ready) throw failure('proxy-down');
|
||||
for (const { id, routes, named } of answers) {
|
||||
if (!routes || typeof routes.instances !== 'object' || routes.instances === null || named === null) { unanswered.add(id); continue; }
|
||||
const table = routes.providerModels && typeof routes.providerModels === 'object' ? routes.providerModels : {};
|
||||
const legacy = routes.catalogue?.legacy && typeof routes.catalogue.legacy === 'object' ? routes.catalogue.legacy : {};
|
||||
const resolve = key => (typeof key === 'string' && (Object.hasOwn(table, key) ? table[key] : Object.hasOwn(legacy, key) ? legacy[key] : null)) || null;
|
||||
const uses = [];
|
||||
for (const [instance, route] of Object.entries(routes.instances)) {
|
||||
if (!ORG_ID.test(instance)) continue;
|
||||
uses.push({ instance, key: route?.model, fallback: false }, { instance, key: route?.fallback?.model, fallback: true });
|
||||
}
|
||||
const once = new Set();
|
||||
for (const { instance, key, fallback } of [...uses, ...named]) {
|
||||
const entry = resolve(key);
|
||||
if (entry?.module !== 'cliproxy' || typeof entry.upstream !== 'string' || typeof entry.model !== 'string') continue;
|
||||
const at = `${offeredProvider(entry.upstream)}\n${entry.model}`;
|
||||
if (once.has(`${at}\n${instance}\n${fallback}`)) continue;
|
||||
once.add(`${at}\n${instance}\n${fallback}`);
|
||||
if (!usedBy.has(at)) usedBy.set(at, []);
|
||||
usedBy.get(at).push({ org: id, instance, fallback });
|
||||
}
|
||||
}
|
||||
return { providers, usedBy, unanswered: [...unanswered].sort() };
|
||||
}
|
||||
const entryOf = (file, p) => (file.offered && Object.hasOwn(file.offered.providers, p) ? file.offered.providers[p] : undefined);
|
||||
const usersOf = (s, provider, id) => s.usedBy.get(`${provider}\n${id}`) ?? [];
|
||||
// The models of `provider` something uses, present or not (an account may be signed out).
|
||||
const usedOf = (s, provider) => [...s.usedBy.keys()].filter(at => at.startsWith(`${provider}\n`)).map(at => at.slice(provider.length + 1)).filter(id => MODEL_ID.test(id));
|
||||
// A provider with no entry yet has every model on (catalogue() reads it so): the present ones and
|
||||
// any one in use whose account is signed out now.
|
||||
const onFor = (entry, present, s, provider) => entry ? entry.on : [...new Set([...present, ...usedOf(s, provider)])];
|
||||
const view = (file, s) => ({
|
||||
revision: file.revision,
|
||||
unanswered: s.unanswered,
|
||||
providers: [...s.providers].map(([provider, present]) => {
|
||||
const entry = entryOf(file, provider);
|
||||
const on = new Set(onFor(entry, present, s, provider).filter(id => present.includes(id)));
|
||||
const seen = new Set(entry ? entry.seen : present);
|
||||
return { provider, label: offeredLabel(provider), on: on.size, total: present.length,
|
||||
models: present.map(id => ({ id, label: id, on: on.has(id), isNew: !seen.has(id), usedBy: usersOf(s, provider, id) })) };
|
||||
}),
|
||||
});
|
||||
|
||||
return {
|
||||
// GET: the lists. A provider seen for the first time is written as all its present models on
|
||||
// and seen, with any model in use whose account is signed out (the plugin has no rule for
|
||||
// "current"), so a model it adds later starts off as New. The seed must change nothing anyone
|
||||
// uses: a provider with no entry is all on already. So it never seeds a provider with more than
|
||||
// MAX_ON such models, nor anything while an organization's usage is unknown (the owner's first
|
||||
// save does it then, with the in-use check), and it seeds only when `seed` is true, which the
|
||||
// Console sets only for a request that passes its write checks. The seed waits when another
|
||||
// admin action holds the lock; the view reads the same either way.
|
||||
async models({ seed = false } = {}) {
|
||||
let file = readFile();
|
||||
const s = await survey();
|
||||
const fresh = seed === true && !s.unanswered.length ? [...s.providers.keys()].filter(p => !entryOf(file, p) && onFor(undefined, s.providers.get(p), s, p).length <= MAX_ON) : [];
|
||||
if (fresh.length) {
|
||||
try {
|
||||
await exclusive('models', async () => {
|
||||
const now = readFile();
|
||||
if (now.revision !== file.revision) return;
|
||||
const providers = { ...(now.offered?.providers ?? {}) };
|
||||
for (const p of fresh) { const all = onFor(undefined, s.providers.get(p), s, p); providers[p] = { on: [...all], seen: [...all] }; }
|
||||
writeOffered(dataRoot, { version: OFFERED_VERSION, providers });
|
||||
receipt({ op: 'models.seed', providers: fresh.map(p => ({ provider: p, on: providers[p].on.length })) });
|
||||
});
|
||||
} catch (error) { if (error?.code !== 'proxy-admin-busy') throw failure('outcome-unknown'); }
|
||||
file = readFile();
|
||||
}
|
||||
return view(file, s);
|
||||
},
|
||||
// POST: one provider's on list for its present models. `revision` is the one the read gave; a
|
||||
// model in use that this switches off refuses unless `confirmInUse` is true, naming who uses
|
||||
// it. When it switches any model off and an organization's usage is unknown, it refuses the same
|
||||
// way and names that organization. A model that is on but not present now (its account signed
|
||||
// out) is not on the page, so it keeps its state: only a present model, or one named in `on`,
|
||||
// changes.
|
||||
async modelsSet({ provider, on, revision, confirmInUse = false, user = null } = {}) {
|
||||
if (typeof provider !== 'string' || !PROVIDER_ID.test(provider) || typeof revision !== 'string' || !REVISION.test(revision) || typeof confirmInUse !== 'boolean') throw failure('invalid-request');
|
||||
if (!idList(on, MAX_ON)) throw failure('models-invalid');
|
||||
return exclusive('models', async () => {
|
||||
const file = readFile();
|
||||
if (file.revision !== revision) throw failure('models-offered-conflict');
|
||||
const s = await survey();
|
||||
const present = s.providers.get(provider);
|
||||
if (!present) throw failure('models-invalid');
|
||||
const entry = entryOf(file, provider);
|
||||
const before = onFor(entry, present, s, provider);
|
||||
// A model may stay on while its account is signed out; a model never listed may not be switched on.
|
||||
if (on.some(id => !present.includes(id) && !before.includes(id))) throw failure('models-invalid');
|
||||
const kept = before.filter(id => !present.includes(id) && !on.includes(id));
|
||||
if (on.length + kept.length > MAX_ON) throw failure('models-invalid');
|
||||
const off = before.filter(id => present.includes(id) && !on.includes(id));
|
||||
const users = off.flatMap(id => usersOf(s, provider, id).map(u => ({ model: id, ...u })));
|
||||
const unanswered = off.length ? s.unanswered : [];
|
||||
if ((users.length || unanswered.length) && confirmInUse !== true) throw failure('models-in-use', { usedBy: users, unanswered });
|
||||
const seen = [...new Set([...(entry?.seen ?? []), ...present, ...on, ...kept])];
|
||||
const providers = { ...(file.offered?.providers ?? {}), [provider]: { on: [...on, ...kept], seen } };
|
||||
if (seen.length > MAX_SEEN) throw failure('models-invalid');
|
||||
const next = writeOffered(dataRoot, { version: OFFERED_VERSION, providers });
|
||||
// Every list is bounded, with a count of the rest, so the receipt line stays well inside what
|
||||
// receiptHistory reads.
|
||||
const record = { op: 'models.set', provider };
|
||||
const list = (name, items) => { record[name] = items.slice(0, RECEIPT_LIST); if (items.length > RECEIPT_LIST) record[`${name}More`] = items.length - RECEIPT_LIST; };
|
||||
list('on', on.filter(id => !before.includes(id)));
|
||||
list('off', off);
|
||||
if (users.length) list('inUse', users.map(u => ({ model: u.model, org: u.org, instance: u.instance })));
|
||||
if (unanswered.length) list('unanswered', unanswered);
|
||||
if (typeof user === 'string' && user) record.user = user.slice(0, 64);
|
||||
let written = null;
|
||||
try { written = receipt(record); } catch { written = null; }
|
||||
return { provider, revision: next, on: on.length, total: present.length, receipt: written };
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
// #1873 models-offered (A9): the owner's per-provider on/off file and the Console's read and write.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, rmSync, writeFileSync, readFileSync, statSync, symlinkSync, linkSync, mkdirSync, chmodSync, existsSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { readOffered, writeOffered, offeredControl, offeredFile, offeredRevision, MAX_ON } from '../src/models-offered.mjs';
|
||||
|
||||
const tempRoot = t => { const root = mkdtempSync(join(tmpdir(), 'mo-')); t.after(() => rmSync(root, { recursive: true, force: true })); return root; };
|
||||
const entry = (upstream, model) => ({ module: 'cliproxy', upstream, model });
|
||||
const rider = (id, models, extra = {}, document = { roles: {} }) => ({ id, cliproxy: true, file: async () => ({ document, revision: 'r' }), call: async verb => { if (verb !== 'routes') throw new Error('no'); return { instances: {}, catalogue: { status: 'ready', models }, ...extra }; } });
|
||||
const NO_ROOT = async () => ({ state: 'absent', agents: {}, assistant: null });
|
||||
function control(t, { riders, busy = false, rootAgents = NO_ROOT } = {}) {
|
||||
const dataRoot = tempRoot(t), receipts = [];
|
||||
const exclusive = async (name, action) => { if (busy) throw Object.assign(new Error('busy'), { code: 'proxy-admin-busy' }); return action(); };
|
||||
return { dataRoot, receipts, ...offeredControl({ dataRoot, riders: async () => riders, receipt: r => { receipts.push(r); return r; }, exclusive, rootAgents }) };
|
||||
}
|
||||
|
||||
test('readOffered: no file is absent; a written file reads ok with its revision; anything else reads damaged', t => {
|
||||
const root = tempRoot(t);
|
||||
assert.deepEqual(readOffered(root), { state: 'absent', offered: null, revision: offeredRevision(null) });
|
||||
const doc = { version: 1, providers: { 'z.ai': { on: ['glm-5'], seen: ['glm-5', 'glm-4.6'] } } };
|
||||
const revision = writeOffered(root, doc);
|
||||
assert.deepEqual(readOffered(root), { state: 'ok', offered: doc, revision });
|
||||
assert.equal(statSync(offeredFile(root)).mode & 0o777, 0o600);
|
||||
assert.equal(revision, offeredRevision(readFileSync(offeredFile(root), 'utf8')));
|
||||
chmodSync(offeredFile(root), 0o640);
|
||||
assert.equal(readOffered(root).state, 'damaged', 'group bits');
|
||||
chmodSync(offeredFile(root), 0o600);
|
||||
assert.equal(readOffered(root, { uid: process.getuid() + 1 }).state, 'damaged', 'another owner');
|
||||
const other = join(root, 'other.json');
|
||||
writeFileSync(other, JSON.stringify(doc), { mode: 0o600 });
|
||||
rmSync(offeredFile(root)); symlinkSync(other, offeredFile(root));
|
||||
assert.equal(readOffered(root).state, 'damaged', 'a symlink');
|
||||
rmSync(offeredFile(root)); linkSync(other, offeredFile(root));
|
||||
assert.equal(readOffered(root).state, 'damaged', 'a second hard link');
|
||||
rmSync(offeredFile(root)); writeFileSync(offeredFile(root), '{"version":1,"providers":{"z.ai":{"on":["glm-5"],"seen":[]}}}', { mode: 0o600 });
|
||||
assert.equal(readOffered(root).state, 'damaged', 'on but never seen');
|
||||
rmSync(offeredFile(root)); writeFileSync(offeredFile(root), '{"version":1,"providers":{"z.ai":{"on":[],"seen":[],"harness":"pi"}}}', { mode: 0o600 });
|
||||
assert.equal(readOffered(root).state, 'damaged', 'an unknown key in an entry');
|
||||
assert.throws(() => writeOffered(root, { ...doc, harness: 'pi' }), { code: 'models-invalid' });
|
||||
});
|
||||
|
||||
test('the first read asked to seed writes every present model on and seen, once; a read not asked to, or a busy lock, leaves the file and still answers', async t => {
|
||||
const models = [entry('zai', 'glm-5'), entry('zai', 'glm-4.6'), entry('codex', 'gpt-5'), entry('zai', 'glm-5'), { module: 'other', upstream: 'zai', model: 'x' }];
|
||||
const quiet = control(t, { riders: [rider('acme', models)] });
|
||||
for (const args of [undefined, {}, { seed: 'yes' }, { seed: 1 }]) assert.deepEqual((await quiet.models(args)).providers.map(p => [p.provider, p.on, p.total]), [['z.ai', 2, 2], ['codex', 1, 1]]);
|
||||
assert.equal(existsSync(offeredFile(quiet.dataRoot)), false, 'no seed unless asked');
|
||||
assert.deepEqual(quiet.receipts, []);
|
||||
const busy = control(t, { riders: [rider('acme', models)], busy: true });
|
||||
const view = await busy.models({ seed: true });
|
||||
assert.deepEqual(view.providers.map(p => [p.provider, p.label, p.on, p.total]), [['z.ai', 'z.ai', 2, 2], ['codex', 'ChatGPT / Codex', 1, 1]]);
|
||||
assert.equal(existsSync(offeredFile(busy.dataRoot)), false);
|
||||
assert.deepEqual(busy.receipts, []);
|
||||
const c = control(t, { riders: [rider('acme', models)] });
|
||||
const first = await c.models({ seed: true });
|
||||
assert.deepEqual(readOffered(c.dataRoot).offered, { version: 1, providers: { 'z.ai': { on: ['glm-5', 'glm-4.6'], seen: ['glm-5', 'glm-4.6'] }, codex: { on: ['gpt-5'], seen: ['gpt-5'] } } });
|
||||
assert.deepEqual(c.receipts, [{ op: 'models.seed', providers: [{ provider: 'z.ai', on: 2 }, { provider: 'codex', on: 1 }] }]);
|
||||
await c.models({ seed: true });
|
||||
assert.equal(c.receipts.length, 1);
|
||||
assert.equal(first.revision, readOffered(c.dataRoot).revision);
|
||||
});
|
||||
|
||||
test(`a provider with more than ${MAX_ON} models is never seeded; it reads all on, and the first save checks every model it switches off`, async t => {
|
||||
const many = Array.from({ length: MAX_ON + 4 }, (_, i) => entry('zai', `glm-${i}`));
|
||||
const last = `glm-${MAX_ON + 3}`;
|
||||
const routes = { instances: { chief: { model: 'mine' } }, providerModels: { mine: entry('zai', last) } };
|
||||
const c = control(t, { riders: [rider('acme', many, routes), rider('bolt', [entry('codex', 'gpt-5')])] });
|
||||
const view = await c.models({ seed: true });
|
||||
assert.deepEqual([view.providers[0].on, view.providers[0].total], [MAX_ON + 4, MAX_ON + 4]);
|
||||
assert.equal(view.providers[0].models.at(-1).on, true, 'the model in use reads on, as the catalogue offers it');
|
||||
assert.deepEqual(Object.keys(readOffered(c.dataRoot).offered.providers), ['codex'], 'only the small provider is seeded');
|
||||
const first = many.slice(0, MAX_ON).map(m => m.model);
|
||||
await assert.rejects(c.modelsSet({ provider: 'z.ai', on: first, revision: view.revision }), error => {
|
||||
assert.equal(error.code, 'models-in-use');
|
||||
assert.deepEqual(error.usedBy, [{ model: last, org: 'acme', instance: 'chief', fallback: false }]);
|
||||
return true;
|
||||
});
|
||||
const saved = await c.modelsSet({ provider: 'z.ai', on: first, revision: view.revision, confirmInUse: true });
|
||||
assert.equal(saved.on, MAX_ON);
|
||||
const record = c.receipts.at(-1);
|
||||
assert.deepEqual(record.off, many.slice(MAX_ON).map(m => m.model), 'the receipt names every model switched off');
|
||||
assert.equal(readOffered(c.dataRoot).offered.providers['z.ai'].seen.length, MAX_ON + 4);
|
||||
});
|
||||
|
||||
test('an organization whose usage is unknown (its file unreadable, its bus down, its catalogue not ready) counts as a possible user of any model switched off', async t => {
|
||||
const models = [entry('zai', 'glm-5'), entry('zai', 'glm-4.6')];
|
||||
const down = { id: 'bolt', cliproxy: true, call: async () => { throw new Error('down'); } };
|
||||
const unreadable = { id: 'crux', cliproxy: null, call: async () => { throw new Error('not asked'); } };
|
||||
const notReady = rider('dune', [], { instances: { coder: { model: 'old-glm' } }, catalogue: { status: 'unavailable', models: [], legacy: {} } });
|
||||
const notRiding = { id: 'east', cliproxy: false, call: async () => { throw new Error('not asked'); } };
|
||||
const noFile = { ...rider('fern', models), file: async () => { throw new Error('unreadable'); } };
|
||||
const noFileReader = { ...rider('gale', models), file: undefined };
|
||||
const c = control(t, { riders: [rider('acme', models), down, unreadable, notReady, notRiding, noFile, noFileReader] });
|
||||
const view = await c.models({ seed: true });
|
||||
assert.deepEqual(view.unanswered, ['bolt', 'crux', 'dune', 'fern', 'gale']);
|
||||
assert.equal(existsSync(offeredFile(c.dataRoot)), false, 'no seed while any usage is unknown');
|
||||
await assert.rejects(c.modelsSet({ provider: 'z.ai', on: ['glm-5'], revision: view.revision }), error => {
|
||||
assert.equal(error.code, 'models-in-use');
|
||||
assert.deepEqual([error.usedBy, error.unanswered], [[], ['bolt', 'crux', 'dune', 'fern', 'gale']]);
|
||||
return true;
|
||||
});
|
||||
assert.equal(readOffered(c.dataRoot).revision, view.revision, 'nothing written');
|
||||
// Switching nothing off needs no ask.
|
||||
const same = await c.modelsSet({ provider: 'z.ai', on: ['glm-5', 'glm-4.6'], revision: view.revision });
|
||||
const saved = await c.modelsSet({ provider: 'z.ai', on: ['glm-5'], revision: same.revision, confirmInUse: true });
|
||||
assert.equal(saved.on, 1);
|
||||
assert.deepEqual(c.receipts.at(-1), { op: 'models.set', provider: 'z.ai', on: [], off: ['glm-4.6'], unanswered: ['bolt', 'crux', 'dune', 'fern', 'gale'] });
|
||||
// The root agent file unreadable (a throw, or not the loader's shape) leaves every organization's usage unknown.
|
||||
for (const rootAgents of [async () => { throw new Error('unreadable'); }, async () => ({ state: 'ok', agents: { a: { vars: {} } } }), async () => null, null]) {
|
||||
const r = control(t, { riders: [rider('acme', models)], rootAgents });
|
||||
assert.deepEqual((await r.models({ seed: true })).unanswered, ['acme'], String(rootAgents));
|
||||
assert.equal(existsSync(offeredFile(r.dataRoot)), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('in use counts every place the organization file names a model and the root agents it takes: project agents, root copies; not an excluded or assistant root agent, not launch.models itself', async t => {
|
||||
const models = [entry('zai', 'glm-5'), entry('zai', 'glm-4.6'), entry('codex', 'gpt-5'), entry('codex', 'gpt-5-mini')];
|
||||
const routes = { instances: { chief: { model: 'g5' } }, providerModels: { g5: entry('zai', 'glm-5'), g46: entry('zai', 'glm-4.6'), gpt: entry('codex', 'gpt-5'), mini: entry('codex', 'gpt-5-mini') } };
|
||||
const document = { roles: { chief: { vars: { model: 'g5' } } }, launch: { models: { g5: { module: 'cliproxy', upstream: 'zai', model: 'g46' } } },
|
||||
projects: { site: { agents: { coder: { define: { definition: 'coder', vars: { model: 'g46', 'fallback.model': 'gpt' } } } } } } };
|
||||
const root = { state: 'ok', assistant: null, agents: {
|
||||
helper: { definition: 'coder', excludeOrgs: [], vars: { model: 'mini' } },
|
||||
away: { definition: 'coder', excludeOrgs: ['acme'], vars: { model: 'gpt' } },
|
||||
front: { definition: 'assistant', excludeOrgs: [], vars: { model: 'gpt' } } } };
|
||||
const c = control(t, { riders: [rider('acme', models, routes, document)], rootAgents: async () => root });
|
||||
const view = await c.models({ seed: true });
|
||||
assert.deepEqual(view.providers.map(p => p.models.map(m => [m.id, m.usedBy])), [
|
||||
[['glm-5', [{ org: 'acme', instance: 'chief', fallback: false }]], ['glm-4.6', [{ org: 'acme', instance: 'coder', fallback: false }]]],
|
||||
[['gpt-5', [{ org: 'acme', instance: 'coder', fallback: true }]], ['gpt-5-mini', [{ org: 'acme', instance: 'helper', fallback: false }]]]]);
|
||||
await assert.rejects(c.modelsSet({ provider: 'codex', on: [], revision: view.revision }), error => {
|
||||
assert.deepEqual(error.usedBy.map(u => [u.model, u.instance, u.fallback]), [['gpt-5', 'coder', true], ['gpt-5-mini', 'helper', false]]);
|
||||
return true;
|
||||
});
|
||||
});
|
||||
|
||||
test('a model in use whose account is signed out: the seed keeps it on, the first save with no entry keeps it on, and a save that leaves it off the page keeps it on', async t => {
|
||||
let models = [entry('codex', 'gpt-5')];
|
||||
const routes = { instances: { chief: { model: 'pro' } }, providerModels: { pro: entry('codex', 'gpt-5-pro') } };
|
||||
const acme = { ...rider('acme', []), call: async () => ({ ...routes, catalogue: { status: 'ready', models } }) };
|
||||
const c = control(t, { riders: [acme] });
|
||||
const view = await c.models({ seed: true });
|
||||
assert.deepEqual(readOffered(c.dataRoot).offered.providers.codex, { on: ['gpt-5', 'gpt-5-pro'], seen: ['gpt-5', 'gpt-5-pro'] }, 'the seed keeps the model in use on');
|
||||
const saved = await c.modelsSet({ provider: 'codex', on: [], revision: view.revision });
|
||||
assert.deepEqual(readOffered(c.dataRoot).offered.providers.codex.on, ['gpt-5-pro'], 'a model not on the page keeps its state');
|
||||
assert.deepEqual(c.receipts.at(-1), { op: 'models.set', provider: 'codex', on: [], off: ['gpt-5'] });
|
||||
models = [entry('codex', 'gpt-5'), entry('codex', 'gpt-5-pro')];
|
||||
await assert.rejects(c.modelsSet({ provider: 'codex', on: [], revision: saved.revision }), { code: 'models-in-use' }, 'back again, it is on the page and asks');
|
||||
// With no entry at all, the first save keeps an absent model in use on too.
|
||||
models = [entry('codex', 'gpt-5')];
|
||||
const fresh = control(t, { riders: [acme] });
|
||||
const read = await fresh.models();
|
||||
assert.equal(existsSync(offeredFile(fresh.dataRoot)), false);
|
||||
await fresh.modelsSet({ provider: 'codex', on: ['gpt-5'], revision: read.revision });
|
||||
assert.deepEqual(readOffered(fresh.dataRoot).offered.providers.codex, { on: ['gpt-5', 'gpt-5-pro'], seen: ['gpt-5', 'gpt-5-pro'] });
|
||||
});
|
||||
|
||||
test(`a model kept on while its account is signed out counts against the ${MAX_ON} limit; a save past it is models-invalid before any ask, and writes nothing`, async t => {
|
||||
const present = Array.from({ length: MAX_ON - 3 }, (_, i) => entry('zai', `glm-${i}`));
|
||||
const away = Array.from({ length: 10 }, (_, i) => `gone-${i}`);
|
||||
const routes = { instances: { chief: { model: 'first' } }, providerModels: { first: entry('zai', 'glm-0') } };
|
||||
const c = control(t, { riders: [rider('acme', present, routes)] });
|
||||
const all = present.map(m => m.model);
|
||||
writeOffered(c.dataRoot, { version: 1, providers: { 'z.ai': { on: [...away, ...all.slice(0, MAX_ON - 10)], seen: [...away, ...all] } } });
|
||||
const before = readOffered(c.dataRoot);
|
||||
// glm-0 is in use and this switches it off, but the list is too long first: no ask for a save that cannot be written.
|
||||
await assert.rejects(c.modelsSet({ provider: 'z.ai', on: all.slice(1), revision: before.revision }), { code: 'models-invalid' }, `${all.length - 1} on plus 10 kept is past ${MAX_ON}`);
|
||||
await assert.rejects(c.modelsSet({ provider: 'z.ai', on: all.slice(1), revision: before.revision, confirmInUse: true }), { code: 'models-invalid' });
|
||||
assert.equal(readOffered(c.dataRoot).revision, before.revision);
|
||||
assert.deepEqual(c.receipts, []);
|
||||
const saved = await c.modelsSet({ provider: 'z.ai', on: all.slice(7), revision: before.revision, confirmInUse: true });
|
||||
assert.equal(saved.on, MAX_ON - 10);
|
||||
const after = readOffered(c.dataRoot);
|
||||
assert.equal(after.state, 'ok', 'the file it writes still reads');
|
||||
assert.equal(after.offered.providers['z.ai'].on.length, MAX_ON);
|
||||
assert.deepEqual(after.offered.providers['z.ai'].on.slice(-10), away);
|
||||
});
|
||||
|
||||
test('a save keeps every model seen before, so one away at the save and back later is not New', async t => {
|
||||
let models = [entry('codex', 'gpt-5')];
|
||||
const acme = { ...rider('acme', []), call: async () => ({ instances: {}, catalogue: { status: 'ready', models } }) };
|
||||
const c = control(t, { riders: [acme] });
|
||||
writeOffered(c.dataRoot, { version: 1, providers: { codex: { on: ['gpt-5'], seen: ['gpt-5', 'gpt-old'] } } });
|
||||
await c.modelsSet({ provider: 'codex', on: ['gpt-5'], revision: readOffered(c.dataRoot).revision });
|
||||
assert.deepEqual(readOffered(c.dataRoot).offered.providers.codex.seen, ['gpt-5', 'gpt-old']);
|
||||
models = [entry('codex', 'gpt-5'), entry('codex', 'gpt-old')];
|
||||
const view = await c.models();
|
||||
const old = view.providers.find(p => p.provider === 'codex').models.find(m => m.id === 'gpt-old');
|
||||
assert.deepEqual([old.on, old.isNew], [false, false]);
|
||||
});
|
||||
|
||||
test('the receipt bounds every list at 32 with a count of the rest', async t => {
|
||||
const many = Array.from({ length: 40 }, (_, i) => entry('zai', `glm-${i}`));
|
||||
const instances = Object.fromEntries(many.map((m, i) => [`agent-${i}`, { model: `k${i}` }]));
|
||||
const providerModels = Object.fromEntries(many.map((m, i) => [`k${i}`, m]));
|
||||
const down = { id: 'zz-down', cliproxy: null, call: async () => { throw new Error('down'); } };
|
||||
const quiet = Array.from({ length: 34 }, (_, i) => ({ ...down, id: `q-${String(i).padStart(2, '0')}` }));
|
||||
const c = control(t, { riders: [rider('acme', many, { instances, providerModels }), ...quiet] });
|
||||
const view = await c.models();
|
||||
await c.modelsSet({ provider: 'z.ai', on: [], revision: view.revision, confirmInUse: true });
|
||||
const r = c.receipts.at(-1);
|
||||
assert.deepEqual([r.off.length, r.offMore, r.inUse.length, r.inUseMore, r.unanswered.length, r.unansweredMore], [32, 8, 32, 8, 32, 2]);
|
||||
const back = await c.modelsSet({ provider: 'z.ai', on: many.map(m => m.model), revision: readOffered(c.dataRoot).revision });
|
||||
assert.equal(back.on, 40);
|
||||
assert.deepEqual([c.receipts.at(-1).on.length, c.receipts.at(-1).onMore], [32, 8]);
|
||||
});
|
||||
|
||||
test('the seed rechecks the revision under the lock: a write between the read and the lock leaves the seed out', async t => {
|
||||
const box = {};
|
||||
const sneaky = { ...rider('acme', [entry('zai', 'glm-5')]), call: async () => { writeOffered(box.root, { version: 1, providers: { codex: { on: [], seen: [] } } }); return { instances: {}, catalogue: { status: 'ready', models: [entry('zai', 'glm-5')] } }; } };
|
||||
const c = control(t, { riders: [sneaky] });
|
||||
box.root = c.dataRoot;
|
||||
await c.models({ seed: true });
|
||||
assert.deepEqual(readOffered(c.dataRoot).offered.providers, { codex: { on: [], seen: [] } });
|
||||
assert.deepEqual(c.receipts, []);
|
||||
});
|
||||
|
||||
test('a damaged file: the read and the write answer outcome-unknown and write nothing', async t => {
|
||||
const c = control(t, { riders: [rider('acme', [entry('zai', 'glm-5')])] });
|
||||
mkdirSync(join(c.dataRoot, 'state'), { mode: 0o700 });
|
||||
writeFileSync(offeredFile(c.dataRoot), 'not json', { mode: 0o600 });
|
||||
await assert.rejects(c.models(), { code: 'outcome-unknown' });
|
||||
await assert.rejects(c.modelsSet({ provider: 'z.ai', on: [], revision: 'a'.repeat(16) }), { code: 'outcome-unknown' });
|
||||
assert.equal(readFileSync(offeredFile(c.dataRoot), 'utf8'), 'not json');
|
||||
assert.deepEqual(c.receipts, []);
|
||||
});
|
||||
|
||||
test('no organization riding is not-configured; none answering a ready catalogue is proxy-down; a busy lock refuses the write', async t => {
|
||||
await assert.rejects(control(t, { riders: [] }).models(), { code: 'not-configured' });
|
||||
await assert.rejects(control(t, { riders: [{ ...rider('acme', []), cliproxy: false }] }).models(), { code: 'not-configured' });
|
||||
const down = { id: 'acme', cliproxy: true, call: async () => { throw new Error('down'); } };
|
||||
await assert.rejects(control(t, { riders: [down, rider('bolt', [], { catalogue: { status: 'unavailable', models: [] } })] }).models(), { code: 'proxy-down' });
|
||||
await assert.rejects(control(t, { riders: [rider('acme', [entry('zai', 'glm-5')])], busy: true }).modelsSet({ provider: 'z.ai', on: [], revision: 'a'.repeat(16) }), { code: 'proxy-admin-busy' });
|
||||
});
|
||||
|
||||
test('the write checks its body first: a bad provider, revision or confirm is invalid-request; a bad or too long on list is models-invalid', async t => {
|
||||
const c = control(t, { riders: [rider('acme', [entry('zai', 'glm-5')])] });
|
||||
const r = 'a'.repeat(16);
|
||||
for (const args of [{ provider: 'Z AI', on: [], revision: r }, { provider: 'z.ai', on: [], revision: 'short' }, { provider: 'z.ai', on: [], revision: r, confirmInUse: 'yes' }, {}])
|
||||
await assert.rejects(c.modelsSet(args), { code: 'invalid-request' }, JSON.stringify(args));
|
||||
for (const on of ['glm-5', ['glm-5', 'glm-5'], ['bad id'], Array.from({ length: MAX_ON + 1 }, (_, i) => `m-${i}`)])
|
||||
await assert.rejects(c.modelsSet({ provider: 'z.ai', on, revision: r }), { code: 'models-invalid' }, JSON.stringify(on).slice(0, 40));
|
||||
});
|
||||
|
||||
test('in use counts the organization model table and the bus legacy mapping, primary and fallback; a model still on stays on while its account is signed out', async t => {
|
||||
const legacy = { instances: { coder: { model: 'old-glm' } }, catalogue: { status: 'ready', models: [entry('zai', 'glm-5'), entry('zai', 'glm-4.6')], legacy: { 'old-glm': entry('zai', 'glm-4.6') } } };
|
||||
const table = { instances: { assistant: { model: 'mine', fallback: { model: 'mine' } }, '../x': { model: 'mine' } }, providerModels: { mine: entry('zai', 'glm-5') }, catalogue: { status: 'ready', models: [] } };
|
||||
const c = control(t, { riders: [rider('acme', [], legacy), rider('bolt', [], table)] });
|
||||
const view = await c.models({ seed: true });
|
||||
assert.deepEqual(view.providers[0].models.map(m => [m.id, m.usedBy]), [
|
||||
['glm-5', [{ org: 'bolt', instance: 'assistant', fallback: false }, { org: 'bolt', instance: 'assistant', fallback: true }]],
|
||||
['glm-4.6', [{ org: 'acme', instance: 'coder', fallback: false }]]]);
|
||||
await assert.rejects(c.modelsSet({ provider: 'z.ai', on: [], revision: view.revision }), error => {
|
||||
assert.equal(error.code, 'models-in-use');
|
||||
assert.deepEqual(error.usedBy.map(u => [u.model, u.org, u.instance, u.fallback]), [['glm-5', 'bolt', 'assistant', false], ['glm-5', 'bolt', 'assistant', true], ['glm-4.6', 'acme', 'coder', false]]);
|
||||
return true;
|
||||
});
|
||||
// glm-4.6 leaves the catalogue (its account signed out): it may stay on, but one never listed may not be switched on.
|
||||
legacy.catalogue.models = [entry('zai', 'glm-5')];
|
||||
const saved = await c.modelsSet({ provider: 'z.ai', on: ['glm-5', 'glm-4.6'], revision: view.revision });
|
||||
assert.equal(saved.on, 2);
|
||||
assert.deepEqual(readOffered(c.dataRoot).offered.providers['z.ai'], { on: ['glm-5', 'glm-4.6'], seen: ['glm-5', 'glm-4.6'] });
|
||||
await assert.rejects(c.modelsSet({ provider: 'z.ai', on: ['glm-5', 'glm-4.6', 'glm-9'], revision: saved.revision }), { code: 'models-invalid' });
|
||||
});
|
||||
@@ -29,9 +29,35 @@ export function providerUpstream(provider, list = PROVIDERS) {
|
||||
// It routes a request by model name across every account, so a group model whose name an OAuth
|
||||
// Claude account offers (`oauth`) could be served by that account and is held to claude-code too.
|
||||
const harnesses = (upstream, oauth = false) => upstream === 'claude' || oauth ? ['claude-code'] : ['claude-code', 'pi'];
|
||||
// #1873 models-offered (A9): the provider id an entry of the owner's offered file is keyed by. An
|
||||
// OAuth provider's catalogue upstream is its id; a key provider's is the family of its base URL.
|
||||
// A group on any other base URL is keyed `other`.
|
||||
export const offeredProvider = upstream => PROVIDERS.find(p => (p.signIn === 'oauth' ? p.id : family(p.baseUrl)) === upstream)?.id ?? upstream;
|
||||
// The name the owner's model list shows for a provider: its PROVIDERS label, or a plain word for a
|
||||
// group on another base URL.
|
||||
export const offeredLabel = provider => PROVIDERS.find(p => p.id === provider)?.label ?? 'Other';
|
||||
const offeredShape = o => !!o && typeof o === 'object' && o.version === 1 && !!o.providers && typeof o.providers === 'object' && !Array.isArray(o.providers)
|
||||
&& Object.values(o.providers).every(e => !!e && Array.isArray(e.on) && Array.isArray(e.seen));
|
||||
// `offered` is the parsed file, null or undefined when there is none, or anything else when it is
|
||||
// damaged. No file, or a provider with no entry yet, keeps every model on: the plugin has no rule
|
||||
// for a provider's current models, so the first read seeds all present models on and the Console
|
||||
// writes them as on and seen. With an entry, a model is on only when it is both seen and on; one
|
||||
// not seen yet is New and starts off. A damaged file switches every model off. Only `available`,
|
||||
// `reason` and `isNew` change: `harnesses` never does, so the file cannot widen where a model runs.
|
||||
function applyOffered(models, offered) {
|
||||
if (offered === undefined || offered === null) return;
|
||||
const whole = offeredShape(offered);
|
||||
for (const m of models) {
|
||||
const id = offeredProvider(m.upstream), entry = whole && Object.hasOwn(offered.providers, id) ? offered.providers[id] : undefined;
|
||||
if (whole && entry === undefined) continue;
|
||||
const seen = whole && entry.seen.includes(m.model);
|
||||
if (whole && !seen) m.isNew = true;
|
||||
if (!(seen && entry.on.includes(m.model))) { m.available = false; m.reason = 'model-off'; }
|
||||
}
|
||||
}
|
||||
const slug = (upstream, model) => `${upstream}-${model}`.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+$/g, '');
|
||||
|
||||
export async function catalogue({ listAccounts, listModels, listGroups, now }) {
|
||||
export async function catalogue({ listAccounts, listModels, listGroups, now, offered }) {
|
||||
try {
|
||||
const [accounts, groups] = await Promise.all([listAccounts(), listGroups()]);
|
||||
if (!Array.isArray(accounts?.files) || !Array.isArray(groups) || accounts.files.length > MAX_MODELS || groups.length > MAX_MODELS) throw Error();
|
||||
@@ -75,6 +101,7 @@ export async function catalogue({ listAccounts, listModels, listGroups, now }) {
|
||||
for (const model of group.models) add(upstream, model?.alias || model?.name);
|
||||
}
|
||||
for (const m of models) m.harnesses = harnesses(m.upstream, oauth.has(m.model.toLowerCase()));
|
||||
applyOffered(models, offered);
|
||||
return { status: 'ready', observedAt: now(), models, notices: [...new Set(notices)] };
|
||||
} catch (error) {
|
||||
return { status: 'unavailable', observedAt: null, models: [], notices: [], ...(error.code === 'model-key-collision' ? { reason: error.code } : {}) };
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { catalogue, preflight, providerUpstream, PROVIDERS } from '../model-provider/cliproxy/index.mjs';
|
||||
import { catalogue, preflight, providerUpstream, PROVIDERS, route } from '../model-provider/cliproxy/index.mjs';
|
||||
|
||||
const ZAI = 'https://api.z.ai/api/anthropic';
|
||||
const deps = () => ({
|
||||
@@ -191,3 +191,76 @@ test('providerUpstream names the upstream catalogue() uses for each provider, an
|
||||
assert.equal(providerUpstream('z.ai', [{ id: 'z.ai', signIn: 'apikey', baseUrl: 'https://example.invalid/anthropic' }]), 'other');
|
||||
assert.equal(providerUpstream('x', [{ id: 'x', signIn: 'device' }]), null);
|
||||
});
|
||||
|
||||
// #1873 models-offered (A9): the owner's on/off file as the catalogue input `offered`.
|
||||
const offeredDeps = () => {
|
||||
const d = deps();
|
||||
d.listModels = async name => ({ models: name === 'credential-1' ? [{ id: 'fixture-chat' }, { id: 'fixture-chat-older' }] : [] });
|
||||
d.listGroups = async () => [{ 'base-url': ZAI, keys: [{ auth_index: 'k' }], models: [{ name: 'fixture-glm' }, { name: 'fixture-glm-new' }] }];
|
||||
return d;
|
||||
};
|
||||
const state = c => Object.fromEntries(c.models.map(m => [m.model, [m.available, m.reason, m.isNew === true, m.harnesses]]));
|
||||
|
||||
test('models-offered: no file, or no entry for a provider, keeps every model as the plugin lists it', async () => {
|
||||
const plain = state(await catalogue(offeredDeps()));
|
||||
for (const offered of [undefined, null, { version: 1, providers: {} }]) assert.deepEqual(state(await catalogue({ ...offeredDeps(), offered })), plain, JSON.stringify(offered));
|
||||
assert.deepEqual(plain['fixture-chat'], [true, null, false, ['claude-code']]);
|
||||
assert.deepEqual(plain['fixture-glm'], [true, null, false, ['claude-code', 'pi']]);
|
||||
});
|
||||
|
||||
test('models-offered: an off model and an unseen one are unavailable with model-off, the unseen one is New, and harnesses never change', async () => {
|
||||
const offered = { version: 1, providers: { claude: { on: ['fixture-chat'], seen: ['fixture-chat', 'fixture-chat-older'] }, 'z.ai': { on: ['fixture-glm'], seen: ['fixture-glm'] } } };
|
||||
const c = await catalogue({ ...offeredDeps(), offered });
|
||||
assert.equal(c.status, 'ready');
|
||||
assert.deepEqual(state(c), {
|
||||
'fixture-chat': [true, null, false, ['claude-code']],
|
||||
'fixture-chat-older': [false, 'model-off', false, ['claude-code']],
|
||||
'fixture-glm': [true, null, false, ['claude-code', 'pi']],
|
||||
'fixture-glm-new': [false, 'model-off', true, ['claude-code', 'pi']],
|
||||
});
|
||||
// Off is refused at admission like any unavailable model.
|
||||
const older = c.models.find(m => m.model === 'fixture-chat-older');
|
||||
assert.deepEqual(preflight({ selection: older, harness: 'claude-code', catalogue: c }), { allow: false, code: 'model-provider-unavailable' });
|
||||
// On in a file that also lists it never widens an OAuth Claude model to pi.
|
||||
const chat = c.models.find(m => m.model === 'fixture-chat');
|
||||
assert.deepEqual(preflight({ selection: chat, harness: 'pi', catalogue: c }), { allow: false, code: 'model-harness-incompatible' });
|
||||
});
|
||||
|
||||
test('models-offered: a key model whose name an OAuth Claude account offers stays claude-code only when switched on', async () => {
|
||||
const d = offeredDeps();
|
||||
d.listGroups = async () => [{ 'base-url': ZAI, keys: [{ auth_index: 'k' }], models: [{ name: 'fixture-chat' }] }];
|
||||
const c = await catalogue({ ...d, offered: { version: 1, providers: { claude: { on: ['fixture-chat'], seen: ['fixture-chat'] }, 'z.ai': { on: ['fixture-chat'], seen: ['fixture-chat'] } } } });
|
||||
const zai = c.models.find(m => m.upstream === 'zai');
|
||||
assert.deepEqual([zai.available, zai.harnesses], [true, ['claude-code']]);
|
||||
// A selection of unknown account kind (no catalogue module) named as Claude is still held to claude-code.
|
||||
assert.deepEqual(route({ selection: { provider: 'zai', model: 'fixture-claude-chat' }, harness: 'pi' }), { code: 'model-harness-incompatible' });
|
||||
// A Claude account whose state is unknown, signed out or switched off is not listed, but its names
|
||||
// still count as OAuth: switching the same-named key model on keeps it claude-code only.
|
||||
for (const accountState of [{ status: 'unknown' }, { status: 'error' }, { status: 'active', disabled: true }, { status: 'active', unavailable: true }]) {
|
||||
const u = offeredDeps();
|
||||
u.listAccounts = async () => ({ files: [{ name: 'credential-1', provider: 'claude', ...accountState }] });
|
||||
u.listGroups = async () => [{ 'base-url': ZAI, keys: [{ auth_index: 'k' }], models: [{ name: 'fixture-chat' }] }];
|
||||
const cu = await catalogue({ ...u, offered: { version: 1, providers: { 'z.ai': { on: ['fixture-chat'], seen: ['fixture-chat'] } } } });
|
||||
const label = JSON.stringify(accountState);
|
||||
assert.deepEqual(cu.models.map(m => [m.upstream, m.model, m.available, m.harnesses]), [['zai', 'fixture-chat', true, ['claude-code']]], label);
|
||||
assert.deepEqual(preflight({ selection: cu.models[0], harness: 'pi', catalogue: cu }), { allow: false, code: 'model-harness-incompatible' }, label);
|
||||
}
|
||||
});
|
||||
|
||||
test('models-offered: a damaged file switches every model off and never falls back to all on', async () => {
|
||||
for (const offered of ['damaged', 'x', 42, [], { version: 2, providers: {} }, { version: 1 }, { version: 1, providers: [] }, { version: 1, providers: { claude: { on: 'fixture-chat', seen: [] } } }, { version: 1, providers: { claude: null } }]) {
|
||||
const c = await catalogue({ ...offeredDeps(), offered });
|
||||
assert.equal(c.status, 'ready', JSON.stringify(offered));
|
||||
assert.ok(c.models.length === 4 && c.models.every(m => m.available === false && m.reason === 'model-off'), JSON.stringify(offered));
|
||||
assert.ok(c.models.every(m => m.harnesses.length > 0), 'harnesses are kept, never widened or blanked');
|
||||
}
|
||||
});
|
||||
|
||||
test('models-offered: an entry keyed by an inherited name is not an entry', async () => {
|
||||
const d = offeredDeps();
|
||||
d.listAccounts = async () => ({ files: [] });
|
||||
d.listGroups = async () => [{ 'base-url': 'https://fixture.invalid', keys: [{ auth_index: 'b' }], models: [{ name: 'fixture-other' }] }];
|
||||
const providers = Object.create({ other: { on: [], seen: [] } });
|
||||
const c = await catalogue({ ...d, offered: { version: 1, providers } });
|
||||
assert.deepEqual([c.models[0].available, c.models[0].reason], [true, 'unverified']);
|
||||
});
|
||||
@@ -36,6 +36,9 @@ const ROUTES = Object.freeze({
|
||||
// #1873 ride-default: Ride all, and the confirmed move of one stopped fixture organization.
|
||||
'/api/proxy/admin/ride-all': ['POST', []],
|
||||
'/api/proxy/admin/ride-move': ['POST', ['org']],
|
||||
// #1873 models-offered (A9): the owner's per-provider model lists, and one provider's on list.
|
||||
'/api/proxy/admin/models': ['GET', []],
|
||||
'/api/proxy/admin/models/set': ['POST', ['provider', 'on', 'revision', 'confirmInUse']],
|
||||
// #1873 settings-backend A1: reads for Model setup. The list names each read's query keys.
|
||||
'/api/proxy/admin/log': ['GET', ['lines']],
|
||||
'/api/proxy/admin/service-key': ['GET', []],
|
||||
@@ -110,6 +113,26 @@ export async function proxyAdminHTTP(req, res, { path, admin, call, named, teste
|
||||
if (Object.keys(args).some(k => !allowed.includes(k))) throw Error();
|
||||
} catch { return refuse('invalid-request'); }
|
||||
}
|
||||
// #1873 models-offered (A9). A model in use that a save would switch off is refused with who
|
||||
// uses it (organization and instance names only, and each organization whose usage is unknown),
|
||||
// so the page can ask in place. The read may write the first seed, so it seeds only when the
|
||||
// request passes the write checks above: a sending Console, same-origin fetch metadata, and no
|
||||
// other origin (a same-origin GET fetch sends none).
|
||||
if (path === '/api/proxy/admin/models' || path === '/api/proxy/admin/models/set') {
|
||||
try {
|
||||
if (path === '/api/proxy/admin/models') {
|
||||
const seed = send === true && req.headersDistinct['sec-fetch-site']?.length === 1 && req.headers['sec-fetch-site'] === 'same-origin'
|
||||
&& (req.headers.origin === undefined || (req.headersDistinct.origin?.length === 1 && req.headers.origin === origin));
|
||||
return done(200, await admin.models({ seed }));
|
||||
}
|
||||
if (!Array.isArray(args.on) || (Object.hasOwn(args, 'confirmInUse') && typeof args.confirmInUse !== 'boolean')) return refuse('invalid-request');
|
||||
return done(200, await admin.modelsSet({ provider: args.provider, on: args.on, revision: args.revision, confirmInUse: args.confirmInUse === true, user: typeof user === 'string' ? user : null }));
|
||||
} catch (error) {
|
||||
const code = ['models-offered-conflict', 'models-in-use', 'models-invalid', 'invalid-request', 'not-configured', 'proxy-down', 'proxy-admin-busy'].includes(error?.code) ? error.code : 'outcome-unknown';
|
||||
const status = code === 'models-offered-conflict' || code === 'models-in-use' ? 409 : STATUS[code] ?? 400;
|
||||
return done(status, { error: code, ...(code === 'models-in-use' ? { usedBy: Array.isArray(error.usedBy) ? error.usedBy : [], unanswered: Array.isArray(error.unanswered) ? error.unanswered : [] } : {}) });
|
||||
}
|
||||
}
|
||||
try {
|
||||
switch (path) {
|
||||
case '/api/proxy/admin/status': return done(200, await admin.status());
|
||||
|
||||
@@ -903,11 +903,112 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
setup.accounts(accountList.length);
|
||||
paintAccountCard();
|
||||
}
|
||||
// Models offered: read-only, from the routes read of an organization whose model list is ready.
|
||||
// Turning one model on or off is not built yet, so each switch reads Coming later.
|
||||
// Models offered. The instance owner switches models on or off per provider (#1873 models-offered,
|
||||
// A9, GET /api/proxy/admin/models and POST models/set). Anyone else reads the list from an
|
||||
// organization whose model list is ready, and each switch reads Coming later.
|
||||
let offeredRound = 0;
|
||||
async function offeredCall(path, args) {
|
||||
const response = await fetch('/api/proxy/admin/' + path, { cache: 'no-store', credentials: 'same-origin', redirect: 'manual', method: args === undefined ? 'GET' : 'POST',
|
||||
...(args === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(args) }) });
|
||||
if (response.type === 'opaqueredirect' || response.status === 401) throw Object.assign(new Error(), { code: 'signed-out' });
|
||||
let value = null; try { value = await response.json(); } catch { /* refused below */ }
|
||||
if (!response.ok) throw Object.assign(new Error(), { code: typeof value?.error === 'string' && /^[a-z-]+$/.test(value.error) ? value.error : 'outcome-unknown', usedBy: Array.isArray(value?.usedBy) ? value.usedBy : [], unanswered: Array.isArray(value?.unanswered) ? value.unanswered : [] });
|
||||
return value;
|
||||
}
|
||||
const OFFERED_SAYS = {
|
||||
'signed-out': 'Sign in to the Console again.',
|
||||
'models-offered-conflict': 'The model list changed since this page read it. Read it again, then make your change.',
|
||||
'models-invalid': 'The model service no longer lists one of these models. Read the list again.',
|
||||
'proxy-down': 'No organization that uses your model service answered, so its models can\'t be listed now.',
|
||||
'not-configured': 'No organization uses your model service yet. Its models show here once one does.',
|
||||
'proxy-admin-busy': 'Another change to the model service is running. Try again in a moment.',
|
||||
'outcome-unknown': 'The outcome is unknown. Read the list again before you try again.',
|
||||
};
|
||||
const offeredSays = code => Object.hasOwn(OFFERED_SAYS, code) ? OFFERED_SAYS[code] : `The change was refused (${code}).`;
|
||||
const offeredWho = u => { const org = window.MosaicOrg?.row?.(u.org)?.label || u.org; return `${u.instance ? `${org}'s ${u.instance}` : `an agent in ${org}`}${u.fallback ? ' fallback' : ''}`; };
|
||||
let offeredSaved = null;
|
||||
async function readOfferedOwner(round) {
|
||||
const box = $('proxy-offered-list'), saved = offeredSaved;
|
||||
const open = new Set([...box.querySelectorAll('details[data-offered][open]')].map(d => d.dataset.offered));
|
||||
offeredSaved = null;
|
||||
box.replaceChildren(el('p', 'Reading the models…', 'small muted'));
|
||||
let view;
|
||||
try { view = await offeredCall('models'); }
|
||||
catch (error) { if (round === offeredRound) box.replaceChildren(el('p', offeredSays(error.code), 'small muted')); return; }
|
||||
if (round !== offeredRound) return;
|
||||
const providers = Array.isArray(view?.providers) ? view.providers : [];
|
||||
if (!providers.length) { box.replaceChildren(el('p', 'Your model service lists no models yet.', 'small muted')); return; }
|
||||
box.replaceChildren(...providers.map(p => offeredList(p, view.revision, open.has(p.provider), saved === p.provider)));
|
||||
}
|
||||
function offeredList(p, revision, open, saved) {
|
||||
const name = String(p.label), models = Array.isArray(p.models) ? p.models : [];
|
||||
const details = el('details'), summary = el('summary', `${name} models offered: ${p.on} of ${p.total} on`), inside = el('div', undefined, 'inside');
|
||||
details.dataset.offered = p.provider; details.open = open; details.append(summary, inside);
|
||||
const form = el('form', undefined, 'settings-form'), set = el('fieldset'), list = el('ul', undefined, 'model-list');
|
||||
set.append(el('legend', `${name} models`), el('p', `A model you switch off is offered nowhere: not to any organization, agent or Triage. A model ${name} adds later shows here as New, switched off.`, 'help small muted'));
|
||||
if (models.length > 8) {
|
||||
const field = el('div', undefined, 'field'), id = `proxy-find-${String(p.provider).replace(/[^a-z0-9]/g, '')}`, label = el('label', `Find a ${name} model`), input = document.createElement('input');
|
||||
label.htmlFor = id; input.id = id; input.type = 'search'; input.autocomplete = 'off'; input.placeholder = 'Part of a name';
|
||||
input.addEventListener('input', () => { const q = input.value.trim().toLowerCase(); list.querySelectorAll('li').forEach(li => { li.hidden = Boolean(q) && !li.dataset.model.includes(q); }); });
|
||||
field.append(label, input); set.append(field);
|
||||
}
|
||||
const boxes = models.map(m => {
|
||||
const li = el('li'), label = el('label'), check = document.createElement('input'), note = el('span', '', 'small muted');
|
||||
check.type = 'checkbox'; check.checked = m.on === true; check.value = m.id; check.dataset.was = String(m.on === true);
|
||||
const users = Array.isArray(m.usedBy) ? m.usedBy : [];
|
||||
const paint = () => {
|
||||
const changed = String(check.checked) !== check.dataset.was;
|
||||
note.textContent = [m.isNew ? 'New' : '', users.length ? `In use: ${users.map(offeredWho).join(', ')}` : '', changed ? `Switched ${check.checked ? 'on' : 'off'}, not saved yet` : ''].filter(Boolean).join(' · ');
|
||||
};
|
||||
check.addEventListener('change', () => { paint(); dirty(); });
|
||||
label.append(check, ` ${m.label}`); li.dataset.model = String(m.id).toLowerCase(); li.append(label, note); paint();
|
||||
list.append(li); return { check, users, model: m };
|
||||
});
|
||||
set.append(list);
|
||||
const foot = el('div', undefined, 'form-foot'), save = el('button', `Save ${name} models`, 'btn primary'), said = el('p'), ask = el('div', undefined, 'banner ref');
|
||||
save.type = 'button'; save.dataset.offeredSave = ''; save.disabled = true; said.setAttribute('role', 'status'); if (saved) { said.className = 'settings-success'; said.textContent = `Saved. ${p.on} of ${p.total} on.`; } said.setAttribute('aria-live', 'polite'); ask.hidden = true; ask.setAttribute('role', 'alert');
|
||||
foot.append(save, said); form.append(set, foot, ask); inside.append(form);
|
||||
if (!offeredSend) { set.disabled = true; said.className = 'small muted'; said.textContent = 'This Console is read-only. Switching models on or off is unavailable.'; }
|
||||
function dirty() { save.disabled = !boxes.some(b => String(b.check.checked) !== b.check.dataset.was); ask.hidden = true; }
|
||||
async function send(confirmInUse) {
|
||||
save.disabled = true; set.disabled = true; ask.hidden = true; said.className = 'small muted'; said.textContent = 'Saving…';
|
||||
const on = boxes.filter(b => b.check.checked).map(b => b.model.id);
|
||||
try {
|
||||
await offeredCall('models/set', { provider: p.provider, on, revision, ...(confirmInUse ? { confirmInUse: true } : {}) });
|
||||
offeredSaved = p.provider; readOffered();
|
||||
} catch (error) {
|
||||
set.disabled = false; dirty();
|
||||
if (error.code === 'models-in-use') {
|
||||
said.textContent = ''; said.className = '';
|
||||
const who = error.usedBy.map(u => `${u.model}: ${offeredWho(u)}`).join('; ');
|
||||
const quiet = error.unanswered.map(org => window.MosaicOrg?.row?.(org)?.label || org).join(', ');
|
||||
const yes = el('button', 'Switch off anyway', 'btn'), no = el('button', 'Keep them on', 'btn'), actions = el('div', undefined, 'actions');
|
||||
yes.type = 'button'; no.type = 'button'; actions.append(yes, no);
|
||||
const says = [];
|
||||
if (who) says.push(el('p', `In use: ${who}. Switched off, a model is offered nowhere, so these can no longer use it. Give each one another model on its organization's Models page.`));
|
||||
if (quiet) says.push(el('p', `Not answering now, so it is not known which models they use: ${quiet}. A model you switch off stops working for them too.`));
|
||||
ask.replaceChildren(...says, actions);
|
||||
ask.hidden = false;
|
||||
yes.addEventListener('click', () => send(true));
|
||||
no.addEventListener('click', () => { ask.hidden = true; save.focus(); });
|
||||
yes.focus();
|
||||
return;
|
||||
}
|
||||
said.className = 'banner err'; said.textContent = offeredSays(error.code);
|
||||
if (['models-offered-conflict', 'models-invalid', 'outcome-unknown'].includes(error.code)) {
|
||||
const again = el('button', 'Read the list again', 'btn'); again.type = 'button'; again.addEventListener('click', () => readOffered()); said.append(' ', again);
|
||||
}
|
||||
}
|
||||
}
|
||||
// A plain button, not a submit: the read-only rule for organization pages hides submit buttons,
|
||||
// and this list is the instance owner's (offeredSend), not an organization's setting.
|
||||
save.addEventListener('click', () => { if (!save.disabled && offeredSend) send(false); });
|
||||
form.addEventListener('submit', event => event.preventDefault());
|
||||
return details;
|
||||
}
|
||||
async function readOffered() {
|
||||
const box = $('proxy-offered-list'), round = ++offeredRound;
|
||||
if (proxyAdmin) return readOfferedOwner(round);
|
||||
if (!accountList?.length) { box.replaceChildren(el('p', 'Add an account first. Its models show here.', 'small muted')); return; }
|
||||
const source = setup.readyOrg();
|
||||
const url = source ? `/api/orgs/${encodeURIComponent(source)}/bus/routes` : '/api/bus/routes';
|
||||
@@ -1189,6 +1290,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
'unit.install': 'Service installed', 'unit.start': 'Started', 'unit.stop': 'Stopped', 'unit.restart': 'Restarted',
|
||||
'ride-all': 'Organizations switched to your models', 'ride-move': `${some} switched to your models`, 'ride-intent': `Switching ${org ?? 'an organization'} to your models`,
|
||||
'ride-not-added': `${some} was not switched to your models`, 'ride-removed': `${some} stopped using your models`,
|
||||
'models.seed': 'Model lists recorded, every model on', 'models.set': provider ? `${provider} models switched on or off` : 'Models switched on or off',
|
||||
};
|
||||
const label = typeof entry.op === 'string' && Object.hasOwn(labels, entry.op) ? labels[entry.op] : 'Other setup action';
|
||||
const inOrg = org && String(entry.op).startsWith('account.') ? ` in ${org}` : '';
|
||||
@@ -1889,13 +1991,13 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
document.addEventListener('mosaic-org-restarted', onRestarted);
|
||||
const cleanup = () => { document.removeEventListener('mosaic-org-restarted', onRestarted); setup.stop(); clearTimeout(poll); login = null; const redirect=$('proxy-login-submit')?.elements.redirect_url, key=$('proxy-apikey')?.elements.key; if(redirect)redirect.value='';if(key)key.value=''; };
|
||||
window.addEventListener('pagehide', cleanup, {once:true});
|
||||
let devOwner = false, proxyAdmin = false;
|
||||
let devOwner = false, proxyAdmin = false, offeredSend = false;
|
||||
const NOT_SET = 'The model service is not set up on this instance.';
|
||||
fetch('/api/config', { cache: 'no-store' }).then(r => r.json()).then(config => {
|
||||
// F3: an organization's settings writes go with settingsSend (the org Console has no global send).
|
||||
canWrite = (config.send === true || config.settingsSend === true) && config.tester !== true && config.user !== true;
|
||||
devOwner = config.devOwner === true;
|
||||
proxyAdmin = config.proxyAdmin === true;
|
||||
proxyAdmin = config.proxyAdmin === true; offeredSend = proxyAdmin && config.proxyAdminSend === true;
|
||||
applyWrite();
|
||||
root.classList.toggle('solo', !proxyAdmin);
|
||||
if (proxyAdmin) { root.querySelectorAll('[data-admin]').forEach(part => { part.hidden = false; }); setup.start(config); }
|
||||
|
||||
@@ -20,6 +20,8 @@ const ROUTES = [
|
||||
['fence/clear', 'POST', {}], ['init-lock/clear', 'POST', {}],
|
||||
// #1873 ride-default: Ride all, and the move of one stopped fixture organization.
|
||||
['ride-all', 'POST', {}], ['ride-move', 'POST', { org: 'stand-in' }],
|
||||
// #1873 models-offered (A9): the owner's model lists, and one provider's on list.
|
||||
['models', 'GET'], ['models/set', 'POST', { provider: 'z.ai', on: [], revision: 'r' }],
|
||||
// #1873 settings-backend A1: the model service log, the service key's made-at time, setup history.
|
||||
['log', 'GET'], ['service-key', 'GET'], ['history', 'GET'],
|
||||
// #1873 settings-backend A2: one program off for every organization, and access health.
|
||||
@@ -45,6 +47,8 @@ function fakeAdmin() {
|
||||
recordAccount: entry => { calls.push(['recordAccount', entry]); return true; },
|
||||
programsOff: async args => { calls.push(['programsOff', args]); return { name: args.name, results: [], receipt: null }; },
|
||||
access: async () => { calls.push(['access']); return { organizations: [] }; },
|
||||
models: async args => { calls.push(['models', args]); return { revision: null, providers: [] }; },
|
||||
modelsSet: async args => { calls.push(['modelsSet', args]); return { provider: args.provider, revision: 'r2', on: 0, total: 0, receipt: null }; },
|
||||
};
|
||||
}
|
||||
const send = (port, path, { method = 'GET', headers = {}, body } = {}) => new Promise((resolve, reject) => {
|
||||
@@ -66,7 +70,7 @@ async function devServer(t, options = {}) {
|
||||
}
|
||||
const hit = (f, route, extra = {}) => send(f.port, `/api/proxy/admin/${route[0]}`, { method: route[1], headers: { ...f.headers(), ...extra }, body: route[2] });
|
||||
|
||||
test('the route table is exactly the brief: status, render, fetch, init, four unit verbs, fence clear, lock clear, ride all, ride move, log, service key, history, programs off, access', () => {
|
||||
test('the route table is exactly the brief: status, render, fetch, init, four unit verbs, fence clear, lock clear, ride all, ride move, models, models set, log, service key, history, programs off, access', () => {
|
||||
// #1873 account-remove: its two routes are tested in proxy-account-remove-http.test.mjs.
|
||||
assert.deepEqual(PROXY_ADMIN_PATHS, [...ROUTES.map(([p]) => `/api/proxy/admin/${p}`), '/api/proxy/admin/accounts/impact', '/api/proxy/admin/accounts/remove']);
|
||||
});
|
||||
@@ -77,7 +81,7 @@ test('the dev local owner reaches every route; init and fence clear go to the bu
|
||||
const r = await hit(f, route);
|
||||
assert.equal(r.status, route[0] === 'fetch' ? 202 : 200, route[0]);
|
||||
}
|
||||
assert.deepEqual(f.admin.calls.map(c => c[0]), ['status', 'render', 'fetchStart', 'init', 'unitAction', 'unitAction', 'unitAction', 'unitAction', 'fenceClear', 'initLockClear', 'rideAll', 'rideMove', 'log', 'serviceKey', 'history', 'programsOff', 'access']);
|
||||
assert.deepEqual(f.admin.calls.map(c => c[0]), ['status', 'render', 'fetchStart', 'init', 'unitAction', 'unitAction', 'unitAction', 'unitAction', 'fenceClear', 'initLockClear', 'rideAll', 'rideMove', 'models', 'modelsSet', 'log', 'serviceKey', 'history', 'programsOff', 'access']);
|
||||
assert.deepEqual(f.admin.calls.find(c => c[0] === 'programsOff')[1], { name: 'alpha', user: 'Local operator' });
|
||||
assert.deepEqual(f.admin.calls.filter(c => c[0] === 'unitAction').map(c => c[1]), ['install', 'start', 'stop', 'restart']);
|
||||
assert.deepEqual(f.busCalls.map(c => c[0]), ['proxy.init', 'proxy.fence.clear']);
|
||||
@@ -507,3 +511,159 @@ test('A2 end to end: programs off writes one receipt, skips a down bus, and no a
|
||||
assert.doesNotMatch(all, /ms[kotp]-[A-Za-z0-9_-]{4,}/);
|
||||
for (const bit of [TAIL, TAIL.slice(0, 10), root]) assert.equal(all.includes(bit), false, bit);
|
||||
});
|
||||
|
||||
// #1873 models-offered (A9): the owner's per-provider model lists.
|
||||
const MODELS = ROUTES.filter(([p]) => ['models', 'models/set'].includes(p));
|
||||
|
||||
test('models: a member and an organization owner get human-required on both routes, before any controller call', async t => {
|
||||
const organizations = { list: async () => [], resolve: async id => (id === 'x' ? { busHealthy: true } : null) };
|
||||
for (const session of [{ name: 'Bob', provider: 'local-dev', iss: 'local-dev', sub: 'bob', rootOwner: false, instanceRole: 'member' },
|
||||
{ name: 'Olive', provider: 'local-dev', iss: 'local-dev', sub: 'olive', rootOwner: false, instanceRole: 'operator', orgRole: 'owner' }]) {
|
||||
const f = await devServer(t, { organizations, sso: { ...createDevOwner(), session: () => session } });
|
||||
for (const route of MODELS) {
|
||||
const inOrg = await send(f.port, `/api/orgs/x/proxy/admin/${route[0]}`, { method: route[1], headers: f.headers(), body: route[2] });
|
||||
assert.equal(inOrg.status, 403, `${session.sub} ${route[0]}`); assert.deepEqual(inOrg.json, { error: 'human-required' }, `${session.sub} ${route[0]}`);
|
||||
const plain = await hit(f, route);
|
||||
assert.equal(plain.status >= 400 && plain.status < 500, true, `${session.sub} ${route[0]} outside an organization is refused`);
|
||||
}
|
||||
assert.deepEqual(f.admin.calls, []);
|
||||
}
|
||||
});
|
||||
|
||||
test('models set takes provider, an on list, revision and a true or false confirmInUse, nothing else; a refusal reaches the page as its code, in use with who', async t => {
|
||||
const f = await devServer(t);
|
||||
const base = { provider: 'z.ai', on: [], revision: 'a'.repeat(16) };
|
||||
for (const body of [{}, { ...base, on: 'glm-5' }, { ...base, on: null }, { ...base, confirmInUse: 'yes' }, { ...base, confirmInUse: 1 }, { ...base, extra: 1 }, { ...base, harness: 'pi' }])
|
||||
assert.deepEqual((await hit(f, ['models/set', 'POST', body])).json, { error: 'invalid-request' }, JSON.stringify(body));
|
||||
assert.deepEqual(f.admin.calls, []);
|
||||
assert.equal((await send(f.port, '/api/proxy/admin/models', { method: 'POST', headers: f.headers(), body: {} })).status, 405);
|
||||
assert.equal((await send(f.port, '/api/proxy/admin/models/set', { headers: f.headers() })).status, 405);
|
||||
assert.equal((await hit(f, ['models/set', 'POST', base])).status, 200);
|
||||
assert.equal((await hit(f, ['models/set', 'POST', { ...base, confirmInUse: true }])).status, 200);
|
||||
assert.deepEqual(f.admin.calls.map(c => c[1]), [{ ...base, confirmInUse: false, user: 'Local operator' }, { ...base, confirmInUse: true, user: 'Local operator' }]);
|
||||
const usedBy = [{ model: 'glm-5', org: 'acme', instance: 'assistant', fallback: false }];
|
||||
f.admin.modelsSet = async () => { throw Object.assign(new Error(`${SENTINEL} in use`), { code: 'models-in-use', usedBy, unanswered: ['bolt'] }); };
|
||||
const inUse = await hit(f, ['models/set', 'POST', base]);
|
||||
assert.equal(inUse.status, 409); assert.deepEqual(inUse.json, { error: 'models-in-use', usedBy, unanswered: ['bolt'] });
|
||||
f.admin.modelsSet = async () => { throw Object.assign(new Error(`${SENTINEL} in use`), { code: 'models-in-use', usedBy: 'x' }); };
|
||||
assert.deepEqual((await hit(f, ['models/set', 'POST', base])).json, { error: 'models-in-use', usedBy: [], unanswered: [] });
|
||||
for (const [code, status] of [['models-offered-conflict', 409], ['models-invalid', 400], ['proxy-admin-busy', 409], ['proxy-down', 503], ['not-configured', 503]]) {
|
||||
f.admin.modelsSet = async () => { throw Object.assign(new Error(`${SENTINEL} /home/owner/x`), { code, usedBy }); };
|
||||
const r = await hit(f, ['models/set', 'POST', base]);
|
||||
assert.equal(r.status, status, code); assert.deepEqual(r.json, { error: code }, code);
|
||||
}
|
||||
f.admin.modelsSet = async () => { throw Object.assign(new Error(SENTINEL), { code: 'proxy-file-refused' }); };
|
||||
assert.deepEqual((await hit(f, ['models/set', 'POST', base])).json, { error: 'outcome-unknown' });
|
||||
f.admin.models = async () => { throw new Error(SENTINEL); };
|
||||
const read = await hit(f, ['models', 'GET']);
|
||||
assert.equal(read.status, 503); assert.deepEqual(read.json, { error: 'outcome-unknown' });
|
||||
assert.equal(f.logs.join('\n').includes(SENTINEL), false);
|
||||
for (const code of ['models-offered-conflict', 'models-in-use', 'models-invalid']) assert.equal(typeof REFUSALS[code]?.nextStep, 'string', code);
|
||||
});
|
||||
|
||||
// The read may write the first seed, so it asks for one only when the request passes the write checks.
|
||||
test('models read: the seed is asked for only by a sending Console on a same-origin request', async t => {
|
||||
const f = await devServer(t);
|
||||
const seeds = async (headers, server = f) => {
|
||||
server.admin.calls.length = 0;
|
||||
const all = { ...server.headers(), ...headers };
|
||||
for (const [k, v] of Object.entries(all)) if (v === undefined) delete all[k];
|
||||
const r = await send(server.port, '/api/proxy/admin/models', { headers: all });
|
||||
assert.equal(r.status, 200);
|
||||
return server.admin.calls[0][1].seed;
|
||||
};
|
||||
assert.equal(await seeds({}), true, 'same origin, with the Origin header');
|
||||
assert.equal(await seeds({ origin: undefined }), true, 'a same-origin GET fetch sends no Origin');
|
||||
assert.equal(await seeds({ 'sec-fetch-site': 'cross-site' }), false, 'cross-site');
|
||||
assert.equal(await seeds({ 'sec-fetch-site': 'same-site' }), false, 'same-site');
|
||||
assert.equal(await seeds({ 'sec-fetch-site': undefined }), false, 'no fetch metadata');
|
||||
f.admin.calls.length = 0;
|
||||
assert.equal((await send(f.port, '/api/proxy/admin/models', { headers: { ...f.headers(), origin: 'http://evil.example' } })).status, 403, 'a foreign Origin never reaches the read');
|
||||
assert.deepEqual(f.admin.calls, []);
|
||||
const readOnly = await devServer(t, { send: null });
|
||||
assert.equal(await seeds({}, readOnly), false, 'a read-only Console');
|
||||
});
|
||||
|
||||
// The real controller behind the real routes, with fake organizations whose route answers carry a planted key.
|
||||
test('models end to end: the first read seeds every present model on and seen; a stale revision, a model in use and an organization that does not answer refuse; confirm saves; a new model reads New and off; receipts and the file hold labels only', async t => {
|
||||
const { createProxyAdmin } = await import('../../model-proxy/src/admin-control.mjs');
|
||||
const { mkdirSync, statSync, existsSync } = await import('node:fs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'pa-mo-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
|
||||
mkdirSync(configDir, { mode: 0o700 }); mkdirSync(dataRoot, { mode: 0o700 });
|
||||
const planted = `msk-k1a2-Ab3_dE5-fG7hJ9kL1mN3pQ5rS7tU9vW1xY3zA5bC7dE`;
|
||||
const catalogue = [['zai', 'glm-5'], ['zai', 'glm-4.6'], ['codex', 'gpt-5']];
|
||||
const entry = ([upstream, model]) => ({ key: `${upstream}-${model}`.replace(/\./g, '-'), module: 'cliproxy', upstream, model, available: true, reason: null, harnesses: ['claude-code', 'pi'] });
|
||||
const org = (id, { down = false, cliproxy = true, instances = {} } = {}) => ({
|
||||
id, fixture: false, cliproxy, changes: '', down,
|
||||
file: async () => ({ document: { roles: {} }, revision: 'c'.repeat(64) }),
|
||||
async call(verb) {
|
||||
if (this.down) throw Object.assign(new Error(planted), { code: 'outcome-unknown' });
|
||||
if (verb === 'routes') return { business: id, revision: 'c'.repeat(64), note: planted, instances,
|
||||
providerModels: { glm5: { module: 'cliproxy', upstream: 'zai', model: 'glm-5', provider: 'zai' }, gpt5: { module: 'cliproxy', upstream: 'codex', model: 'gpt-5', provider: 'codex' } },
|
||||
catalogue: { status: 'ready', models: catalogue.map(entry), notices: [] } };
|
||||
throw Object.assign(new Error(planted), { code: 'invalid-request' });
|
||||
},
|
||||
});
|
||||
const orgs = [org('acme', { instances: { assistant: { model: 'glm5', fallback: { model: 'gpt5' } }, idle: { model: 'none' } } }), org('bolt', { down: true }), org('none', { cliproxy: false, instances: { assistant: { model: 'glm5' } } })];
|
||||
const admin = createProxyAdmin({ dataRoot, configDir, unit: { unit: 'mosaic-proxy-zz.service', status: async () => ({ installed: false }) }, buses: async () => ({ stopped: true, running: [] }), now: () => new Date(0), env: {},
|
||||
riders: async () => orgs, harnesses: () => [], rootAgents: () => ({ state: 'absent', agents: {}, assistant: null }) });
|
||||
const f = await devServer(t, { proxyAdmin: admin });
|
||||
const file = join(dataRoot, 'state', 'models-offered.json');
|
||||
const crossSite = await hit(f, ['models', 'GET'], { 'sec-fetch-site': 'cross-site' });
|
||||
assert.equal(crossSite.status, 200);
|
||||
assert.equal(existsSync(file), false, 'a cross-site read seeds nothing');
|
||||
const waiting = await hit(f, ['models', 'GET']);
|
||||
assert.deepEqual(waiting.json.unanswered, ['bolt'], 'bolt\'s bus is down, so its usage is unknown');
|
||||
assert.equal(existsSync(file), false, 'no seed while an organization\'s usage is unknown');
|
||||
orgs[1].down = false;
|
||||
const first = await hit(f, ['models', 'GET']);
|
||||
assert.equal(first.status, 200);
|
||||
assert.deepEqual(first.json.unanswered, []);
|
||||
orgs[1].down = true;
|
||||
assert.match(first.json.revision, /^[a-f0-9]{16}$/);
|
||||
assert.deepEqual(first.json.providers.map(p => [p.provider, p.on, p.total]), [['z.ai', 2, 2], ['codex', 1, 1]]);
|
||||
assert.deepEqual(first.json.providers[0].models, [
|
||||
{ id: 'glm-5', label: 'glm-5', on: true, isNew: false, usedBy: [{ org: 'acme', instance: 'assistant', fallback: false }] },
|
||||
{ id: 'glm-4.6', label: 'glm-4.6', on: true, isNew: false, usedBy: [] }]);
|
||||
assert.deepEqual(first.json.providers[1].models[0].usedBy, [{ org: 'acme', instance: 'assistant', fallback: true }]);
|
||||
assert.deepEqual(JSON.parse(readFileSync(file, 'utf8')), { version: 1, providers: { 'z.ai': { on: ['glm-5', 'glm-4.6'], seen: ['glm-5', 'glm-4.6'] }, codex: { on: ['gpt-5'], seen: ['gpt-5'] } } });
|
||||
assert.equal(statSync(file).mode & 0o777, 0o600);
|
||||
// A second read writes nothing more.
|
||||
assert.equal((await hit(f, ['models', 'GET'])).json.revision, first.json.revision);
|
||||
const stale = await hit(f, ['models/set', 'POST', { provider: 'z.ai', on: ['glm-4.6'], revision: 'f'.repeat(16) }]);
|
||||
assert.equal(stale.status, 409); assert.deepEqual(stale.json, { error: 'models-offered-conflict' });
|
||||
const inUse = await hit(f, ['models/set', 'POST', { provider: 'z.ai', on: ['glm-4.6'], revision: first.json.revision }]);
|
||||
assert.equal(inUse.status, 409);
|
||||
assert.deepEqual(inUse.json, { error: 'models-in-use', usedBy: [{ model: 'glm-5', org: 'acme', instance: 'assistant', fallback: false }], unanswered: ['bolt'] });
|
||||
const fallback = await hit(f, ['models/set', 'POST', { provider: 'codex', on: [], revision: first.json.revision, confirmInUse: false }]);
|
||||
assert.deepEqual(fallback.json, { error: 'models-in-use', usedBy: [{ model: 'gpt-5', org: 'acme', instance: 'assistant', fallback: true }], unanswered: ['bolt'] }, 'a fallback model counts as in use');
|
||||
const quiet = await hit(f, ['models/set', 'POST', { provider: 'z.ai', on: ['glm-5'], revision: first.json.revision }]);
|
||||
assert.deepEqual(quiet.json, { error: 'models-in-use', usedBy: [], unanswered: ['bolt'] }, 'glm-4.6 has no known user, but bolt did not answer');
|
||||
const unknown = await hit(f, ['models/set', 'POST', { provider: 'z.ai', on: ['glm-4.6', 'made-up'], revision: first.json.revision }]);
|
||||
assert.equal(unknown.status, 400); assert.deepEqual(unknown.json, { error: 'models-invalid' }, 'a model never listed cannot be switched on');
|
||||
assert.deepEqual((await hit(f, ['models/set', 'POST', { provider: 'claude', on: [], revision: first.json.revision }])).json, { error: 'models-invalid' }, 'a provider no organization lists');
|
||||
assert.deepEqual(JSON.parse(readFileSync(file, 'utf8')).providers['z.ai'].on, ['glm-5', 'glm-4.6'], 'nothing refused was written');
|
||||
const saved = await hit(f, ['models/set', 'POST', { provider: 'z.ai', on: ['glm-4.6'], revision: first.json.revision, confirmInUse: true }]);
|
||||
assert.equal(saved.status, 200);
|
||||
assert.equal(saved.json.on, 1); assert.equal(saved.json.total, 2);
|
||||
assert.notEqual(saved.json.revision, first.json.revision);
|
||||
assert.deepEqual(saved.json.receipt, { time: new Date(0).toISOString(), op: 'models.set', provider: 'z.ai', on: [], off: ['glm-5'], inUse: [{ model: 'glm-5', org: 'acme', instance: 'assistant' }], unanswered: ['bolt'], user: 'Local operator' });
|
||||
assert.deepEqual((await hit(f, ['models/set', 'POST', { provider: 'z.ai', on: ['glm-5', 'glm-4.6'], revision: first.json.revision }])).json, { error: 'models-offered-conflict' }, 'the old revision is stale now');
|
||||
// A model the provider adds later reads New and off.
|
||||
catalogue.push(['zai', 'glm-6']);
|
||||
const later = await hit(f, ['models', 'GET']);
|
||||
assert.equal(later.json.revision, saved.json.revision, 'a known provider is not seeded again');
|
||||
assert.deepEqual(later.json.providers[0].models.map(m => [m.id, m.on, m.isNew]), [['glm-5', false, false], ['glm-4.6', true, false], ['glm-6', false, true]]);
|
||||
const doc = JSON.parse(readFileSync(file, 'utf8'));
|
||||
assert.deepEqual(Object.keys(doc), ['version', 'providers']);
|
||||
for (const e of Object.values(doc.providers)) assert.deepEqual(Object.keys(e), ['on', 'seen']);
|
||||
const lines = readFileSync(join(dataRoot, 'state', 'proxy-admin.jsonl'), 'utf8').trim().split('\n').map(l => JSON.parse(l));
|
||||
assert.deepEqual(lines.map(l => l.op), ['models.seed', 'models.set']);
|
||||
assert.deepEqual(lines[0].providers, [{ provider: 'z.ai', on: 2 }, { provider: 'codex', on: 1 }]);
|
||||
const history = await hit(f, ['history', 'GET']);
|
||||
assert.deepEqual(history.json.entries.map(e => e.op), ['models.seed', 'models.set']);
|
||||
const all = [first.text, stale.text, inUse.text, saved.text, later.text, history.text, readFileSync(file, 'utf8'), JSON.stringify(lines), f.logs.join('\n')].join('\n');
|
||||
for (const bit of [planted, 'msk-', root, '/home/']) assert.equal(all.includes(bit), false, bit);
|
||||
});
|
||||
@@ -21,10 +21,22 @@ test('a3: no provider id, sign-in host or key base URL is written out in client.
|
||||
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']) {
|
||||
for (const file of ['../../model-proxy/src/client.mjs', '../../bus/src/proxy-page.mjs', '../src/public/display.js', '../../model-proxy/src/models-offered.mjs']) {
|
||||
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`);
|
||||
}
|
||||
});
|
||||
|
||||
// #1873 models-offered (A9): the offered file holds provider and model ids only. A harness, key or
|
||||
// label field refuses the whole file, so the file can switch a model off but never says where it runs.
|
||||
test('models-offered: the file takes version, providers, on and seen only; anything else reads as damaged', async () => {
|
||||
const { parseOffered } = await import('../../model-proxy/src/models-offered.mjs');
|
||||
const good = { version: 1, providers: { 'z.ai': { on: ['glm-5'], seen: ['glm-5'] } } };
|
||||
assert.deepEqual(parseOffered(good), good);
|
||||
for (const bad of [{ ...good, harness: 'pi' }, { ...good, version: 2 }, { version: 1, providers: { 'z.ai': { on: ['glm-5'], seen: ['glm-5'], harnesses: ['pi'] } } },
|
||||
{ version: 1, providers: { 'z.ai': { on: ['glm-5'], seen: ['glm-5'], key: 'x' } } }, { version: 1, providers: { 'z.ai': { on: ['glm-5'], seen: [] } } },
|
||||
{ version: 1, providers: { 'z.ai': { on: ['glm-5', 'glm-5'], seen: ['glm-5'] } } }, { version: 1, providers: { '../x': { on: [], seen: [] } } }, { version: 1, providers: [] }])
|
||||
assert.equal(parseOffered(bad), null, JSON.stringify(bad));
|
||||
});
|
||||
@@ -0,0 +1,264 @@
|
||||
// #1873 models-offered (A9; settings-backend DESIGN.md section 2, settings-walk DESIGN.md 3.3, mockup
|
||||
// models-offered): Model setup, Accounts, Models offered. The instance owner's page reads
|
||||
// GET /api/proxy/admin/models and shows one list per provider with a count, New and In use notes, a
|
||||
// search past eight, and a Save that stays disabled until a box changes. Save posts one provider's on
|
||||
// list with the read's revision (POST /api/proxy/admin/models/set). A model in use that a save would
|
||||
// switch off is refused with who uses it, and the page asks in place before it sends confirmInUse. A
|
||||
// page without proxyAdmin sends no /api/proxy/admin/ request; a read-only owner page changes nothing.
|
||||
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 { publicProviders } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
import { browser } from './browser.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
|
||||
const LIST = [
|
||||
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
|
||||
{ id: 'lab', label: 'Lab Bench', theme: 'cobalt', busHealthy: true },
|
||||
];
|
||||
const ROUTES = {
|
||||
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 () => ({ ...ROUTES, 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' } } };
|
||||
}
|
||||
|
||||
const SERVICE_UP = { next: ['accounts'], init: { initialized: true, partial: false, problem: null, settings: { port: 18432 }, 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: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 12 } }], ride: [{ id: 'acme', state: 'already' }], providers: publicProviders() };
|
||||
const ACCOUNTS = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 1 }, { accountId: 'a2', provider: 'z.ai', displayName: 'z.ai key', status: 'active', priority: 0 }];
|
||||
// The read's names and counts only: the page holds no model or provider list of its own.
|
||||
const m = (id, on, extra = {}) => ({ id, label: id, on, isNew: false, usedBy: [], ...extra });
|
||||
const VIEW = { revision: 'r1', providers: [
|
||||
{ provider: 'claude', label: 'Claude', on: 2, total: 3, models: [m('claude-opus-5-5', true), m('claude-sonnet-5-5', true, { usedBy: [{ org: 'acme', instance: 'assistant', fallback: false }, { org: 'lab', instance: 'chief', fallback: true }] }), m('claude-next-6', false, { isNew: true })] },
|
||||
{ provider: 'z.ai', label: 'z.ai', on: 9, total: 9, models: Array.from({ length: 9 }, (_, i) => m(`glm-5.${i}`, true)) },
|
||||
] };
|
||||
const SAVED = { revision: 'r2', providers: [{ ...VIEW.providers[0], on: 1, models: VIEW.providers[0].models.map(x => x.id === 'claude-opus-5-5' ? { ...x, on: false } : x) }, VIEW.providers[1]] };
|
||||
|
||||
// The owner's flags, the status, the accounts, and the admin reads and writes by name (a list: each
|
||||
// call takes the next one and the last one stays). window.__admin records every /api/proxy/admin/
|
||||
// request and window.__writes every write's body.
|
||||
const stub = ({ owner = true, send = owner, admin = {} } = {}) => `(() => {
|
||||
const real = window.fetch.bind(window);
|
||||
window.__mo = ${JSON.stringify({ owner, send, admin, service: SERVICE_UP, accounts: ACCOUNTS })}; 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: name, body: init.body ? JSON.parse(init.body) : null });
|
||||
if (name === 'status') return json(__mo.service);
|
||||
const a = next(__mo.admin[method === 'GET' ? name : method + ' ' + name]);
|
||||
if (!a) return json({ error: 'fixture-unexpected-api' }, 403);
|
||||
return a.status ? json(a.body, a.status) : json(a);
|
||||
}
|
||||
if (method !== 'GET' && /\\/proxy\\//.test(path)) { window.__writes.push({ path, 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, ...(__mo.owner ? { proxyAdmin: true, proxyAdminSend: __mo.send } : {}) }); }
|
||||
if (path.endsWith('/proxy/accounts')) return json({ accounts: __mo.accounts, providers: ${JSON.stringify(publicProviders())} });
|
||||
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, { 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}/#/settings/model-setup?step=accounts`);
|
||||
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 click = sel => b.evaluate(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) throw Error("no ${sel.replace(/"/g, '')}"); el.click(); return true; })()`);
|
||||
return { b, wait, click, admin: () => b.evaluate('window.__admin'), writes: () => b.evaluate('window.__writes') };
|
||||
}
|
||||
const LISTED = 'document.querySelectorAll("#proxy-accounts li[data-account]").length === 2';
|
||||
const CLAUDE = '#proxy-offered-list details[data-offered=claude]';
|
||||
const ZAI = '#proxy-offered-list details[data-offered="z.ai"]';
|
||||
async function openOffered(b, wait) {
|
||||
await wait(LISTED);
|
||||
await b.evaluate('document.querySelector("#proxy-offered").open = true; true');
|
||||
await wait(`document.querySelector(${JSON.stringify(CLAUDE)})`);
|
||||
await b.evaluate(`document.querySelector(${JSON.stringify(CLAUDE)}).open = true; true`);
|
||||
}
|
||||
const rows = (b, sel) => b.evaluate(`[...document.querySelectorAll(${JSON.stringify(sel + ' li')})].map(li => ({ id: li.dataset.model, on: li.querySelector("input").checked, note: li.querySelector(".small").textContent }))`);
|
||||
const toggle = (b, id) => b.evaluate(`(() => { const c = document.querySelector('${CLAUDE} input[value="${id}"]'); c.click(); return c.checked; })()`);
|
||||
const save = sel => `document.querySelector(${JSON.stringify(sel + ' button[data-offered-save]')})`;
|
||||
|
||||
test('models-offered page: the owner sees one list per provider with its count, New and In use notes naming who, a search past eight, and a dimmed Save; reading writes nothing', { timeout: 90000 }, async t => {
|
||||
const { b, wait, admin } = await setup(t, { admin: { models: VIEW } });
|
||||
await openOffered(b, wait);
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-offered-list details[data-offered] > summary")].map(s => s.textContent)'), ['Claude models offered: 2 of 3 on', 'z.ai models offered: 9 of 9 on']);
|
||||
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(CLAUDE + ' legend')}).textContent`), 'Claude models');
|
||||
assert.match(await b.evaluate(`document.querySelector(${JSON.stringify(CLAUDE + ' .help')}).textContent`), /offered nowhere: not to any organization, agent or Triage\. A model Claude adds later shows here as New, switched off\./);
|
||||
assert.deepEqual(await rows(b, CLAUDE), [
|
||||
{ id: 'claude-opus-5-5', on: true, note: '' },
|
||||
{ id: 'claude-sonnet-5-5', on: true, note: 'In use: Acme Studio\'s assistant, Lab Bench\'s chief fallback' },
|
||||
{ id: 'claude-next-6', on: false, note: 'New' },
|
||||
]);
|
||||
// Every box has a label, and the Save of each list is disabled until a box in it changes.
|
||||
assert.equal(await b.evaluate('[...document.querySelectorAll("#proxy-offered-list input[type=checkbox]")].every(c => c.closest("label") && !c.disabled)'), true);
|
||||
assert.deepEqual(await b.evaluate(`[${save(CLAUDE)}, ${save(ZAI)}].map(s => [s.textContent, s.disabled])`), [['Save Claude models', true], ['Save z.ai models', true]]);
|
||||
// Search only on the list longer than eight; it ignores case.
|
||||
assert.equal(await b.evaluate(`!!document.querySelector(${JSON.stringify(CLAUDE + ' input[type=search]')})`), false);
|
||||
await b.evaluate(`(() => { document.querySelector(${JSON.stringify(ZAI)}).open = true; const i = document.querySelector(${JSON.stringify(ZAI + ' input[type=search]')}); i.value = 'GLM-5.7'; i.dispatchEvent(new Event('input')); return true; })()`);
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll(${JSON.stringify(ZAI + ' li')})].filter(li => !li.hidden).map(li => li.dataset.model)`), ['glm-5.7']);
|
||||
assert.equal(await b.evaluate(`document.querySelector('label[for="' + document.querySelector(${JSON.stringify(ZAI + ' input[type=search]')}).id + '"]').textContent`), 'Find a z.ai model');
|
||||
assert.deepEqual((await admin()).filter(r => r.startsWith('POST')), [], 'reading the lists writes nothing');
|
||||
assert.equal((await admin()).filter(r => r === 'GET models').length, 1);
|
||||
});
|
||||
|
||||
test('models-offered page: a changed box says so and lights Save; changing it back dims Save; Save sends the list with the revision and keeps the list open with a saved line', { timeout: 90000 }, async t => {
|
||||
const { b, wait, writes } = await setup(t, { admin: { models: [VIEW, SAVED], 'POST models/set': { provider: 'claude', revision: 'r2', on: 1, total: 3, receipt: { op: 'models.set' } } } });
|
||||
await openOffered(b, wait);
|
||||
assert.equal(await toggle(b, 'claude-next-6'), true);
|
||||
assert.equal((await rows(b, CLAUDE))[2].note, 'New · Switched on, not saved yet');
|
||||
assert.equal(await b.evaluate(`${save(CLAUDE)}.disabled`), false);
|
||||
assert.equal(await b.evaluate(`${save(ZAI)}.disabled`), true, 'the other list keeps its Save dimmed');
|
||||
await toggle(b, 'claude-next-6');
|
||||
assert.equal((await rows(b, CLAUDE))[2].note, 'New');
|
||||
assert.equal(await b.evaluate(`${save(CLAUDE)}.disabled`), true, 'back as read: Save is dimmed again');
|
||||
assert.equal(await toggle(b, 'claude-opus-5-5'), false);
|
||||
assert.equal((await rows(b, CLAUDE))[0].note, 'Switched off, not saved yet');
|
||||
await b.evaluate(`${save(CLAUDE)}.click(); true`);
|
||||
await wait(`document.querySelector(${JSON.stringify(CLAUDE + ' > summary')})?.textContent === "Claude models offered: 1 of 3 on"`);
|
||||
assert.deepEqual(await writes(), [{ path: 'models/set', body: { provider: 'claude', on: ['claude-sonnet-5-5'], revision: 'r1' } }]);
|
||||
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(CLAUDE)}).open`), true, 'the saved list stays open');
|
||||
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(CLAUDE + ' [role=status]')}).textContent`), 'Saved. 1 of 3 on.');
|
||||
assert.equal((await rows(b, CLAUDE))[0].on, false);
|
||||
});
|
||||
|
||||
test('models-offered page: switching off a model in use asks in place, naming who uses it; Keep them on sends nothing more, Switch off anyway sends confirmInUse', { timeout: 90000 }, async t => {
|
||||
const inUse = { status: 409, body: { error: 'models-in-use', usedBy: [{ model: 'claude-sonnet-5-5', org: 'acme', instance: 'assistant', fallback: false }, { model: 'claude-sonnet-5-5', org: 'lab', instance: 'chief', fallback: true }] } };
|
||||
const done = { provider: 'claude', revision: 'r2', on: 1, total: 3, receipt: { op: 'models.set' } };
|
||||
const { b, wait, writes } = await setup(t, { admin: { models: VIEW, 'POST models/set': [inUse, inUse, done] } });
|
||||
await openOffered(b, wait);
|
||||
await toggle(b, 'claude-sonnet-5-5');
|
||||
await b.evaluate(`${save(CLAUDE)}.click(); true`);
|
||||
const ASK = CLAUDE + ' [role=alert]';
|
||||
await wait(`document.querySelector(${JSON.stringify(ASK)}) && !document.querySelector(${JSON.stringify(ASK)}).hidden`);
|
||||
const ask = await b.evaluate(`document.querySelector(${JSON.stringify(ASK)}).textContent`);
|
||||
assert.match(ask, /In use: claude-sonnet-5-5: Acme Studio's assistant; claude-sonnet-5-5: Lab Bench's chief fallback\./);
|
||||
assert.match(ask, /Give each one another model on its organization's Models page\./);
|
||||
assert.equal(await b.evaluate('document.activeElement.textContent'), 'Switch off anyway', 'focus moves to the question');
|
||||
assert.deepEqual((await writes()).map(w => w.body.confirmInUse), [undefined], 'the first save does not confirm');
|
||||
await b.evaluate(`[...document.querySelectorAll(${JSON.stringify(ASK + ' button')})].find(x => x.textContent === 'Keep them on').click(); true`);
|
||||
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(ASK)}).hidden`), true);
|
||||
assert.equal((await writes()).length, 1, 'Keep them on sends nothing');
|
||||
assert.equal((await rows(b, CLAUDE))[1].on, false, 'the box stays as the owner left it, still unsaved');
|
||||
await b.evaluate(`${save(CLAUDE)}.click(); true`);
|
||||
await wait(`!document.querySelector(${JSON.stringify(ASK)}).hidden`);
|
||||
await b.evaluate(`[...document.querySelectorAll(${JSON.stringify(ASK + ' button')})].find(x => x.textContent === 'Switch off anyway').click(); true`);
|
||||
await wait('window.__writes.length === 3');
|
||||
assert.deepEqual((await writes())[2].body, { provider: 'claude', on: ['claude-opus-5-5'], revision: 'r1', confirmInUse: true });
|
||||
});
|
||||
|
||||
test('models-offered page: an organization that is not answering is named in the ask, labelled where known; a user named by the organization file with no instance reads as an agent in it', { timeout: 90000 }, async t => {
|
||||
const quiet = { status: 409, body: { error: 'models-in-use', usedBy: [{ model: 'claude-sonnet-5-5', org: 'acme', instance: null, fallback: false }], unanswered: ['lab', 'zeta'] } };
|
||||
const done = { provider: 'claude', revision: 'r2', on: 1, total: 3, receipt: { op: 'models.set' } };
|
||||
const { b, wait, writes } = await setup(t, { admin: { models: VIEW, 'POST models/set': [quiet, done] } });
|
||||
await openOffered(b, wait);
|
||||
await toggle(b, 'claude-sonnet-5-5');
|
||||
await b.evaluate(`${save(CLAUDE)}.click(); true`);
|
||||
const ASK = CLAUDE + ' [role=alert]';
|
||||
await wait(`document.querySelector(${JSON.stringify(ASK)}) && !document.querySelector(${JSON.stringify(ASK)}).hidden`);
|
||||
const ask = await b.evaluate(`document.querySelector(${JSON.stringify(ASK)}).textContent`);
|
||||
assert.match(ask, /Not answering now, so it is not known which models they use: Lab Bench, zeta\. A model you switch off stops working for them too\./);
|
||||
assert.match(ask, /In use: claude-sonnet-5-5: an agent in Acme Studio\./);
|
||||
await b.evaluate(`[...document.querySelectorAll(${JSON.stringify(ASK + ' button')})].find(x => x.textContent === 'Switch off anyway').click(); true`);
|
||||
await wait('window.__writes.length === 2');
|
||||
assert.equal((await writes())[1].body.confirmInUse, true);
|
||||
});
|
||||
|
||||
test('models-offered page: a save after another change is refused as a conflict, worded, with Read the list again; a busy or unknown answer is worded too', { timeout: 90000 }, async t => {
|
||||
const conflict = { status: 409, body: { error: 'models-offered-conflict' } };
|
||||
const busy = { status: 409, body: { error: 'proxy-admin-busy' } };
|
||||
const { b, wait, admin } = await setup(t, { admin: { models: [VIEW, SAVED], 'POST models/set': [busy, conflict] } });
|
||||
await openOffered(b, wait);
|
||||
await toggle(b, 'claude-opus-5-5');
|
||||
const SAID = CLAUDE + ' [role=status]';
|
||||
await b.evaluate(`${save(CLAUDE)}.click(); true`);
|
||||
await wait(`/Another change to the model service is running/.test(document.querySelector(${JSON.stringify(SAID)}).textContent)`);
|
||||
assert.equal(await b.evaluate(`!!document.querySelector(${JSON.stringify(SAID + ' button')})`), false, 'busy: try again, no reread');
|
||||
assert.equal(await b.evaluate(`${save(CLAUDE)}.disabled`), false, 'the change is kept, so Save can be pressed again');
|
||||
await b.evaluate(`${save(CLAUDE)}.click(); true`);
|
||||
await wait(`/The model list changed since this page read it/.test(document.querySelector(${JSON.stringify(SAID)}).textContent)`);
|
||||
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(SAID)}).className`), 'banner err');
|
||||
await b.evaluate(`document.querySelector(${JSON.stringify(SAID + ' button')}).click(); true`);
|
||||
await wait(`document.querySelector(${JSON.stringify(CLAUDE + ' > summary')})?.textContent === "Claude models offered: 1 of 3 on"`);
|
||||
assert.equal((await admin()).filter(r => r === 'GET models').length, 2, 'Read the list again reads it');
|
||||
});
|
||||
|
||||
test('models-offered page: a page without proxyAdmin sends no /api/proxy/admin/ request; a read-only owner page shows the list and can change nothing', { timeout: 90000 }, async t => {
|
||||
{
|
||||
const { b, wait, admin } = await setup(t, { owner: false });
|
||||
await wait(LISTED);
|
||||
await b.evaluate('document.querySelector("#proxy-offered").open = true; true');
|
||||
await wait('document.querySelector("#proxy-offered-list p")');
|
||||
assert.deepEqual(await admin(), [], 'no admin read or write at all');
|
||||
}
|
||||
{
|
||||
const { b, wait, writes } = await setup(t, { send: false, admin: { models: VIEW } });
|
||||
await openOffered(b, wait);
|
||||
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(CLAUDE + ' fieldset')}).disabled`), true);
|
||||
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(CLAUDE + ' [role=status]')}).textContent`), 'This Console is read-only. Switching models on or off is unavailable.');
|
||||
await b.evaluate(`(() => { const s = ${save(CLAUDE)}; s.disabled = false; s.click(); document.querySelector(${JSON.stringify(CLAUDE + ' form')}).requestSubmit(); return true; })()`);
|
||||
assert.deepEqual(await writes(), []);
|
||||
}
|
||||
});
|
||||
|
||||
test('models-offered page: a read the model service cannot answer is worded, never an empty list', { timeout: 90000 }, async t => {
|
||||
for (const [body, line] of [
|
||||
[{ error: 'proxy-down' }, /No organization that uses your model service answered/],
|
||||
[{ error: 'not-configured' }, /No organization uses your model service yet/],
|
||||
[{ error: 'outcome-unknown' }, /The outcome is unknown/],
|
||||
]) {
|
||||
const { b, wait } = await setup(t, { admin: { models: { status: 503, body } } });
|
||||
await wait(LISTED);
|
||||
await b.evaluate('document.querySelector("#proxy-offered").open = true; true');
|
||||
await wait(`${line}.test(document.querySelector("#proxy-offered-list").textContent)`);
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("#proxy-offered-list details[data-offered]").length'), 0);
|
||||
await b.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('models-offered page: at 390 wide the lists fit, every row keeps 44px, and nothing scrolls sideways', { timeout: 90000 }, async t => {
|
||||
const { b, wait } = await setup(t, { viewport: [390, 844], admin: { models: VIEW } });
|
||||
await openOffered(b, wait);
|
||||
await toggle(b, 'claude-next-6');
|
||||
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true);
|
||||
assert.equal(await b.evaluate(`[...document.querySelectorAll(${JSON.stringify(CLAUDE + ' li')})].every(li => li.getBoundingClientRect().height >= 44 && li.getBoundingClientRect().right <= document.documentElement.clientWidth)`), true);
|
||||
assert.equal(await b.evaluate(`${save(CLAUDE)}.checkVisibility()`), true);
|
||||
});
|
||||
@@ -70,6 +70,7 @@ const ownerStub = (service = SERVICE_UP, extra = {}) => `(() => {
|
||||
if (__s4.routes && /\\/bus\\/routes$/.test(path)) return json(__s4.routes);
|
||||
if (/\\/api\\/(orgs\\/[^/]+\\/)?config$/.test(path)) { const c = await (await real(input, init)).json(); return json({ ...c, orgSetup: true, proxyAdmin: true, proxyAdminSend: true, ...(/\\/orgs\\//.test(path) ? { settingsSend: true } : {}) }); }
|
||||
if (path.endsWith('/proxy/admin/status')) return json(__s4.service);
|
||||
if (__s4.offered && path.endsWith('/proxy/admin/models')) return json(__s4.offered);
|
||||
if (path.endsWith('/proxy/accounts')) return json({ accounts: __s4.accounts });
|
||||
if (path.endsWith('/proxy/keys')) return json({ keys: [] });
|
||||
if (path.endsWith('/triage/route')) return json({ route: null });
|
||||
@@ -395,13 +396,16 @@ test('settings-s4 chat-fail F3: an account row shows the accounts read\'s reason
|
||||
}
|
||||
});
|
||||
|
||||
test('settings-s4: Models offered lists each provider\'s models read-only with a count, a search past eight, and Coming later', { timeout: 90000 }, async t => {
|
||||
// #1873 models-offered: the instance owner's page switches models on or off (settings-models-offered-
|
||||
// browser.test.mjs). A page that is not the owner's still reads the list read-only, as here.
|
||||
test('settings-s4: a page that is not the instance owner\'s lists each provider\'s models read-only with a count, a search past eight, and Coming later', { timeout: 90000 }, async t => {
|
||||
const list = [{ accountId: 'a1', provider: 'claude', displayName: 'Claude work', status: 'active', priority: 0 }, { accountId: 'a2', provider: 'codex', displayName: 'Codex home', status: 'active', priority: 0 }];
|
||||
const models = Array.from({ length: 10 }, (_, i) => ({ module: 'cliproxy', upstream: 'claude', model: `claude-model-${i}`, available: true }))
|
||||
.concat([{ module: 'cliproxy', upstream: 'codex', model: 'gpt-x', available: true }, { module: 'cliproxy', upstream: 'codex', model: 'gpt-gone', available: false }, { module: 'fixture', upstream: 'fixture', model: 'fixture-deterministic', available: true }]);
|
||||
const status = { ...running, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', models: 11 } }] };
|
||||
const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': config, '/api/proxy/admin/status': status, ...accounts(list), '/api/triage/route': { route: null },
|
||||
'/api/orgs/acme/bus/routes': { rows: [{ catalogue: { status: 'ready', models } }] } } });
|
||||
const { f, b, wait } = await w15Fixture(t, { scenario: { '/api/config': { send: true, devOwner: true }, '/api/proxy/admin/status': status, ...accounts(list),
|
||||
'GET /api/proxy/accounts': { body: { accounts: list, providers: publicProviders() } }, '/api/triage/route': { route: null },
|
||||
'/api/bus/routes': { rows: [{ catalogue: { status: 'ready', models } }] } } });
|
||||
await b.navigate(f.base + '/#/settings/model-setup?step=accounts');
|
||||
await wait('document.querySelectorAll("#proxy-accounts li[data-account]").length === 2');
|
||||
await b.evaluate('document.querySelector("#proxy-offered").open = true; true');
|
||||
@@ -414,6 +418,7 @@ test('settings-s4: Models offered lists each provider\'s models read-only with a
|
||||
await b.evaluate('(() => { document.querySelector("#proxy-offered-list details[data-offered=claude]").open = true; const i = document.querySelector("#proxy-offered-list details[data-offered=claude] input[type=search]"); i.value = "model-7"; i.dispatchEvent(new Event("input")); return true; })()');
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#proxy-offered-list details[data-offered=claude] li")].filter(li => !li.hidden).map(li => li.dataset.model)'), ['claude-model-7']);
|
||||
assert.deepEqual(await b.evaluate('window.__writes'), [], 'reading the models writes nothing');
|
||||
assert.deepEqual(await b.evaluate('window.__unexpected'), [], 'no admin read: the page is not the owner\'s');
|
||||
});
|
||||
|
||||
test('settings-s4 review N9: before setup, every control under Advanced takes focus with a visible ring', { timeout: 90000 }, async t => {
|
||||
@@ -465,6 +470,9 @@ test('shots', { timeout: 900000, skip: !process.env.MOSAIC_UX_SHOTS }, async t =
|
||||
const models = Array.from({ length: 10 }, (_, i) => ({ module: 'cliproxy', upstream: 'claude', model: `claude-sonnet-4-${i}`, available: true }))
|
||||
.concat(['gpt-5.1', 'gpt-5.1-codex'].map(model => ({ module: 'cliproxy', upstream: 'codex', model, available: true })));
|
||||
const routes = { rows: [{ ...VIEW, catalogue: { status: 'ready', observedAt: new Date().toISOString(), models, notices: [] } }] };
|
||||
// The owner's lists (GET /api/proxy/admin/models), from the same models.
|
||||
const listed = upstream => models.filter(x => x.upstream === upstream).map((x, i) => ({ id: x.model, label: x.model, on: i < 3, isNew: false, usedBy: i === 0 ? [{ org: 'acme', instance: 'assistant', fallback: false }] : [] }));
|
||||
const offered = { revision: 'r1', providers: [{ provider: 'claude', label: 'Claude', on: 3, total: 10, models: listed('claude') }, { provider: 'codex', label: 'ChatGPT / Codex', on: 2, total: 2, models: listed('codex') }] };
|
||||
const go = 'document.querySelector("#proxy-setup-go").click(); true';
|
||||
const PAGES = [
|
||||
{ name: 'nav-open', path: '/#/settings/routing?org=acme', ready: 'document.querySelector("#org-pick")', after: async (b, wait, width) => {
|
||||
@@ -481,7 +489,7 @@ test('shots', { timeout: 900000, skip: !process.env.MOSAIC_UX_SHOTS }, async t =
|
||||
await b.evaluate('window.open = () => null; document.querySelector("#proxy-add-box").open = true; document.querySelector("#proxy-login-start").requestSubmit(); true'); await wait('!document.querySelector("#proxy-signin").hidden'); } },
|
||||
{ name: 'models-accounts-key', path: '/#/settings/model-setup?step=accounts', service: up, extra: { accounts, routes }, ready: 'document.querySelectorAll("#proxy-accounts li[data-account]").length === 2', after: async b => {
|
||||
await b.evaluate('(() => { document.querySelector("#proxy-add-box").open = true; const s = document.querySelector("#proxy-provider"); s.value = "z.ai"; s.dispatchEvent(new Event("change")); return true; })()'); } },
|
||||
{ name: 'models-offered', path: '/#/settings/model-setup?step=accounts', service: up, extra: { accounts, routes }, ready: 'document.querySelectorAll("#proxy-accounts li[data-account]").length === 2', after: async (b, wait) => {
|
||||
{ name: 'models-offered', path: '/#/settings/model-setup?step=accounts', service: up, extra: { accounts, routes, offered }, ready: 'document.querySelectorAll("#proxy-accounts li[data-account]").length === 2', after: async (b, wait) => {
|
||||
await b.evaluate('document.querySelector("#proxy-offered").open = true; true'); await wait('document.querySelector("#proxy-offered-list details[data-offered=claude]")');
|
||||
await b.evaluate('document.querySelector("#proxy-offered-list details[data-offered=claude]").open = true; true'); } },
|
||||
{ name: 'models-problems', path: '/#/settings/model-setup', service: { ...up, organizations: [{ id: 'acme', proxy: 'shared', catalogue: { status: 'ready', launchRestart: true } }, { id: 'north', proxy: 'shared', catalogue: { status: 'ready', models: 12 } }],
|
||||
|
||||
@@ -379,6 +379,15 @@ test('settings-s5b: a history entry whose action is not a known one reads Other
|
||||
for (const item of await items(b)) assert.match(item.text, /^Other setup action · .+ · by jason$/);
|
||||
});
|
||||
|
||||
test('settings-s5b: the models-offered entries read as what they did, never Other setup action', { timeout: 90000 }, async t => {
|
||||
const { b, wait } = await setup(t, { admin: { ...OK, 'history?limit=25': { entries: [{ op: 'models.seed', time: T(1), user: 'jason' }, { op: 'models.set', provider: 'not-a-provider', time: T(2), user: 'jason' }], next: null } } });
|
||||
await wait(READY); await openTech(b);
|
||||
await wait('document.querySelectorAll("#proxy-setup-history li").length === 2');
|
||||
const texts = (await items(b)).map(i => i.text).sort();
|
||||
assert.match(texts[0], /^Model lists recorded, every model on · .+ · by jason$/);
|
||||
assert.match(texts[1], /^Models switched on or off · .+ · by jason$/);
|
||||
});
|
||||
|
||||
test('settings-s5b: a withheld entry shows as withheld and nothing else from it', { timeout: 90000 }, async t => {
|
||||
const { b, wait } = await setup(t, { admin: { ...OK, 'history?limit=25': { entries: [{ withheld: true, op: 'init', time: T(2), user: 'jason', org: 'acme' }, { withheld: true }], next: null } } });
|
||||
await wait(READY); await openTech(b);
|
||||
|
||||
Reference in new issue
Block a user