Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c6082fde1 | ||
|
|
c68440e9da | ||
|
|
2a0d5ecaa1 | ||
|
|
911429fd01 | ||
|
|
4a5434a818 | ||
|
|
5f431da480 | ||
|
|
1e4b5e07f9 | ||
|
|
ffa27c1bb0 | ||
|
|
1b5aa295ba | ||
|
|
125c71051e | ||
|
|
fcbf2dc9e3 | ||
|
|
3169c17098 | ||
|
|
00297e2754 | ||
|
|
323040f9cf | ||
|
|
d3f6d37c53 | ||
|
|
6a851bff3d | ||
|
|
5be7159751 | ||
|
|
3e648558f0 | ||
|
|
0ee9dcac7c | ||
|
|
f9fee0e4c8 | ||
|
|
b64e854ee9 | ||
|
|
af4b1d367e | ||
|
|
58d9c81479 | ||
|
|
5c18e8f1f6 | ||
|
|
67d9288c26 | ||
|
|
525a081471 | ||
|
|
ccbcb80a40 | ||
|
|
f65ca7bb73 | ||
|
|
96e157382b | ||
|
|
650a2d2890 | ||
|
|
66ef78d69e | ||
|
|
a0ec8e028c | ||
|
|
8c5764fd03 |
No files matched your search
+31
-1
@@ -1483,7 +1483,37 @@ render|status|install|start|stop|restart` manages the proxy user unit.
|
||||
confirmed new process listening on the port, then clears the fence with that
|
||||
evidence (`proxy-restart-unconfirmed` otherwise). `proxy init-lock
|
||||
status|clear` clears a stale init lock only when every bus is stopped and no
|
||||
proxy state exists. Details: `packages/model-proxy/README.md`.
|
||||
proxy state exists. `proxy undo` removes only an unfinished setup, matching Remove unfinished setup in Model setup. Connected accounts, riding organizations, a running service or a recorded successful start prevent removal. The pinned download and history stay. Details: `packages/model-proxy/README.md`.
|
||||
|
||||
`proxy ride --instance NAME` makes this instance's worker runs use instance
|
||||
NAME's model proxy (proxy-ride first slice, Jason 2026-11-21). Both instances
|
||||
belong to the OS user running the command. It writes
|
||||
`<configDir>/proxy-ride.json` as `{"version":1,"instance":"NAME"}`, mode 0600,
|
||||
then loads the system config the way a worker run does and removes the file
|
||||
again on any refusal. `proxy ride --off` removes the file without loading the
|
||||
config. Both refuse `human-required` in an agent shell or with `--tester`. The
|
||||
riding instance's `mosaic-config.mjs validate` prints the owner's `proxy` with
|
||||
`owner: {instance, configDir, dataRoot}`; worker runs (`verify.sh`, `hello.sh`,
|
||||
`agent.sh`, `run-task.sh`) then use the owner's management key, lock, fence,
|
||||
state directory and model on/off list. The worker key keeps the riding
|
||||
instance's own tag and file. Buses, the Console and every other verb load the
|
||||
config without that proxy, as on an instance with no proxy, and
|
||||
`MOSAIC_INSTANCE_PROXY_CONFIGURED` stays off, so no proxy unit is installed for
|
||||
the rider. Every validate resolves the owner, so while `proxy-ride.json`
|
||||
exists an owner problem refuses every verb on the rider, buses and the Console
|
||||
included; `proxy ride --off` is the way out. Run the owner with its own config
|
||||
path (`--instance NAME`, or `MOSAIC_CONFIG` set to exactly
|
||||
`~/.config/mosaic-NAME/config.json`): the rider locks the owner's proxy state
|
||||
with that path, and the first side to lock it fixes the lock identity, so the
|
||||
other side refuses `proxy-lock-invalid`. Refusals (validate exit 2):
|
||||
`proxy-ride-invalid` (a bad file, a bad name, the instance's own name, or an owner with the same data root),
|
||||
`proxy-ride-owner-missing` (the named
|
||||
instance has no valid config, claim or `proxy.json`, or rides another instance
|
||||
itself), `proxy-ride-conflict` (`proxy.json` and `proxy-ride.json` both exist;
|
||||
`proxy init` also refuses it on a riding instance). Each prints one line with
|
||||
the owner's next step, except under `run-task.sh`, where a ride refusal still
|
||||
shows as a JSON parse error, as every config refusal there does. `--off` leaves the rider's worker key in the owner's
|
||||
proxy; it is not removed yet.
|
||||
|
||||
## Agent limits (`scripts/mosaic limits`)
|
||||
|
||||
|
||||
@@ -561,9 +561,18 @@ const NOTICE_RUN = 'bus';
|
||||
//
|
||||
// The line has the form a failed turn's reply has (packages/harness/src/failure-notice.mjs), so the
|
||||
// chat renders it the same way: "The turn failed: <cause and next step>\nDetails: <code>". The
|
||||
// text is fixed per code. A refusal's own reason is never put in it: it can name paths, models
|
||||
// and accounts. Codes are the launcher's existing refusal codes and the existing proxy-stall stop
|
||||
// reason; none is added here.
|
||||
// first line is fixed per code. Codes are the launcher's existing refusal codes and the existing
|
||||
// proxy-stall stop reason; none is added here.
|
||||
// first-run-fixes-1 (B4): a refused start whose code has no line of its own (launch-failed, and any
|
||||
// code that gets OTHER) also carries the launcher's plain reason in its Details, so the generic
|
||||
// line alone no longer hides the cause. A code with its own line says its cause already, and its
|
||||
// reason is left out. The launcher has already put it
|
||||
// through relay(); here it is made one line, every absolute or home path and file: URL that
|
||||
// follows a space, a quote, a bracket, a backtick, `=`, `:`, `,`, `;`, `{`, `}`, `|` or `>`
|
||||
// (so a character that ends one path can start the next) is replaced again,
|
||||
// and it is cut to WHY_MAX characters, never inside a character. A path with a space in it is
|
||||
// replaced only up to the space. The reason can name a model, an account or a variable name; it
|
||||
// holds no value only as far as the launcher's own refusal text holds none.
|
||||
const MODEL = "the model this agent uses isn't available from the model service now. Pick another model, or check Settings > Model setup.";
|
||||
const PROXY = "the model proxy isn't ready. Check Settings > Model setup.";
|
||||
const ACCOUNT = "the agent's model account isn't signed in or set up. Sign in again, or check the account in Settings > Model setup.";
|
||||
@@ -603,12 +612,23 @@ const WAITS = new Set(['capacity-full', 'instance-running', 'legacy-run-live', '
|
||||
'processing-generation-changed', 'proxy-lock-busy', 'project-pending', 'processing-halted']);
|
||||
|
||||
const NOTICE_CODE = /^[a-z][a-z-]{0,63}$/;
|
||||
const WHY_MAX = 300;
|
||||
const NOTICE_PATH = /(^|[\s'"(=:,[<`{|)\]>;}])(?:~?\/(?!\/)|file:)[^\s'"),\]>;`}|]*/gi;
|
||||
// A reason as one plain line, or '' when nothing is left of it or it only repeats the code.
|
||||
function noticeWhy(why, code) {
|
||||
if (why === undefined) return '';
|
||||
const line = why.replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g, ' ').replace(NOTICE_PATH, (_, before) => `${before}a host path`).replace(/\s+/g, ' ').trim();
|
||||
if (!line || line === code) return '';
|
||||
const chars = Array.from(line);
|
||||
return chars.length > WHY_MAX ? `${chars.slice(0, WHY_MAX - 3).join('')}...` : line;
|
||||
}
|
||||
|
||||
// The body for a code, or null when the code leaves no line.
|
||||
function failureNoticeBody(code) {
|
||||
function failureNoticeBody(code, why = '') {
|
||||
if (typeof code !== 'string' || !NOTICE_CODE.test(code) || WAITS.has(code)) return null;
|
||||
const line = LINES.get(code) ?? (code.startsWith('proxy-') ? PROXY : OTHER);
|
||||
return `The turn failed: ${line}\nDetails: ${code === 'proxy-stall' ? 'stopped' : 'start refused'}: ${code}`;
|
||||
const because = why && !LINES.has(code) ? `: ${why}` : '';
|
||||
return `The turn failed: ${line}\nDetails: ${code === 'proxy-stall' ? 'stopped' : 'start refused'}: ${code}${because}`;
|
||||
}
|
||||
// Row 143 (#1637, REQ-PROJ-4): a human save of this file through project.file.save sends one notice to each
|
||||
// instance of these definitions. Their answer goes to the instance of SPEC_ANSWER_TO, the chief of staff,
|
||||
@@ -2071,16 +2091,17 @@ export class Broker {
|
||||
// to or from the thread's instance (trigger message_threads_match), so the line is from the
|
||||
// instance, with from_run NOTICE_RUN: no run sent it, the bus did, and a failed turn's own line is
|
||||
// the instance's too. With { thread, session } the messages are the session's pending ones, for a
|
||||
// refused start; with { run } they are the ones delivered to that run and never read, for a
|
||||
// refused start, and an optional `why` is the launcher's reason for it (noticeWhy above); with { run } they are the ones delivered to that run and never read, for a
|
||||
// stopped run. A message the instance has already answered gets no line, so a refusal the
|
||||
// launcher meets on every tick leaves one line per message. The text is fixed per code
|
||||
// launcher meets on every tick leaves one line per message. The first line is fixed per code
|
||||
// (failureNoticeBody above). Trusted launcher API, deliberately NOT a socket verb.
|
||||
failureNotice(record) {
|
||||
keys(record, ['business', 'code', 'thread', 'session', 'run'], ['business', 'code']);
|
||||
keys(record, ['business', 'code', 'thread', 'session', 'run', 'why'], ['business', 'code']);
|
||||
this.#business(identifier(record.business));
|
||||
if (typeof record.code !== 'string' || !NOTICE_CODE.test(record.code)) fail('invalid-request');
|
||||
const byRun = record.run !== undefined;
|
||||
if (byRun === (record.thread !== undefined || record.session !== undefined)) fail('invalid-request');
|
||||
if (record.why !== undefined && (byRun || typeof record.why !== 'string' || record.why.length > 4096)) fail('invalid-request');
|
||||
let session = null, instance, where, param;
|
||||
if (byRun) {
|
||||
const run = this.#runs.get(record.business + ':' + identifier(record.run)) ?? fail('unknown-run');
|
||||
@@ -2096,7 +2117,7 @@ export class Broker {
|
||||
where = `NOT EXISTS(SELECT 1 FROM deliveries d WHERE d.message=m.id AND d.op IN ('delivered','read'))`;
|
||||
param = null;
|
||||
}
|
||||
const body = failureNoticeBody(record.code);
|
||||
const body = failureNoticeBody(record.code, noticeWhy(record.why, record.code));
|
||||
if (body === null) return { posted: 0 };
|
||||
const scope = session ? 'm.id IN (SELECT message FROM message_threads WHERE session=?)' : 'NOT EXISTS(SELECT 1 FROM message_threads mt WHERE mt.message=m.id)';
|
||||
return this.#store.transaction(() => {
|
||||
|
||||
@@ -7,7 +7,7 @@ const fail = code => { throw Object.assign(new Error(code), { code }); };
|
||||
const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
const syncDir = dir => { const fd = fs.openSync(dir, 'r'); try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); } };
|
||||
|
||||
export function createProxyLock({ stateDir, identity, waitMs = 5000 }) {
|
||||
export function createProxyLock({ stateDir, identity, waitMs = 5000, readOnly = false }) {
|
||||
if (typeof stateDir !== 'string' || !path.isAbsolute(stateDir) || typeof identity !== 'string' || !identity || !Number.isSafeInteger(waitMs) || waitMs < 0) fail('proxy-lock-invalid');
|
||||
try {
|
||||
const stat = fs.lstatSync(stateDir);
|
||||
@@ -23,19 +23,24 @@ export function createProxyLock({ stateDir, identity, waitMs = 5000 }) {
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid() || (stat.mode & 0o077) || stat.size > 4096) fail('proxy-lock-invalid');
|
||||
return fs.readFileSync(file, 'utf8');
|
||||
}
|
||||
const identityTemp = path.join(stateDir, `.identity-${randomBytes(16).toString('hex')}`);
|
||||
try {
|
||||
const fd = fs.openSync(identityTemp, 'wx', 0o600);
|
||||
try { fs.writeFileSync(fd, digest + '\n'); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
||||
try { fs.linkSync(identityTemp, identityFile); syncDir(stateDir); }
|
||||
catch (error) { if (error.code !== 'EEXIST') throw error; }
|
||||
} catch { fail('proxy-lock-invalid'); }
|
||||
finally { try { fs.unlinkSync(identityTemp); } catch (error) { if (error.code !== 'ENOENT') fail('proxy-lock-invalid'); } }
|
||||
try { if (readSafe(identityFile) !== digest + '\n') fail('proxy-lock-invalid'); } catch { fail('proxy-lock-invalid'); }
|
||||
if (!readOnly) {
|
||||
const identityTemp = path.join(stateDir, `.identity-${randomBytes(16).toString('hex')}`);
|
||||
try {
|
||||
const fd = fs.openSync(identityTemp, 'wx', 0o600);
|
||||
try { fs.writeFileSync(fd, digest + '\n'); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
||||
try { fs.linkSync(identityTemp, identityFile); syncDir(stateDir); }
|
||||
catch (error) { if (error.code !== 'EEXIST') throw error; }
|
||||
} catch { fail('proxy-lock-invalid'); }
|
||||
finally { try { fs.unlinkSync(identityTemp); } catch (error) { if (error.code !== 'ENOENT') fail('proxy-lock-invalid'); } }
|
||||
}
|
||||
try { if (readSafe(identityFile) !== digest + '\n') fail('proxy-lock-invalid'); }
|
||||
catch (error) { if (!readOnly || error.code !== 'ENOENT') fail('proxy-lock-invalid'); }
|
||||
function assertCertain() {
|
||||
try { fs.lstatSync(fenceFile); } catch (error) { if (error.code === 'ENOENT') return; fail('proxy-uncertain'); }
|
||||
fail('proxy-uncertain');
|
||||
}
|
||||
// Read admission keeps the directory, identity and fence checks but has no write surface.
|
||||
if (readOnly) return { assertCertain };
|
||||
function reap() {
|
||||
// An orphaned reaper is deliberately not guessed away. It needs operator inspection.
|
||||
try { fs.mkdirSync(guard, { mode: 0o700 }); } catch (error) { if (error.code === 'EEXIST') return false; fail('proxy-lock-uncertain'); }
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
// Instance-owner transport. The HTTP owner gate authorizes it; the existing human verifier
|
||||
// checks the host ancestry, just as the bus's human wrapper does. No organization is needed.
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { join, dirname, resolve, isAbsolute } from 'node:path';
|
||||
import { readProcess, verifyHuman } from './human.mjs';
|
||||
import { ProxyPage, PROXY_PAGE_VERBS } from './proxy-page.mjs';
|
||||
import { createProxyLock } from './proxy-lock.mjs';
|
||||
import { initializeProxy, loadProxy } from '../../model-proxy/src/settings.mjs';
|
||||
import { loadManagementClient } from '../../model-proxy/src/client.mjs';
|
||||
import { refuse, sha256, validManagementKey, proxyTiming } from '../../model-proxy/src/common.mjs';
|
||||
import { catalogue } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
import { verifyRestart } from '../../model-proxy/src/admin.mjs';
|
||||
import { readOffered } from '../../model-proxy/src/models-offered.mjs';
|
||||
const self = fileURLToPath(import.meta.url);
|
||||
const consolePath = fileURLToPath(new URL('../../webui/src/cli.mjs', import.meta.url));
|
||||
function parentConfigDir(pid) {
|
||||
// Read only the two instance-selection fields. Never retain or return the parent's environment.
|
||||
let home, selected;
|
||||
for (const entry of readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0')) {
|
||||
if (entry.startsWith('HOME=')) home = entry.slice(5);
|
||||
if (entry.startsWith('MOSAIC_CONFIG=')) selected = entry.slice(14);
|
||||
}
|
||||
const file = selected || (home && join(home, '.config/mosaic-dev/config.json'));
|
||||
if (!file || !isAbsolute(file)) refuse('human-required');
|
||||
return dirname(file);
|
||||
}
|
||||
// The same cooperative same-UID check as the Console bus wrapper: exact direct parent,
|
||||
// instance selection, human ancestry and a second identity check after the walk. A supplied
|
||||
// subject is only an OAuth session namespace; the verified Console authorizes its HTTP owner.
|
||||
export function verifyOwnerConsole({ configDir, pid = process.pid, nonce = process.env.MOSAIC_BUS_CLI_NONCE,
|
||||
launches = [], readProcess: read = readProcess, parentConfigDir: selected = parentConfigDir }) {
|
||||
try {
|
||||
const child = read(pid), parent = read(child.ppid);
|
||||
if (parent.uid !== process.getuid() || parent.argv[1] !== consolePath || parent.argv[2] !== 'serve'
|
||||
|| resolve(selected(parent.pid)) !== resolve(configDir)) refuse('human-required');
|
||||
verifyHuman({ pid, startTime: child.startTime, nonce, business: 'instance-owner' }, { cliPath: self, launches, readProcess: read });
|
||||
const again = read(pid), up = read(parent.pid);
|
||||
if (again.ppid !== parent.pid || again.startTime !== child.startTime || up.startTime !== parent.startTime
|
||||
|| up.ppid !== parent.ppid || up.uid !== parent.uid || up.argv[1] !== parent.argv[1] || up.argv[2] !== 'serve'
|
||||
|| resolve(selected(up.pid)) !== resolve(configDir)) refuse('human-required');
|
||||
} catch { refuse('human-required'); }
|
||||
}
|
||||
export function createOwnerProxyRuntime({ configDir, dataRoot, checkHuman = () => verifyOwnerConsole({ configDir }), init = initializeProxy, load = loadManagementClient }) {
|
||||
let current = null, active = 0, paused = false;
|
||||
const pending = new Map();
|
||||
async function context({ readOnly = false } = {}) {
|
||||
checkHuman();
|
||||
const proxy = loadProxy(configDir, dataRoot);
|
||||
if (!proxy) refuse('not-configured');
|
||||
const identity = JSON.stringify(proxy);
|
||||
if (!current || current.identity !== identity) {
|
||||
const client = await load({ configDir, proxy });
|
||||
current = { identity, client, lock: null, page: null };
|
||||
}
|
||||
// Account and catalogue GETs never create the lock's identity file. Only mutations
|
||||
// acquire the write context; a later mutation still creates and validates the same lock.
|
||||
if (!readOnly && !current.page) {
|
||||
const lock = createProxyLock({ stateDir: join(dataRoot, 'proxy'), identity: `${configDir}:${proxy.port}` });
|
||||
current.lock = lock;
|
||||
current.page = new ProxyPage({ client: current.client, lock, instanceTag: sha256(configDir).slice(0, 12) });
|
||||
}
|
||||
if (readOnly && !current.page) {
|
||||
const lock = createProxyLock({ stateDir: join(dataRoot, 'proxy'), identity: `${configDir}:${proxy.port}`, readOnly: true });
|
||||
return { ...current, lock, page: new ProxyPage({ client: current.client, lock, instanceTag: sha256(configDir).slice(0, 12) }) };
|
||||
}
|
||||
return current;
|
||||
}
|
||||
return {
|
||||
reset() { if (paused) refuse('proxy-admin-busy'); current = null; pending.clear(); },
|
||||
async withRemoval(action) {
|
||||
for (const [state, expires] of pending) if (expires <= Date.now()) pending.delete(state);
|
||||
if (paused || active || pending.size) refuse('proxy-admin-busy');
|
||||
paused = true;
|
||||
try { const result = await action(); current = null; pending.clear(); return result; } finally { paused = false; }
|
||||
},
|
||||
async call(verb, args = {}, principal = null) {
|
||||
if (paused) refuse('proxy-admin-busy');
|
||||
active++;
|
||||
try {
|
||||
checkHuman();
|
||||
if (verb === 'proxy.init') {
|
||||
const { generate, ...given } = args;
|
||||
if (Object.keys(args).some(k => !['generate', 'key', 'port', 'firstOutputSeconds', 'rotateGraceMinutes'].includes(k))
|
||||
|| (generate !== undefined ? generate !== true || 'key' in args : !validManagementKey(args.key))) refuse('invalid-request');
|
||||
proxyTiming(given);
|
||||
const result = await init({ configDir, dataRoot, ...given, ...(generate ? { key: randomBytes(48).toString('base64url') } : {}) });
|
||||
current = null;
|
||||
return result;
|
||||
}
|
||||
const c = await context({ readOnly: verb === 'proxy.accounts' });
|
||||
if (verb === 'proxy.fence.clear') {
|
||||
if (Object.keys(args).length !== 1 || !args.evidence) refuse('invalid-request');
|
||||
const proxy = loadProxy(configDir, dataRoot);
|
||||
return await c.lock.clear({ restarted: true, read: () => c.client.getKeys(), verify: previous => verifyRestart(args.evidence, { fence: previous, port: proxy.port }) });
|
||||
}
|
||||
if (!PROXY_PAGE_VERBS.includes(verb)) refuse('invalid-request');
|
||||
// The verified Console supplies its signed-in owner only as an OAuth session namespace.
|
||||
const result = await c.page.request(verb, args, { business: 'instance-owner', human: JSON.stringify(principal) });
|
||||
if (verb === 'proxy.login.start') pending.set(result.state, Date.now() + 300000);
|
||||
if (verb === 'proxy.login.cancel' || (verb === 'proxy.login.status' && result.status !== 'wait')) pending.delete(args.state);
|
||||
return result;
|
||||
} finally { active--; }
|
||||
},
|
||||
async catalogue() {
|
||||
if (paused) refuse('proxy-admin-busy');
|
||||
active++;
|
||||
try {
|
||||
const { client } = await context({ readOnly: true });
|
||||
return await catalogue({ listAccounts: () => client.getCredentials(), listModels: name => client.getCredentialModels(name),
|
||||
listGroups: () => client.getUpstreamGroups(), now: () => new Date().toISOString(), offered: readOffered(dataRoot).offered });
|
||||
} finally { active--; }
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Private IPC from the Console. Disconnect closes admission, then drains existing work.
|
||||
// In particular, never exit while an init or locked write is still running.
|
||||
export function attachOwnerIPC(channel, owner, authorize) {
|
||||
let release = null, removal = null, closing = false, active = 0, drain = null;
|
||||
const send = message => { if (!closing && channel.connected) channel.send(message, () => {}); };
|
||||
channel.on('disconnect', () => {
|
||||
closing = true;
|
||||
release?.(); release = null;
|
||||
if (active) drain = setInterval(() => {}, 1000);
|
||||
});
|
||||
channel.on('message', async message => {
|
||||
if (closing) return;
|
||||
active++;
|
||||
const { id, type, verb, args, principal } = message ?? {};
|
||||
try {
|
||||
// Resume only gives up a hold. A failed ancestry read must never strand that hold.
|
||||
if (type === 'resume') {
|
||||
release?.(); release = null;
|
||||
await removal;
|
||||
send({ id, result: true });
|
||||
return;
|
||||
}
|
||||
authorize();
|
||||
let result;
|
||||
if (type === 'call') result = await owner.call(verb, args, principal);
|
||||
else if (type === 'catalogue') result = await owner.catalogue();
|
||||
else if (type === 'reset') { owner.reset(); result = true; }
|
||||
else if (type === 'pause') {
|
||||
removal = owner.withRemoval(() => new Promise(resolve => { release = resolve; send({ id, result: true }); }));
|
||||
await removal;
|
||||
return;
|
||||
} else refuse('invalid-request');
|
||||
send({ id, result });
|
||||
} catch (error) { send({ id, error: typeof error?.code === 'string' ? error.code : 'outcome-unknown' }); }
|
||||
finally { active--; if (closing && !active && drain) { clearInterval(drain); drain = null; } }
|
||||
});
|
||||
}
|
||||
if (process.argv[1] === self && process.argv[2] === '--owner-ipc' && process.send) {
|
||||
const configDir = process.argv[3], dataRoot = process.argv[4];
|
||||
const authorize = () => verifyOwnerConsole({ configDir });
|
||||
const owner = createOwnerProxyRuntime({ configDir, dataRoot, checkHuman: authorize });
|
||||
attachOwnerIPC(process, owner, authorize);
|
||||
}
|
||||
@@ -76,19 +76,26 @@ group(
|
||||
"Ask the owner to inspect the provider configuration through its supported controls; never put keys or callback contents in messages."
|
||||
);
|
||||
// #1873: proxy setup from the Console page and `mosaic proxy`. Each code has one owner next step.
|
||||
group("proxy-install-missing proxy-fetch-url proxy-fetch-failed proxy-fetch-redirect", "R1: pinned model proxy release", "Fetch the pinned release from the Proxy page or with mosaic proxy fetch. A download or redirect failure is retried as it stands; the release URL is fixed by the pin.");
|
||||
group("proxy-install-missing proxy-fetch-url proxy-fetch-failed proxy-fetch-redirect", "R1: pinned model proxy release", "Fetch the pinned release from the Model setup page or with mosaic proxy fetch. A download or redirect failure is retried as it stands; the release URL is fixed by the pin.");
|
||||
group("proxy-install-invalid proxy-fetch-hash proxy-fetch-archive proxy-fetch-existing", "R1: pinned release hashes must match", "A file does not match the pinned hash. Do not run it. Ask the owner to remove the pinned release directory named in the README and fetch again.");
|
||||
group("proxy-already-initialized proxy-port-in-use proxy-management-key-invalid", "R1/R4: proxy init is exclusive creation", "Init never rewrites proxy.json. Read the Proxy page status; pick a free port, or keep the existing setup and continue from the status's next step.");
|
||||
group("proxy-init-busy proxy-init-lock-held proxy-init-lock-absent", "R4: init lock clears only when provably stale", "Wait for a running init to finish. A stale lock clears from the Proxy page or with mosaic proxy init-lock clear only when the bus is stopped and no proxy.json, key file or proxy dir exists; the refusal lists what is still there.");
|
||||
group("proxy-already-initialized proxy-port-in-use proxy-management-key-invalid", "R1/R4: proxy init is exclusive creation", "Init never rewrites proxy.json. Read the Model setup page status; pick a free port, or keep the existing setup and continue from the status's next step.");
|
||||
group("proxy-init-busy proxy-init-lock-held proxy-init-lock-absent", "R4: init lock clears only when provably stale", "Wait for a running init to finish. A stale lock clears from the Model setup page or with mosaic proxy init-lock clear only when the bus is stopped and no proxy.json, key file or proxy dir exists; the refusal lists what is still there.");
|
||||
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.");
|
||||
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 Model setup 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 Model setup 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.");
|
||||
group("proxy-client-invalid proxy-client-refused proxy-client-response", "R1: proxy management answers", "Check the proxy unit is running and its port answers on the Proxy page, then retry. Upstream bodies are never shown.");
|
||||
group("proxy-setup-in-use", "R4: undo only unfinished model setup", "A running model service, connected account, riding organization or recorded successful start prevents undo. Keep this model service and resolve its current state in Model setup.");
|
||||
group("proxy-setup-remove-refused", "R4: unfinished state must be known and unused", "Mosaic could not prove the unfinished setup safe to remove. Ask the instance administrator to inspect the service file and unfinished state; no foreign file is removed.");
|
||||
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 belongs to this instance", "Initialize the proxy first, then install the unit from the Model setup page or with mosaic proxy unit install. Existing unit files are never replaced. An identical file is a no-op on retry. A foreign unit or drop-in must be checked by its installer. An unhealthy unit: read its journal by unit name and restart it.");
|
||||
// proxy-ride first slice (Jason 2026-11-21): an instance's worker runs use another instance's proxy.
|
||||
// Each next step is the same line packages/model-proxy/src/settings.mjs RIDE_LINES prints.
|
||||
group("proxy-ride-invalid", "R1/R4: a ride file names one other instance of the same OS user", "proxy-ride.json is not a valid ride file, or it names this instance. Run mosaic proxy ride --off, then mosaic proxy ride --instance NAME with the instance whose proxy this one should use.");
|
||||
group("proxy-ride-owner-missing", "R1/R4: the ridden instance owns a valid model proxy", "The instance named in proxy-ride.json has no valid model proxy, or it rides another instance itself. Set up the proxy on that instance, or run mosaic proxy ride --off.");
|
||||
group("proxy-ride-conflict", "R1/R4: an instance has its own proxy or rides one, never both", "This instance has its own proxy.json and a proxy-ride.json. Run mosaic proxy ride --off to keep its own proxy.");
|
||||
group("proxy-client-invalid proxy-client-refused proxy-client-response", "R1: proxy management answers", "Check the proxy unit is running and its port answers on the Model setup page, then retry. Upstream bodies are never shown.");
|
||||
// proxy-scope slice 4 (Jason 2026-11-19): the Triage key lives with a bus that rides the owner's
|
||||
// proxy, and a Triage session on a key past its retireAt ends before the key leaves the proxy.
|
||||
group("triage-no-riding-bus", "R1/R4: the Triage key is issued and rotated by a bus that rides the owner's proxy", "Triage needs one organization that uses the owner's models. Start an organization that rides the owner's model proxy, then repair Triage access from Settings, Triage.");
|
||||
|
||||
@@ -874,7 +874,7 @@ export async function startBroker({
|
||||
let found;
|
||||
try { found = loadProxy(configDir, instanceRoot ?? dataRoot); }
|
||||
catch (error) { return dropLateProxy(`The model proxy settings do not load (${/^proxy-[a-z-]+$/.test(error?.code ?? '') ? error.code : 'proxy-config-invalid'}). This organization reads no accounts or catalogue until they do.`); }
|
||||
if (found === undefined) return dropLateProxy('The model proxy has not been set up for this instance yet. Set it up on the Model proxy page.');
|
||||
if (found === undefined) return dropLateProxy('The model proxy has not been set up for this instance yet. Set it up on the Model setup page.');
|
||||
if (modelProxyClient && found.port !== proxyPort) dropLateProxy(null);
|
||||
if (fixtureRecorded() && Object.keys(businesses).some(usesFixture))
|
||||
return dropLateProxy('This organization routes launches to the dev fixture, which the host refuses next to a model proxy (fixture-proxy-configured). Remove the fixture or stop using it here.');
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// Existing owner thread/session/message reads only. Runner notices are not answers.
|
||||
import { LENGTH_FAILURE_NOTICE_PREFIX, TURN_FAILURE_NOTICE_PREFIX } from '../../harness/src/failure-notice.mjs';
|
||||
|
||||
function realBody(body) {
|
||||
if (typeof body !== 'string') return false;
|
||||
const text = body.split('\n\n[unslop:')[0].trim();
|
||||
return !!text && text !== '(the session gave no answer)' &&
|
||||
!text.startsWith(TURN_FAILURE_NOTICE_PREFIX) && !text.startsWith(LENGTH_FAILURE_NOTICE_PREFIX);
|
||||
}
|
||||
const newest = rows => [...rows].sort((a, b) => String(b.at ?? '').localeCompare(String(a.at ?? '')) || String(b.id).localeCompare(String(a.id)));
|
||||
|
||||
export const setupState = Object.freeze([
|
||||
{
|
||||
id: 'assistant.replied', title: 'Say hello to your assistant',
|
||||
purpose: 'Send one message and get an answer. That proves every step above works together.',
|
||||
fix: { page: '#/assistant', label: 'Start a conversation' },
|
||||
order: { after: ['agents.routed'] }, required: true,
|
||||
async check(ctx) {
|
||||
let fix = null, incomplete = false, pages = 0;
|
||||
for (const org of ctx.members) {
|
||||
if (ctx.signal?.aborted) { incomplete = true; break; }
|
||||
const assistant = Object.entries(org.doc?.roles ?? {}).find(([, role]) => role.definition === 'assistant')?.[0] ?? 'assistant';
|
||||
fix ??= { page: `#/orgs/${encodeURIComponent(org.id)}`, label: 'Start a conversation' };
|
||||
try {
|
||||
const threads = await ctx.read(org, 'threads');
|
||||
if (!Array.isArray(threads)) throw Error('threads unavailable');
|
||||
const own = newest(threads.filter(t => t.instance === assistant));
|
||||
incomplete ||= own.length > 50;
|
||||
for (const thread of own.slice(0, 50)) {
|
||||
try {
|
||||
const sessions = await ctx.read(org, 'sessions', { thread: thread.id });
|
||||
if (!Array.isArray(sessions)) throw Error('sessions unavailable');
|
||||
incomplete ||= sessions.length > 50;
|
||||
for (const session of newest(sessions).slice(0, 50)) {
|
||||
let after;
|
||||
const human = new Set();
|
||||
for (let page = 0; page < 20; page++) {
|
||||
// A request-wide page budget also bounds many empty threads and sessions.
|
||||
if (pages++ >= 100 || ctx.signal?.aborted) { incomplete = true; break; }
|
||||
const messages = await ctx.read(org, 'messages', { thread: thread.id, session: session.id, ...(after ? { after } : {}), limit: 200 });
|
||||
if (!Array.isArray(messages)) throw Error('messages unavailable');
|
||||
for (const m of messages) {
|
||||
if (m.from_role === 'human' && typeof m.id === 'string') human.add(m.id);
|
||||
if (m.from_role === assistant && m.to_role === 'human' && typeof m.from_run === 'string' && m.from_run && m.from_run !== 'bus' && human.has(m.in_reply_to) && realBody(m.body))
|
||||
return { state: 'done', reason: 'Your assistant has replied to a message in your conversation.' + (incomplete ? " Some conversation history couldn't be checked." : '') };
|
||||
}
|
||||
if (messages.length < 200) break;
|
||||
if (page === 19 || !messages.at(-1)?.id || messages.at(-1).id === after) { incomplete = true; break; }
|
||||
after = messages.at(-1).id;
|
||||
}
|
||||
if (pages >= 100 || ctx.signal?.aborted) break;
|
||||
}
|
||||
} catch { incomplete = true; }
|
||||
if (pages >= 100 || ctx.signal?.aborted) break;
|
||||
}
|
||||
} catch { incomplete = true; }
|
||||
}
|
||||
return { state: 'next', reason: incomplete ? "Some conversation history couldn't be checked. Open your organization to check the conversation or send a message." : 'Open your organization and start a conversation with your assistant.', ...(fix ? { fix } : {}) };
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -186,11 +186,19 @@ const probeFailure = (code) => new TriageKeyError(code, code === "proxy-down" ?
|
||||
// opts.purpose: "triage" (default) or "worker". opts.runtimes (worker only): () => the
|
||||
// processing-control runtime list, listRuntimes(dataRoot); without it no worker key whose grace has
|
||||
// passed is removed. opts.retireGuard: test seams for retireHeld ({ marginMs, live, startedAt }).
|
||||
// proxy-ride first slice (Jason 2026-11-21): a riding instance's system.proxy carries `owner`
|
||||
// ({ instance, configDir, dataRoot }) from scripts/mosaic-config.mjs. Without it, the instance's own.
|
||||
const proxyConfigDir = (configDir, system) => system?.proxy?.owner?.configDir ?? configDir;
|
||||
const proxyStateDir = (system) => join(system?.proxy?.owner?.dataRoot ?? system.dataRoot, "proxy");
|
||||
|
||||
function context({ configDir, system, uid, fileUid, now, hook, client, lock, purpose = "triage", runtimes, retireGuard, planSeam }) {
|
||||
const p = purposeOf(purpose);
|
||||
if (!system?.proxy || !Number.isInteger(system.proxy.port)) throw keyError(purpose, "no-proxy", "the instance has no model proxy set up (proxy.json)");
|
||||
return {
|
||||
configDir, dataRoot: system.dataRoot, proxy: system.proxy, stateDir: join(system.dataRoot, "proxy"),
|
||||
configDir, dataRoot: system.dataRoot, proxy: system.proxy, stateDir: proxyStateDir(system),
|
||||
// proxy-ride: the instance whose proxy this is. Its lock identity, sentinel and management key
|
||||
// are the owner's; the key file, key names and namespace stay this instance's (configDir).
|
||||
proxyConfigDir: proxyConfigDir(configDir, system),
|
||||
uid: uid ?? process.getuid(), fileUid, now: now ?? Date.now, hook: hook ?? (() => {}), client, lock,
|
||||
purpose, p, words: WORDS[purpose],
|
||||
// Tests only: rewrites a plan's result, to prove change()'s namespace check refuses it.
|
||||
@@ -202,18 +210,18 @@ function context({ configDir, system, uid, fileUid, now, hook, client, lock, pur
|
||||
|
||||
function lockFor(c) {
|
||||
if (c.lock) return c.lock;
|
||||
try { return createProxyLock({ stateDir: c.stateDir, identity: `${c.configDir}:${c.proxy.port}` }); }
|
||||
try { return createProxyLock({ stateDir: c.stateDir, identity: `${c.proxyConfigDir}:${c.proxy.port}` }); }
|
||||
catch (e) { throw proxyFailure(e.code ?? "proxy-lock-invalid", c.purpose); }
|
||||
}
|
||||
|
||||
async function clientFor(c) {
|
||||
if (c.client) return c.client;
|
||||
try { return await loadManagementClient({ configDir: c.configDir, proxy: c.proxy }); }
|
||||
try { return await loadManagementClient({ configDir: c.proxyConfigDir, proxy: c.proxy }); }
|
||||
catch (e) { throw proxyFailure(e.code ?? "proxy-management-key-invalid", c.purpose); }
|
||||
}
|
||||
|
||||
function checkSentinel(c, keys) {
|
||||
const prefix = sentinelPrefix(c.configDir);
|
||||
const prefix = sentinelPrefix(c.proxyConfigDir);
|
||||
if (!keys.some((k) => k.startsWith(prefix) && SECRET.test(k.slice(prefix.length)))) {
|
||||
throw keyError(c.purpose, "proxy-open", "the proxy's key list has no sentinel for this instance, so it may be another proxy");
|
||||
}
|
||||
@@ -248,7 +256,7 @@ async function change(c, opName, plan) {
|
||||
await client.putKeys(after);
|
||||
c.hook("put");
|
||||
const confirmed = await client.getKeys();
|
||||
if (!confirmed.some((k) => k.startsWith(sentinelPrefix(c.configDir))) || added.some((k) => !confirmed.includes(k)) || removed.some((k) => confirmed.includes(k))) {
|
||||
if (!confirmed.some((k) => k.startsWith(sentinelPrefix(c.proxyConfigDir))) || added.some((k) => !confirmed.includes(k)) || removed.some((k) => confirmed.includes(k))) {
|
||||
throw keyError(c.purpose, "unconfirmed", "the proxy did not confirm the change; the instance proxy fence stays set, see mosaic proxy fence status");
|
||||
}
|
||||
lock.confirm();
|
||||
@@ -586,12 +594,12 @@ export async function keyStatus(opts) {
|
||||
const record = readKey(configDir, { uid, fileUid, purpose });
|
||||
const proxy = { state: "not-set-up", fence: false, leftoverTemps: tempsIn(keyPaths(configDir, purpose).dir).length };
|
||||
if (system?.proxy && Number.isInteger(system.proxy.port)) {
|
||||
try { lstatSync(join(system.dataRoot, "proxy", "mosaic-keys.uncertain")); proxy.fence = true; }
|
||||
try { lstatSync(join(proxyStateDir(system), "mosaic-keys.uncertain")); proxy.fence = true; }
|
||||
catch (e) { if (e.code !== "ENOENT") proxy.fence = true; }
|
||||
try {
|
||||
const client = await loadManagementClient({ configDir, proxy: system.proxy });
|
||||
const client = await loadManagementClient({ configDir: proxyConfigDir(configDir, system), proxy: system.proxy });
|
||||
const keys = await client.getKeys();
|
||||
const prefix = sentinelPrefix(configDir);
|
||||
const prefix = sentinelPrefix(proxyConfigDir(configDir, system));
|
||||
proxy.state = keys.some((k) => k.startsWith(prefix) && SECRET.test(k.slice(prefix.length))) ? "read" : "no-sentinel";
|
||||
proxy.holdsKey = record ? keys.includes(record.key) : null;
|
||||
proxy.retiringHeld = record ? record.retiring.map((r) => keys.includes(r.key)) : [];
|
||||
|
||||
@@ -191,7 +191,7 @@ test('the restart notice is added after the notices the catalogue already carrie
|
||||
await initThroughA(t, f, a, { groups: [{ 'base-url': ZAI_URL, keys: [{ name: 'group-1' }] }] });
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'ready');
|
||||
assert.deepEqual(view.catalogue.notices, ['z.ai account has no models configured. Add them on Model proxy.', RESTART]);
|
||||
assert.deepEqual(view.catalogue.notices, ['z.ai account has no models configured. Add them on Model setup.', RESTART]);
|
||||
});
|
||||
|
||||
test('a bus started with the proxy shows no restart notice', async t => {
|
||||
|
||||
@@ -98,3 +98,16 @@ test('a contender waits while another process publishes its lock owner', async t
|
||||
await lock.run(async () => {});
|
||||
await new Promise((resolve, reject) => child.once('exit', code => code === 0 ? resolve() : reject(Error(`child exit ${code}`))));
|
||||
});
|
||||
|
||||
test('a read-only lock view validates existing identity without creating files or exposing writes', t => {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'lr-')); t.after(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
fs.chmodSync(root, 0o700);
|
||||
const view = createProxyLock({ stateDir: root, identity: 'fixture', readOnly: true });
|
||||
assert.deepEqual(fs.readdirSync(root), []);
|
||||
assert.deepEqual(Object.keys(view), ['assertCertain']); view.assertCertain();
|
||||
fs.writeFileSync(join(root, 'mosaic-proxy.identity'), 'wrong\n', { mode: 0o600 });
|
||||
assert.throws(() => createProxyLock({ stateDir: root, identity: 'fixture', readOnly: true }), error => error.code === 'proxy-lock-invalid');
|
||||
fs.unlinkSync(join(root, 'mosaic-proxy.identity'));
|
||||
fs.writeFileSync(join(root, 'mosaic-keys.uncertain'), '{}', { mode: 0o600 });
|
||||
assert.throws(() => view.assertCertain(), error => error.code === 'proxy-uncertain');
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
// proxy-ride first slice (Jason 2026-11-21): a riding instance's worker key in the owner
|
||||
// instance's proxy. Two scratch instances and a stand-in proxy on 127.0.0.1 port 0. The rider's
|
||||
// system.proxy carries `owner`, as scripts/mosaic-config.mjs gives it. Nothing here reads a real
|
||||
// config, proxy or secret.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { ensureReady, keyPrefix, keyStatus, readKey, rotateKey, sweepKeys } from "../src/triage-key.mjs";
|
||||
import { ModelKeys } from "../src/model-keys.mjs";
|
||||
import { loadManagementClient } from "../../model-proxy/src/client.mjs";
|
||||
|
||||
const MANAGE = "fxride-manage";
|
||||
const KEY_PATH = "/v8/management/config/access/api-keys";
|
||||
const sha = (s) => createHash("sha256").update(s).digest("hex");
|
||||
const tag = (dir) => sha(dir).slice(0, 12);
|
||||
const b64 = () => randomBytes(32).toString("base64url");
|
||||
const dir700 = (p) => { fs.mkdirSync(p, { recursive: true, mode: 0o700 }); fs.chmodSync(p, 0o700); };
|
||||
|
||||
async function fixture(t) {
|
||||
const root = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), "pr-")));
|
||||
const owner = { configDir: join(root, "oc"), dataRoot: join(root, "od") };
|
||||
const rider = { configDir: join(root, "rc"), dataRoot: join(root, "rd") };
|
||||
for (const d of [owner.configDir, join(owner.configDir, "secrets"), owner.dataRoot, join(owner.dataRoot, "proxy"), rider.configDir, join(rider.configDir, "secrets"), rider.dataRoot]) dir700(d);
|
||||
fs.writeFileSync(join(owner.configDir, "secrets", "proxy-management.key"), MANAGE, { mode: 0o600 });
|
||||
const O = tag(owner.configDir);
|
||||
const ownerKeys = { sentinel: `msk-${O}-sentinel-${b64()}`, bus: `msk-${O}-bus-${b64()}`, org: `mso-${O}-demo-key-${b64()}` };
|
||||
const lockFile = join(owner.dataRoot, "proxy", "mosaic-keys.lock");
|
||||
const state = { keys: Object.values(ownerKeys), puts: [] };
|
||||
const server = http.createServer(async (req, res) => {
|
||||
if (req.url === "/v1/models") {
|
||||
res.writeHead(state.keys.includes(req.headers.authorization?.slice(7)) ? 200 : 401); res.end("{}"); return;
|
||||
}
|
||||
if (req.url !== KEY_PATH || req.headers.authorization !== `Bearer ${MANAGE}`) { res.writeHead(401); res.end("{}"); return; }
|
||||
if (req.method === "GET") { res.end(JSON.stringify(state.keys)); return; }
|
||||
const chunks = []; for await (const c of req) chunks.push(c);
|
||||
state.keys = JSON.parse(Buffer.concat(chunks));
|
||||
state.puts.push({ locked: fs.existsSync(lockFile) });
|
||||
res.end('{"status":"ok"}');
|
||||
});
|
||||
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const port = server.address().port;
|
||||
t.after(async () => { server.closeAllConnections(); await new Promise((r) => server.close(r)); fs.rmSync(root, { recursive: true, force: true }); });
|
||||
owner.system = { dataRoot: owner.dataRoot, proxy: { port, binary: "/fixture-unused" } };
|
||||
rider.system = { dataRoot: rider.dataRoot, proxy: { port, binary: "/fixture-unused", owner: { instance: "owner", configDir: owner.configDir, dataRoot: owner.dataRoot } } };
|
||||
const opts = (who, extra = {}) => ({ configDir: who.configDir, system: who.system, purpose: "worker", ...extra });
|
||||
return { root, owner, rider, ownerKeys, state, port, lockFile, opts, receipts: join(owner.dataRoot, "proxy", "mosaic-keys.receipts.jsonl") };
|
||||
}
|
||||
|
||||
test("a rider's worker key lands under the rider's tag, under the owner's lock, and survives the owner's own key work", async (t) => {
|
||||
const f = await fixture(t);
|
||||
// The owner writes first, so its lock identity file exists before the rider's write.
|
||||
await ensureReady(f.opts(f.owner));
|
||||
const ownerWorker = readKey(f.owner.configDir, { purpose: "worker" }).key;
|
||||
const putsBefore = f.state.puts.length;
|
||||
|
||||
const done = await ensureReady(f.opts(f.rider));
|
||||
assert.equal(done.action, "issued");
|
||||
const riderKey = readKey(f.rider.configDir, { purpose: "worker" }).key;
|
||||
assert.match(riderKey, new RegExp(`^msw-${tag(f.rider.configDir)}-worker-[A-Za-z0-9_-]{43}$`));
|
||||
assert.ok(riderKey.startsWith(keyPrefix(f.rider.configDir, "worker")));
|
||||
assert.ok(f.state.keys.includes(riderKey));
|
||||
assert.ok(f.state.puts.length > putsBefore && f.state.puts.every((p) => p.locked), "every PUT ran under the owner's lock");
|
||||
assert.equal(fs.existsSync(join(f.rider.dataRoot, "proxy")), false, "the rider has no proxy state of its own");
|
||||
assert.equal(fs.existsSync(join(f.rider.configDir, "secrets", "proxy-management.key")), false);
|
||||
const ops = fs.readFileSync(f.receipts, "utf8").trim().split("\n").map((l) => JSON.parse(l).op);
|
||||
assert.deepEqual(ops, ["worker.key.ensure", "worker.key.ensure"], "the rider's receipt is in the owner's state directory");
|
||||
for (const k of [...Object.values(f.ownerKeys), ownerWorker]) assert.ok(f.state.keys.includes(k), "the rider removes none of the owner's keys");
|
||||
|
||||
// The rider rotates and sweeps its own key; the owner's keys stay.
|
||||
await rotateKey(f.opts(f.rider));
|
||||
await sweepKeys(f.opts(f.rider));
|
||||
for (const k of [...Object.values(f.ownerKeys), ownerWorker]) assert.ok(f.state.keys.includes(k));
|
||||
const riderNow = readKey(f.rider.configDir, { purpose: "worker" }).key;
|
||||
|
||||
// The owner's own worker key work and its bus model key reconcile leave the rider's key.
|
||||
await rotateKey(f.opts(f.owner));
|
||||
await sweepKeys(f.opts(f.owner));
|
||||
await ensureReady(f.opts(f.owner));
|
||||
const client = await loadManagementClient({ configDir: f.owner.configDir, proxy: f.owner.system.proxy });
|
||||
const manager = new ModelKeys({ credentials: { status: () => [], modelRecord: () => null }, client, configDir: f.owner.configDir, baseUrl: `http://127.0.0.1:${f.port}/v1` });
|
||||
const receipt = await manager.reconcile();
|
||||
assert.ok(receipt.removedKeyIds.length >= 1, "the reconcile did remove the owner's own stale bus key");
|
||||
assert.ok(f.state.keys.includes(riderNow), "the rider's key survives the owner's reconcile and cleanup");
|
||||
assert.equal((await ensureReady(f.opts(f.rider))).action, "held");
|
||||
});
|
||||
|
||||
test("the rider's lock identity is the owner's: a writer naming the rider's own config directory refuses", async (t) => {
|
||||
const f = await fixture(t);
|
||||
await ensureReady(f.opts(f.owner));
|
||||
// The same state directory under the rider's own identity is another proxy to the lock.
|
||||
const wrong = { ...f.rider.system, proxy: { ...f.rider.system.proxy, owner: { ...f.rider.system.proxy.owner, configDir: f.rider.configDir } } };
|
||||
// Give it every other piece, so only the lock identity differs.
|
||||
fs.copyFileSync(join(f.owner.configDir, "secrets", "proxy-management.key"), join(f.rider.configDir, "secrets", "proxy-management.key"));
|
||||
f.state.keys.push(`msk-${tag(f.rider.configDir)}-sentinel-${b64()}`);
|
||||
const puts = f.state.puts.length;
|
||||
await assert.rejects(ensureReady({ configDir: f.rider.configDir, system: wrong, purpose: "worker" }), (e) => e.code === "proxy-lock-invalid");
|
||||
assert.equal(f.state.puts.length, puts, "no write without the owner's identity");
|
||||
});
|
||||
|
||||
test("the owner's fence stops the rider's key write, and the rider's status reports it", async (t) => {
|
||||
const f = await fixture(t);
|
||||
await ensureReady(f.opts(f.rider));
|
||||
const held = readKey(f.rider.configDir, { purpose: "worker" });
|
||||
fs.writeFileSync(join(f.owner.dataRoot, "proxy", "mosaic-keys.uncertain"), "{}\n", { mode: 0o600 });
|
||||
const puts = f.state.puts.length;
|
||||
// A held key goes to the lock while the fence is set, and the lock refuses.
|
||||
await assert.rejects(ensureReady(f.opts(f.rider)), (e) => e.code === "proxy-uncertain");
|
||||
await assert.rejects(rotateKey(f.opts(f.rider)), (e) => e.code === "proxy-uncertain");
|
||||
assert.equal(f.state.puts.length, puts, "no PUT while the owner's fence is set");
|
||||
assert.deepEqual(readKey(f.rider.configDir, { purpose: "worker" }), held);
|
||||
const status = await keyStatus(f.opts(f.rider));
|
||||
assert.equal(status.proxy.fence, true);
|
||||
assert.equal(status.proxy.state, "read", "status reads the list with the owner's management key and sentinel");
|
||||
assert.equal(status.proxy.holdsKey, true);
|
||||
assert.equal(JSON.stringify(status).includes(MANAGE), false);
|
||||
});
|
||||
|
||||
test("a rider without its own secrets directory refuses before any proxy write", async (t) => {
|
||||
const f = await fixture(t);
|
||||
fs.rmdirSync(join(f.rider.configDir, "secrets"));
|
||||
await assert.rejects(ensureReady(f.opts(f.rider)), (e) => e.code === "worker-key-unreadable" && /secrets directory is missing/.test(e.message));
|
||||
assert.equal(f.state.puts.length, 0);
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setupState } from '../src/setup-reply.mjs';
|
||||
const org = { id: 'team', doc: { roles: { assistant: { definition: 'assistant' } } } };
|
||||
const human = { id: 'q', from_role: 'human', body: 'Hello' };
|
||||
const answer = { id: 'a', from_role: 'assistant', from_run: 'real-run', to_role: 'human', in_reply_to: 'q', body: 'Hello back' };
|
||||
test('hello needs an actual reply to the owner, including retired session history', async () => {
|
||||
const run = messages => setupState[0].check({ members: [org], read: async (_, name) => name === 'threads' ? [{ id: 'thread', instance: 'assistant' }] : name === 'sessions' ? [{ id: 'session' }] : messages });
|
||||
assert.equal((await run([human, answer])).state, 'done');
|
||||
assert.equal((await run([human])).state, 'next');
|
||||
assert.equal((await run([human, { ...answer, from_run: 'bus', body: 'The turn failed' }])).state, 'next');
|
||||
assert.equal((await run([{ ...answer, in_reply_to: null }])).state, 'next');
|
||||
assert.equal((await setupState[0].check({ members: [] })).state, 'next');
|
||||
assert.match((await setupState[0].check({ members: [org], read: async () => { throw Error(); } })).reason, /couldn't be checked/);
|
||||
});
|
||||
|
||||
import { failureBody, LENGTH_FAILURE_NOTICE_PREFIX } from '../../harness/src/failure-notice.mjs';
|
||||
for (const [kind, body] of [
|
||||
['failed turn', failureBody({ reason: 'adapter exited' })],
|
||||
['length failure', LENGTH_FAILURE_NOTICE_PREFIX + 'answer was too long'],
|
||||
['empty answer', '(the session gave no answer)'],
|
||||
]) test(`hello rejects the runner ${kind} notice, including its unslop note`, async () => {
|
||||
for (const note of ['', '\n\n[unslop: the check is broken, so this session\'s replies go unchecked: test]']) {
|
||||
const result = await setupState[0].check({ members: [org], read: async (_, name) => name === 'threads' ? [{ id: 'thread', instance: 'assistant' }] : name === 'sessions' ? [{ id: 'session' }] : [human, { ...answer, class: 'RESULT', body: body + note }] });
|
||||
assert.equal(result.state, 'next');
|
||||
}
|
||||
});
|
||||
test('one unavailable organization does not hide a real reply in another', async () => {
|
||||
const result = await setupState[0].check({ members: [{ id: 'stopped' }, org], read: async (member, name) => {
|
||||
if (member.id === 'stopped') throw Error('private');
|
||||
return name === 'threads' ? [{ id: 'thread', instance: 'assistant' }] : name === 'sessions' ? [{ id: 'session' }] : [human, answer];
|
||||
} });
|
||||
assert.equal(result.state, 'done'); assert.match(result.reason, /couldn't be checked/);
|
||||
});
|
||||
test('large histories scan newest first and stop at the first real reply', async () => {
|
||||
const calls = [];
|
||||
const result = await setupState[0].check({ members: [org], read: async (_, name, args) => {
|
||||
calls.push([name, args]);
|
||||
if (name === 'threads') return Array.from({ length: 51 }, (_, n) => ({ id: `t${n}`, at: String(n).padStart(3, '0'), instance: 'assistant' }));
|
||||
if (name === 'sessions') return Array.from({ length: 51 }, (_, n) => ({ id: `s${n}`, at: String(n).padStart(3, '0') }));
|
||||
return [human, answer, ...Array.from({ length: 198 }, () => human)];
|
||||
} });
|
||||
assert.equal(result.state, 'done');
|
||||
assert.deepEqual(calls.map(c => c[0]), ['threads', 'sessions', 'messages']);
|
||||
assert.equal(calls[1][1].thread, 't50'); assert.equal(calls[2][1].session, 's50');
|
||||
});
|
||||
test('bounded history without a reply stays honest and plain', async () => {
|
||||
let pages = 0;
|
||||
const result = await setupState[0].check({ members: [org], read: async (_, name) => name === 'threads' ? Array.from({ length: 51 }, (_, i) => ({ id: String(i), instance: 'assistant' })) : name === 'sessions' ? [{ id: 'session' }] : (pages++, Array.from({ length: 200 }, (_, i) => ({ ...human, id: `${pages}-${i}` }))) });
|
||||
assert.equal(result.state, 'next'); assert.match(result.reason, /couldn't be checked/); assert.equal(pages, 100);
|
||||
});
|
||||
@@ -716,6 +716,46 @@ test('#1873 F2: a stalled run puts one line on each message delivered to it and
|
||||
assert.equal(store.get('SELECT count(*) n FROM message_threads WHERE message=?', line.id).n, 0);
|
||||
});
|
||||
|
||||
// first-run-fixes-1 (B4): a refused start's line carries the launcher's plain reason, as one line
|
||||
// with no host path, so "launch-failed" alone no longer hides the cause.
|
||||
test('B4: a refused start puts its plain reason in Details, one line, with no host path', (t) => {
|
||||
const { b, store, call, A } = twoThreads(t);
|
||||
b.endLaunch({ business: 'demo', run: 'a-run', reason: 'idle' });
|
||||
const session = store.get('SELECT session FROM session_defaults WHERE thread=?', A).session;
|
||||
const notice = (code, why) => b.failureNotice({ business: 'demo', thread: A, session, code, why });
|
||||
const one = call('human', 'thread.send', { thread: A, body: 'one' });
|
||||
assert.deepEqual(notice('launch-failed', 'listen EINVAL /home/u/.mosaic-dev/org-runtime/acme/launches/acme/r1/tools.sock\n at Server.listen'), { posted: 1 });
|
||||
assert.equal(lines(store, one.id)[0].body, "The turn failed: the assistant couldn't start. Try again later, or check the agent in Agents.\nDetails: start refused: launch-failed: listen EINVAL a host path at Server.listen");
|
||||
const two = call('human', 'thread.send', { thread: A, body: 'two' });
|
||||
assert.deepEqual(notice('limit-reached', '{"path":["tokens"],"limit":0}'), { posted: 1 });
|
||||
assert.equal(lines(store, two.id)[0].body, LIMIT_LINE, 'a code with its own line leaves its reason out');
|
||||
const three = call('human', 'thread.send', { thread: A, body: 'three' });
|
||||
assert.deepEqual(notice('checkout-failed', 'checkout-failed'), { posted: 1 });
|
||||
assert.match(lines(store, three.id)[0].body, /\nDetails: start refused: checkout-failed$/, 'a reason that only repeats the code adds nothing');
|
||||
const four = call('human', 'thread.send', { thread: A, body: 'four' });
|
||||
assert.deepEqual(notice('checkout-failed', `stack: ${'y'.repeat(400)} file:///x/y`), { posted: 1 });
|
||||
const details = lines(store, four.id)[0].body.split('\nDetails: ')[1];
|
||||
assert.ok(details.startsWith('start refused: checkout-failed: stack: yyy'));
|
||||
assert.ok(details.endsWith('...'), details.slice(-20));
|
||||
assert.equal(details.length, 'start refused: checkout-failed: '.length + 300);
|
||||
const five = call('human', 'thread.send', { thread: A, body: 'five' });
|
||||
assert.deepEqual(notice('project-refused', 'see ~/work/x and file:///etc/y, (/srv/z)'), { posted: 1 });
|
||||
assert.match(lines(store, five.id)[0].body, /\nDetails: start refused: project-refused: see a host path and a host path, \(a host path\)$/);
|
||||
// Review P3-4: a path after a backtick, `{` or `|` is replaced too, and the cut never splits a character.
|
||||
const six = call('human', 'thread.send', { thread: A, body: 'six' });
|
||||
assert.deepEqual(notice('checkout-failed', 'bad file `/home/u/.mosaic-x/a.json` {/srv/a} |~/b|'), { posted: 1 });
|
||||
assert.match(lines(store, six.id)[0].body, /\nDetails: start refused: checkout-failed: bad file `a host path` \{a host path\} \|a host path\|$/);
|
||||
// Re-check P3-1: a character that ends one path can start the next.
|
||||
const eight = call('human', 'thread.send', { thread: A, body: 'eight' });
|
||||
assert.deepEqual(notice('checkout-failed', 'at `/home/u/{a}/home/u/secret` and (/srv/a)/srv/b;/srv/c'), { posted: 1 });
|
||||
assert.match(lines(store, eight.id)[0].body, /\nDetails: start refused: checkout-failed: at `a host path\}a host path` and \(a host path\)a host path;a host path$/);
|
||||
const seven = call('human', 'thread.send', { thread: A, body: 'seven' });
|
||||
assert.deepEqual(notice('checkout-failed', `${'x'.repeat(296)}${'\u{1F600}'.repeat(10)}`), { posted: 1 });
|
||||
const cut = lines(store, seven.id)[0].body.split('\nDetails: start refused: checkout-failed: ')[1];
|
||||
assert.equal(cut, `${'x'.repeat(296)}\u{1F600}...`);
|
||||
assert.doesNotMatch(cut, /[\uD800-\uDBFF](?![\uDC00-\uDFFF])/, 'no lone high surrogate');
|
||||
});
|
||||
|
||||
test('#1873 F2: failureNotice refuses a malformed record before any write', (t) => {
|
||||
const { b, store, A } = twoThreads(t);
|
||||
const session = store.get('SELECT session FROM session_defaults WHERE thread=?', A).session;
|
||||
@@ -726,7 +766,10 @@ test('#1873 F2: failureNotice refuses a malformed record before any write', (t)
|
||||
[{ business: 'demo', code: 'Limit Reached', run: 'a-run' }, 'invalid-request'],
|
||||
[{ business: 'demo', code: 'x'.repeat(65), run: 'a-run' }, 'invalid-request'],
|
||||
[{ business: 'demo', code: 7, run: 'a-run' }, 'invalid-request'],
|
||||
[{ business: 'demo', code: 'limit-reached', run: 'a-run', why: 'secret text' }, 'invalid-request'],
|
||||
// first-run-fixes-1 (B4): a reason rides only on a refused start, as a string of at most 4096.
|
||||
[{ business: 'demo', code: 'limit-reached', run: 'a-run', why: 'a reason' }, 'invalid-request'],
|
||||
[{ business: 'demo', code: 'limit-reached', thread: A, session, why: 7 }, 'invalid-request'],
|
||||
[{ business: 'demo', code: 'limit-reached', thread: A, session, why: 'x'.repeat(4097) }, 'invalid-request'],
|
||||
[{ business: 'demo', code: 'limit-reached', run: 'nobody-run' }, 'unknown-run'],
|
||||
[{ business: 'demo', code: 'limit-reached', thread: A, session: 'no-such-session' }, 'session-not-found'],
|
||||
];
|
||||
|
||||
@@ -66,7 +66,8 @@ export const USAGE = `usage:
|
||||
${PLUGINS_USAGE}
|
||||
${CREDENTIALS_USAGE}
|
||||
mosaic proxy fetch | status [--json] | fence status [--json] | fence clear --proxy-restarted | fence clear --restart [--business ID] | init [--generate-key] [--port N] [--business ID] [--rotate-grace-minutes N] [--first-output-seconds N]
|
||||
mosaic proxy unit render|install|start|stop|restart|status [--json] | init-lock status|clear
|
||||
mosaic proxy undo
|
||||
mosaic proxy unit render|install|start|stop|restart|status [--json] | init-lock status|clear | ride --instance NAME | ride --off
|
||||
${HOSTS_USAGE}
|
||||
${GRANTS_USAGE}
|
||||
${ORG_INSTANCES_USAGE}
|
||||
|
||||
@@ -17,6 +17,7 @@ import { systemConfigProblem } from "../../organization/src/system-config-proble
|
||||
import { businessFilePath } from "../../organization/src/organization-config.mjs";
|
||||
import { busOrganization } from "../../bus/src/organization-context.mjs";
|
||||
import { BusError } from "../../bus/src/broker.mjs";
|
||||
import { RIDE_LINES } from "../../model-proxy/src/settings.mjs";
|
||||
import { CliError } from "./errors.mjs";
|
||||
import { accessContextFor } from "./access.mjs";
|
||||
|
||||
@@ -57,6 +58,9 @@ function instanceProblem(problem, label) {
|
||||
m = new RegExp(`^instance-config-mismatch: --instance (${INSTANCE}) names `).exec(body);
|
||||
if (m) return `instance-config-mismatch: --instance ${m[1]} names its own config, but MOSAIC_CONFIG names another`;
|
||||
if (body.startsWith("instance-config-mismatch: ")) return "instance-config-mismatch: --instance names its own config, but MOSAIC_CONFIG names another";
|
||||
// proxy-ride refusals carry their fixed owner line from settings.mjs, never the child's text.
|
||||
m = /^(proxy-ride-(?:invalid|owner-missing|conflict)): /.exec(body);
|
||||
if (m) return `${m[1]}: ${RIDE_LINES[m[1]]}`;
|
||||
if (body.startsWith("instance-name-invalid: ")) return `instance-name-invalid: an instance name must match /^${INSTANCE}$/`;
|
||||
if (body.startsWith("configuration not found: ")) {
|
||||
m = new RegExp(`\\(run (scripts/bootstrap\\.sh(?: --instance ${INSTANCE})?) to create it\\)$`).exec(body);
|
||||
@@ -65,7 +69,14 @@ function instanceProblem(problem, label) {
|
||||
return null;
|
||||
}
|
||||
|
||||
export function loadSystem({ env = process.env, instance = null } = {}) {
|
||||
// proxy-ride first slice (Jason 2026-11-21): on an instance whose proxy-ride.json names another
|
||||
// instance, validate prints the owner's proxy with an `owner` object. Only worker runs use it
|
||||
// (`ride: true`, packages/processing-control/src/container-cli.mjs). Every other caller, the
|
||||
// bus boot and the Console among them, gets the system config without that proxy, so a riding
|
||||
// instance's buses run exactly as an instance with no proxy runs. That holds while the owner is
|
||||
// valid: validate resolves the owner on every call, so while proxy-ride.json exists an owner
|
||||
// problem refuses every verb on the rider, buses and the Console included.
|
||||
export function loadSystem({ env = process.env, instance = null, ride = false } = {}) {
|
||||
const proc = spawnSync(process.execPath, [join(REPO, "scripts", "mosaic-config.mjs"), "validate", ...(instance === null ? [] : ["--instance", instance])], {
|
||||
encoding: "utf8",
|
||||
maxBuffer: 1024 * 1024,
|
||||
@@ -76,11 +87,14 @@ export function loadSystem({ env = process.env, instance = null } = {}) {
|
||||
const known = instanceProblem(String(proc.stderr ?? "").trim(), label);
|
||||
throw new CliError(known ? `system config problem (mosaic-config exit ${proc.status}): ${known}` : systemConfigProblem(proc, env, label), 3);
|
||||
}
|
||||
let system;
|
||||
try {
|
||||
return JSON.parse(proc.stdout);
|
||||
system = JSON.parse(proc.stdout);
|
||||
} catch {
|
||||
throw new CliError("system config: mosaic-config printed something that isn't JSON", 3);
|
||||
}
|
||||
if (!ride && system?.proxy?.owner) delete system.proxy;
|
||||
return system;
|
||||
}
|
||||
|
||||
export function rolesDir(env = process.env) {
|
||||
@@ -207,7 +221,7 @@ export function bootConfig({ system, businessId, orgRoot = system.dataRoot, env
|
||||
const config = {
|
||||
dataRoot: orgRoot,
|
||||
...(orgRoot === system.dataRoot ? {} : { instanceRoot: system.dataRoot, org: { id: b.id }, instanceDataRoot: system.dataRoot, instanceConfigDir: configDir(env) }),
|
||||
...(system.proxy ? { proxy: system.proxy } : {}),
|
||||
...(system.proxy && !system.proxy.owner ? { proxy: system.proxy } : {}),
|
||||
businesses: { [b.id]: busOrganization(b, resolved) },
|
||||
organization: {dir:configDir(env),rolesDir:rolesDir(env),system:vars},
|
||||
launches: [],
|
||||
|
||||
@@ -173,7 +173,7 @@ import {
|
||||
workspaceDir,
|
||||
writeSessionFile,
|
||||
} from "../../seat/src/session.mjs";
|
||||
import { BWRAP, sandboxProblem } from "../../seat/src/sandbox.mjs";
|
||||
import { BWRAP, sandboxProblem, TOOL_SOCKET } from "../../seat/src/sandbox.mjs";
|
||||
import { collectCompactions, READ_BYTES, readBudget, readStreams, STREAMS } from "../../seat/src/compactions.mjs";
|
||||
import { CheckoutError, ensureCheckouts } from "../../seat/src/checkout.mjs";
|
||||
import { createGitSocket } from "./git-socket.mjs";
|
||||
@@ -742,7 +742,8 @@ export function createLauncher({
|
||||
const sessionDir = store ? store.session : join(runDir, "session");
|
||||
if (!store) mkdirSync(sessionDir, { mode: 0o700 });
|
||||
if (store) compactions(store, model.harness, harness, { instance, thread, session, run });
|
||||
const toolSocket = join(runDir, "tools.sock");
|
||||
// first-run-fixes-1 (B4): a short path inside the sandbox, bound from the run's sock/.
|
||||
const toolSocket = TOOL_SOCKET;
|
||||
const turnMarker = join(runDir, "turn.done");
|
||||
const version = harnessVersion !== undefined ? harnessVersion : await call(model.harness, "version", () => harness.version({ env }));
|
||||
// Row 137 (#1631): a role and thread holding an approved, unspent merge decision get land_work.
|
||||
@@ -1096,7 +1097,8 @@ export function createLauncher({
|
||||
refusalSeen.set(key, noticed);
|
||||
if (noticedThreads.get(key) !== noticed && (code !== "launch-failed" || repeated)) {
|
||||
try {
|
||||
await host.op({ op: "failureNotice", record: { business: b.id, thread: t.thread, session: t.session, code } });
|
||||
// first-run-fixes-1 (B4): with the refusal's plain reason, so the chat says why.
|
||||
await host.op({ op: "failureNotice", record: { business: b.id, thread: t.thread, session: t.session, code, why: reason(e).slice(0, 4096) } });
|
||||
noticedThreads.set(key, noticed);
|
||||
noticeFailed.delete(key);
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
import { lstatSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { configDir } from '../../organization/src/organization-config.mjs';
|
||||
import { createProxyLock } from '../../bus/src/proxy-lock.mjs';
|
||||
import { loadManagementClient } from '../../model-proxy/src/client.mjs';
|
||||
import { CliError } from './errors.mjs';
|
||||
import { loadSystem, rolesDir } from './config.mjs';
|
||||
import { orgSelector } from './org-selector.mjs';
|
||||
import { refuseInsideAgent } from './transport.mjs';
|
||||
import { fetchPinned } from '../../model-proxy/src/fetch.mjs';
|
||||
import { validManagementKey, proxyTiming } from '../../model-proxy/src/common.mjs';
|
||||
import { organizationWriter } from '../../organization/src/organization.mjs';
|
||||
import { readRider } from '../../model-proxy/src/ride.mjs';
|
||||
import { orgUsesFixture } from './dev-fixture.mjs';
|
||||
import { ownedText } from '../../model-proxy/src/admin.mjs';
|
||||
import { RIDE_LINES, RIDE_NAME, readRide, createRide, removeRide } from '../../model-proxy/src/settings.mjs';
|
||||
import { createProxyAdmin } from '../../model-proxy/src/admin-control.mjs';
|
||||
import { listOrgs } from '../../organization/src/org-registry.mjs';
|
||||
import { busesStopped, instanceFromConfig } from './proxy-admin-host.mjs';
|
||||
@@ -47,6 +54,10 @@ function adminFor(io, system, deps) {
|
||||
dataRoot: config.dataRoot, configDir: dir, instance: instanceFromConfig(io.env), env: io.env, fetch: deps.fetch ?? fetchPinned,
|
||||
unitDir: deps.unitDir ?? null,
|
||||
buses: () => busesStopped({ dataRoot: config.dataRoot, configDir: dir }),
|
||||
riders: async () => {
|
||||
const writer = organizationWriter({ dir, rolesDir: rolesDir(io.env) });
|
||||
return (await listOrgs({ configDir: dir, dataRoot: config.dataRoot })).filter(org => org.state === 'active').map(org => readRider({ id: org.id, read: () => writer.read(org.id).document, readLog: () => ownedText(writer.logFile(org.id), { mask: 0o022 }), isFixture: orgUsesFixture }));
|
||||
},
|
||||
orgs: async () => (await listOrgs({ configDir: dir, dataRoot: config.dataRoot })).filter(org => org.state === 'active').map(org => ({ id: org.id, proxy: 'shared', catalogue: null })),
|
||||
});
|
||||
}
|
||||
@@ -57,6 +68,10 @@ const hostCode = (error, fallback) => (/^proxy-[a-z-]+$/.test(error?.code ?? '')
|
||||
async function setupCommand(verb, rest, io, { system, deps }) {
|
||||
const admin = adminFor(io, system, deps);
|
||||
try {
|
||||
if (verb === 'undo') {
|
||||
if (rest.length) throw failure('proxy-usage', 4);
|
||||
print(io, await admin.undo()); return;
|
||||
}
|
||||
if (verb === 'status') {
|
||||
if (!(rest.length === 0 || (rest.length === 1 && rest[0] === '--json'))) throw failure('proxy-usage', 4);
|
||||
const status = await admin.status();
|
||||
@@ -91,14 +106,51 @@ async function setupCommand(verb, rest, io, { system, deps }) {
|
||||
throw failure('proxy-usage', 4);
|
||||
}
|
||||
|
||||
// proxy-ride first slice (Jason 2026-11-21): `mosaic proxy ride --instance NAME` writes this
|
||||
// instance's proxy-ride.json, then loads the system config exactly as a worker run loads it; any
|
||||
// refusal removes the file again, so a file the loader refuses is never left behind. `--off`
|
||||
// removes the file without loading the config, so it works when the owner is gone. Neither form
|
||||
// changes the owner instance, its proxy or any key.
|
||||
const RIDE_CODES = Object.keys(RIDE_LINES);
|
||||
const rideFailure = (code) => Object.assign(new CliError(`${code}: ${RIDE_LINES[code]}`, 2), { code });
|
||||
const rideCode = (error) => RIDE_CODES.find(code => error?.code === code || new RegExp(`(?:^|: )${code}: `).test(error?.message ?? ''));
|
||||
async function rideCommand(rest, io, { validate }) {
|
||||
const dir = configDir(io.env);
|
||||
if (rest.length === 1 && rest[0] === '--off') {
|
||||
let removed;
|
||||
try { removed = removeRide(dir); } catch { throw rideFailure('proxy-ride-invalid'); }
|
||||
return print(io, { riding: null, removed });
|
||||
}
|
||||
if (rest.length !== 2 || rest[0] !== '--instance') throw failure('proxy-usage', 4);
|
||||
const name = rest[1];
|
||||
if (!RIDE_NAME.test(name)) throw rideFailure('proxy-ride-invalid');
|
||||
let current;
|
||||
try { current = readRide(dir); } catch (error) { throw rideFailure(rideCode(error) ?? 'proxy-ride-invalid'); }
|
||||
if (current && current.instance !== name) {
|
||||
throw Object.assign(new CliError(`proxy-usage: this instance already rides instance ${current.instance}; run mosaic proxy ride --off first`, 4), { code: 'proxy-usage' });
|
||||
}
|
||||
let undo = () => {};
|
||||
if (!current) {
|
||||
try { lstatSync(join(dir, 'proxy.json')); throw rideFailure('proxy-ride-conflict'); }
|
||||
catch (error) { if (error instanceof CliError) throw error; if (error.code !== 'ENOENT') throw rideFailure('proxy-ride-conflict'); }
|
||||
try { undo = createRide(dir, name); } catch { throw rideFailure('proxy-ride-invalid'); }
|
||||
}
|
||||
let system;
|
||||
try { system = validate(); }
|
||||
catch (error) { undo(); const code = rideCode(error); if (code) throw rideFailure(code); throw error; }
|
||||
if (system?.proxy?.owner?.instance !== name || !Number.isInteger(system.proxy.port)) { undo(); throw rideFailure('proxy-ride-owner-missing'); }
|
||||
return print(io, { riding: name, port: system.proxy.port });
|
||||
}
|
||||
|
||||
export async function proxyCommand(args, io, { system, callFor, prompt = promptProxyKey, fetch = fetchPinned, ...deps }) {
|
||||
const [verb, ...rest] = args;
|
||||
if (args.includes('--tester')) throw failure('human-required', 3);
|
||||
// #1873: every proxy verb, read or write, runs only from a human shell.
|
||||
if (['init', 'fetch', 'fence', 'status', 'unit', 'init-lock'].includes(verb)) {
|
||||
if (['init', 'fetch', 'fence', 'status', 'unit', 'init-lock', 'ride', 'undo'].includes(verb)) {
|
||||
try { refuseInsideAgent(io.env); } catch { throw failure('human-required', 3); }
|
||||
}
|
||||
if (['status', 'unit', 'init-lock'].includes(verb)) return setupCommand(verb, rest, io, { system, deps: { ...deps, fetch } });
|
||||
if (verb === 'ride') return rideCommand(rest, io, { validate: deps.rideValidate ?? (() => loadSystem({ env: io.env, ride: true })) });
|
||||
if (['status', 'unit', 'init-lock', 'undo'].includes(verb)) return setupCommand(verb, rest, io, { system, deps: { ...deps, fetch } });
|
||||
if (verb === 'fence' && rest[0] === 'clear' && rest.includes('--restart')) {
|
||||
// #1873: restart the proxy unit, then send the restart evidence to the bus, which re-proves it
|
||||
// on the host before it clears the fence. --business/--org names the bus.
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// proxy-ride first slice (Jason 2026-11-21): `mosaic proxy ride --instance NAME | --off`, the CLI
|
||||
// loader's view of a riding instance, the bus boot config, and the worker launcher's refusal line.
|
||||
// The rider is the cli fixture's config; the owner is named instance "owner" under a made-up HOME.
|
||||
// The real scripts/mosaic-config.mjs runs; nothing reads a real config, proxy or secret.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { existsSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { main } from '../src/cli.mjs';
|
||||
import { bootConfig, loadSystem } from '../src/config.mjs';
|
||||
import { proxyCommand } from '../src/model-proxy.mjs';
|
||||
import { RIDE_LINES, installPaths } from '../../model-proxy/src/settings.mjs';
|
||||
import { fixture, io, tmp } from './helpers.mjs';
|
||||
|
||||
const MANAGE = 'ride-cli-management-key';
|
||||
const CONTAINER_CLI = fileURLToPath(new URL('../../processing-control/src/container-cli.mjs', import.meta.url));
|
||||
// The stand-in launch step of worker-proxy-task.test.mjs; FAKE_WP=proxy answers with the proxy it got.
|
||||
const HOOK = fileURLToPath(new URL('../../processing-control/tests/fixtures/worker-proxy-hook.mjs', import.meta.url));
|
||||
const code = (c) => (e) => e.code === c;
|
||||
|
||||
function setup(t) {
|
||||
const root = tmp(t, 'rcl-');
|
||||
const f = fixture(root, 'acme');
|
||||
f.env.HOME = root;
|
||||
const ownerDir = join(root, '.config', 'mosaic-owner'), ownerData = join(root, 'od');
|
||||
mkdirSync(join(ownerDir, 'secrets'), { recursive: true, mode: 0o700 }); mkdirSync(ownerData, { mode: 0o700 });
|
||||
writeFileSync(join(ownerDir, 'config.json'), JSON.stringify({ configVersion: 1, environment: 'development', dataRoot: ownerData, execution: { backend: 'docker', provider: 'fixture', model: 'fixture' } }));
|
||||
writeFileSync(join(ownerData, 'instance.json'), JSON.stringify({ instanceVersion: 1, name: 'owner' }));
|
||||
const value = { port: 18452, binary: installPaths(ownerData).binary };
|
||||
writeFileSync(join(ownerDir, 'proxy.json'), JSON.stringify(value));
|
||||
writeFileSync(join(ownerDir, 'secrets', 'proxy-management.key'), MANAGE, { mode: 0o600 });
|
||||
const riderDir = join(root, 'config');
|
||||
return { root, f, env: f.env, riderDir, rideFile: join(riderDir, 'proxy-ride.json'), owner: { dir: ownerDir, dataRoot: ownerData, value } };
|
||||
}
|
||||
const ride = (s, args, env = s.env) => { const x = io(env); return main(['proxy', 'ride', ...args], x).then(() => x); };
|
||||
|
||||
test('ride --instance writes the file, prints the owner port, and a second identical ride holds it', async (t) => {
|
||||
const s = setup(t);
|
||||
let x = await ride(s, ['--instance', 'owner']);
|
||||
assert.deepEqual(JSON.parse(x.out.text), { riding: 'owner', port: 18452 });
|
||||
assert.equal(readFileSync(s.rideFile, 'utf8'), '{"version":1,"instance":"owner"}\n');
|
||||
assert.equal(lstatSync(s.rideFile).mode & 0o777, 0o600);
|
||||
assert.equal(x.out.text.includes(MANAGE) || x.err.text.includes(MANAGE), false);
|
||||
x = await ride(s, ['--instance', 'owner']);
|
||||
assert.deepEqual(JSON.parse(x.out.text), { riding: 'owner', port: 18452 });
|
||||
// Nothing of the owner's changed.
|
||||
assert.deepEqual(JSON.parse(readFileSync(join(s.owner.dir, 'proxy.json'), 'utf8')), s.owner.value);
|
||||
assert.equal(existsSync(join(s.riderDir, 'proxy.json')), false);
|
||||
});
|
||||
|
||||
test('ride and ride --off run only from a human shell', async (t) => {
|
||||
const s = setup(t);
|
||||
for (const args of [['--instance', 'owner'], ['--off']]) {
|
||||
await assert.rejects(ride(s, args, { ...s.env, CLAUDECODE: '1' }), code('human-required'));
|
||||
await assert.rejects(ride(s, [...args, '--tester']), code('human-required'));
|
||||
}
|
||||
assert.equal(existsSync(s.rideFile), false);
|
||||
});
|
||||
|
||||
test('a ride the loader refuses is removed again, with the ride code and its owner line', async (t) => {
|
||||
const s = setup(t);
|
||||
const cases = [
|
||||
[['--instance', 'nobody'], 'proxy-ride-owner-missing', () => {}],
|
||||
[['--instance', 'owner'], 'proxy-ride-owner-missing', () => rmSync(join(s.owner.dir, 'proxy.json'))],
|
||||
];
|
||||
for (const [args, c, prep] of cases) {
|
||||
prep();
|
||||
await assert.rejects(ride(s, args), (e) => e.code === c && e.message === `${c}: ${RIDE_LINES[c]}` && e.exitCode === 2);
|
||||
assert.equal(existsSync(s.rideFile), false, `${c}: the refused file is gone`);
|
||||
}
|
||||
await assert.rejects(ride(s, ['--instance', '../x']), code('proxy-ride-invalid'));
|
||||
assert.equal(existsSync(s.rideFile), false);
|
||||
});
|
||||
|
||||
test('ride refuses beside its own proxy.json, and over a ride of another instance', async (t) => {
|
||||
const s = setup(t);
|
||||
writeFileSync(join(s.riderDir, 'proxy.json'), '{}');
|
||||
await assert.rejects(ride(s, ['--instance', 'owner']), code('proxy-ride-conflict'));
|
||||
assert.equal(existsSync(s.rideFile), false);
|
||||
rmSync(join(s.riderDir, 'proxy.json'));
|
||||
writeFileSync(s.rideFile, '{"version":1,"instance":"other"}\n', { mode: 0o600 });
|
||||
await assert.rejects(ride(s, ['--instance', 'owner']), (e) => e.code === 'proxy-usage' && e.exitCode === 4 && /already rides instance other/.test(e.message));
|
||||
assert.equal(readFileSync(s.rideFile, 'utf8'), '{"version":1,"instance":"other"}\n', 'the existing ride is left as it was');
|
||||
});
|
||||
|
||||
test('ride --off removes the file, also when the owner is gone, and says when there was none', async (t) => {
|
||||
const s = setup(t);
|
||||
await ride(s, ['--instance', 'owner']);
|
||||
rmSync(s.owner.dir, { recursive: true });
|
||||
let x = await ride(s, ['--off']);
|
||||
assert.deepEqual(JSON.parse(x.out.text), { riding: null, removed: true });
|
||||
assert.equal(existsSync(s.rideFile), false);
|
||||
x = await ride(s, ['--off']);
|
||||
assert.deepEqual(JSON.parse(x.out.text), { riding: null, removed: false });
|
||||
for (const args of [[], ['--instance'], ['--off', '--instance', 'owner'], ['--on']]) await assert.rejects(ride(s, args), code('proxy-usage'));
|
||||
});
|
||||
|
||||
test('a validate seam that answers another owner or no port removes the file', async (t) => {
|
||||
const s = setup(t);
|
||||
for (const answer of [{ proxy: { port: 1, owner: { instance: 'elsewhere' } } }, { proxy: { owner: { instance: 'owner' } } }, {}]) {
|
||||
const x = io(s.env);
|
||||
await assert.rejects(proxyCommand(['ride', '--instance', 'owner'], x, { system: () => ({}), rideValidate: () => answer }), code('proxy-ride-owner-missing'));
|
||||
assert.equal(existsSync(s.rideFile), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('loadSystem drops the ridden proxy unless a worker run asks; the bus boot config is the one with no proxy', async (t) => {
|
||||
const s = setup(t);
|
||||
const plain = bootConfig({ system: loadSystem({ env: s.env }), businessId: 'acme', env: s.env });
|
||||
await ride(s, ['--instance', 'owner']);
|
||||
const off = loadSystem({ env: s.env });
|
||||
assert.equal(Object.hasOwn(off, 'proxy'), false, 'every caller but a worker run sees no proxy');
|
||||
const on = loadSystem({ env: s.env, ride: true });
|
||||
assert.deepEqual(on.proxy, { ...s.owner.value, owner: { instance: 'owner', configDir: s.owner.dir, dataRoot: s.owner.dataRoot } });
|
||||
for (const system of [off, on]) {
|
||||
const boot = bootConfig({ system, businessId: 'acme', env: s.env });
|
||||
assert.equal(Object.hasOwn(boot, 'proxy'), false);
|
||||
assert.deepEqual(boot, plain, "the rider's bus boots exactly as it did before the ride");
|
||||
}
|
||||
// An instance with its own proxy keeps it in the boot config, as before.
|
||||
const own = bootConfig({ system: { ...off, proxy: { port: 18460, binary: '/x' } }, businessId: 'acme', env: s.env });
|
||||
assert.deepEqual(own.proxy, { port: 18460, binary: '/x' });
|
||||
});
|
||||
|
||||
test('a ride refusal reaches loadSystem and the worker launcher as its code and owner line', async (t) => {
|
||||
const s = setup(t);
|
||||
writeFileSync(s.rideFile, '{"version":1,"instance":"owner","path":"/x"}', { mode: 0o600 });
|
||||
const line = `proxy-ride-invalid: ${RIDE_LINES['proxy-ride-invalid']}`;
|
||||
assert.throws(() => loadSystem({ env: s.env }), (e) => e.exitCode === 3 && e.message === `system config problem (mosaic-config exit 2): ${line}`);
|
||||
const r = spawnSync(process.execPath, [CONTAINER_CLI, '--check'], { env: s.env, encoding: 'utf8', timeout: 20000 });
|
||||
assert.equal(r.status, 3, r.stderr);
|
||||
assert.equal(r.stderr, `processing: ${line}\n`);
|
||||
assert.equal(r.stderr.includes(s.root), false);
|
||||
});
|
||||
|
||||
test("a worker launch through container-cli is given the owner's proxy", async (t) => {
|
||||
const s = setup(t);
|
||||
const launch = () => spawnSync(process.execPath, ['--import', HOOK, CONTAINER_CLI], { env: { ...s.env, FAKE_WP: 'proxy' }, encoding: 'utf8', timeout: 20000 });
|
||||
let r = launch();
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.equal(r.stdout, 'no-owner:no-proxy', 'no ride file: no proxy, as before');
|
||||
await ride(s, ['--instance', 'owner']);
|
||||
r = launch();
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.equal(r.stdout, 'owner:18452');
|
||||
});
|
||||
@@ -128,3 +128,12 @@ test('proxy fetch shows the page\'s progress steps and writes the same fetch rec
|
||||
await assert.rejects(proxyCommand(['fetch'], human(), { system: failed, fetch: async () => { throw Object.assign(Error('mismatch'), { code: 'proxy-fetch-hash' }); } }), code('proxy-fetch-hash'));
|
||||
assert.throws(() => readFileSync(join(failed.dataRoot, 'state', 'proxy-admin.jsonl')), { code: 'ENOENT' });
|
||||
});
|
||||
|
||||
test('proxy undo is the same owner-only unfinished-setup action as the screen', async () => {
|
||||
let calls = 0; const out = io();
|
||||
await proxyCommand(['undo'], out, { system: fakeSystem, admin: { undo: async () => { calls++; return { removed: true }; } } });
|
||||
assert.equal(calls, 1); assert.match(out.out.text, /removed/);
|
||||
await assert.rejects(proxyCommand(['undo', 'extra'], io(), { system: fakeSystem, admin: {} }), code('proxy-usage'));
|
||||
const agent = io(); agent.env.MOSAIC_AGENT_RUN = 'fixture';
|
||||
await assert.rejects(proxyCommand(['undo'], agent, { system: fakeSystem, admin: {} }), code('human-required'));
|
||||
});
|
||||
@@ -2210,10 +2210,12 @@ export class Store {
|
||||
// C1's scripts/mosaic runs B's host, as a copy-check failure needs.
|
||||
// Row 294: config.mjs imports access/transport. Task 5b also imports the built-in catalogue and
|
||||
// its task, bus, seat and processing-control dependencies; the rehearsal needs those files too.
|
||||
// proxy-ride-1: config.mjs imports the ride refusal lines from model-proxy/src/settings.mjs, whose
|
||||
// common.mjs reads model-proxy/PIN when it loads.
|
||||
const RCOPIES=join(base,'rcopies');mkdirSync(RCOPIES);
|
||||
for(const [id,v,froms] of [[B,'3g',['3f']],[C,'3h',['3f','3g']],[A,'3g',['3f']],[C1,'3g',['3f']]]){
|
||||
const d=join(RCOPIES,id);
|
||||
for(const p of ['scripts/mosaic','scripts/mosaic-config.mjs','packages/cli/src/config.mjs','packages/cli/src/errors.mjs','packages/cli/src/access.mjs','packages/cli/src/org-selector.mjs','packages/cli/src/transport.mjs','packages/bus/src/business.mjs','packages/bus/src/organization-context.mjs','packages/bus/src/request-store.mjs','packages/bus/src/requirement-catalog.mjs','packages/tasks/src','packages/seat/src/landing.mjs','packages/seat/src/checkout.mjs','packages/processing-control/src','packages/plugins/src/kinds.mjs','packages/organization/src','packages/business/src','packages/library/src','roles'])cpSync(join(repo,p),join(d,p),{recursive:true});
|
||||
for(const p of ['scripts/mosaic','scripts/mosaic-config.mjs','packages/cli/src/config.mjs','packages/cli/src/errors.mjs','packages/cli/src/access.mjs','packages/cli/src/org-selector.mjs','packages/cli/src/transport.mjs','packages/bus/src/business.mjs','packages/bus/src/organization-context.mjs','packages/bus/src/request-store.mjs','packages/bus/src/requirement-catalog.mjs','packages/tasks/src','packages/seat/src/landing.mjs','packages/seat/src/checkout.mjs','packages/processing-control/src','packages/model-proxy/src','packages/model-proxy/PIN','packages/plugins/src/kinds.mjs','packages/organization/src','packages/business/src','packages/library/src','roles'])cpSync(join(repo,p),join(d,p),{recursive:true});
|
||||
// Row 333 R2 (#1831): what the business loader imports from outside its directory, model-quota.mjs included.
|
||||
for(const p of businessImportedFiles(repo))if(!existsSync(join(d,p)))cpSync(join(repo,p),join(d,p));
|
||||
if(id===C1)writeFileSync(join(d,'scripts','mosaic'),`#!/usr/bin/env bash\nexec node "${join(RCOPIES,B,'packages','cli','src','cli.mjs')}" "$@"\n`,{mode:0o755});
|
||||
|
||||
@@ -549,7 +549,8 @@ test("#1873 F2 the same launch-failed refusal twice for one message posts one li
|
||||
const A = host.call("thread.create", { project, name: "alpha" }).id;
|
||||
host.call("thread.send", { thread: A, body: "for A" });
|
||||
const [line] = await until(() => failedLines(host, A).length && failedLines(host, A));
|
||||
assert.match(line.body, /\nDetails: start refused: launch-failed$/);
|
||||
// first-run-fixes-1 (B4): the line carries the refusal's plain reason, not only the code.
|
||||
assert.match(line.body, /\nDetails: start refused: launch-failed: launch-op refused: launch-op-refused$/);
|
||||
for (let i = 0; i < 3; i++) await host.launcher.tick();
|
||||
assert.equal(failedLines(host, A).length, 1);
|
||||
});
|
||||
|
||||
@@ -238,7 +238,7 @@ cross-role), plus the reads and `raise_decision`. The broker still decides
|
||||
every call; a tool being present is not permission.
|
||||
|
||||
The harness never holds the capability. Tools call the runner's tool socket
|
||||
(`tools.sock`, 0600) with `{tool, args}`; the runner checks the name
|
||||
(`tools.sock`, 0600, at `/run/mosaic/tools.sock` inside the sandbox) with `{tool, args}`; the runner checks the name
|
||||
against `tools.json` and forwards the call with its own capability. A
|
||||
refusal comes back to the model as `refused: <code>`.
|
||||
|
||||
|
||||
@@ -149,7 +149,8 @@ export function turnCause(stdout, secrets = []) {
|
||||
}
|
||||
|
||||
// The chat body for a failed turn: the plain cause first, the technical reason after.
|
||||
export const TURN_FAILURE_NOTICE_PREFIX = 'The turn failed: ';
|
||||
export const DETAILS = "\nDetails: ";
|
||||
export function failureBody(turn) {
|
||||
return turn.cause ? `The turn failed: ${turn.cause}${DETAILS}${turn.reason}` : `The turn failed: ${turn.reason}`;
|
||||
return turn.cause ? `${TURN_FAILURE_NOTICE_PREFIX}${turn.cause}${DETAILS}${turn.reason}` : `${TURN_FAILURE_NOTICE_PREFIX}${turn.reason}`;
|
||||
}
|
||||
@@ -63,7 +63,7 @@ it was installed from (`systemctl --user cat <unit>` shows it). If the new
|
||||
code is in that same tree, a restart picks it up. If it is in another tree,
|
||||
the unit keeps the old PIN until it is installed again from the new tree:
|
||||
stop it, remove its unit file, then `mosaic proxy unit install` from the new
|
||||
tree, because install never replaces a unit. Then run `mosaic proxy fetch` (or Fetch on the Console's
|
||||
tree, because install never replaces a unit. An identical installed file is a no-op on retry. Then run `mosaic proxy fetch` (or Fetch on the Console's
|
||||
Model setup page), which installs the new release beside the old one
|
||||
under `<dataRoot>/opt/cliproxyapi/<version>/`. Then restart the proxy with
|
||||
`mosaic proxy unit restart`. Before the fetch, the proxy fails to start with
|
||||
@@ -162,11 +162,14 @@ state offers its next step as one button. CLI parity:
|
||||
mosaic proxy unit render|status|install|start|stop|restart
|
||||
mosaic proxy fence clear --restart --business ID
|
||||
mosaic proxy init-lock status|clear
|
||||
mosaic proxy undo
|
||||
mosaic proxy ride --instance NAME | ride --off (CLI only; no Console control)
|
||||
|
||||
- Fetch runs the same PIN and hash checks as `mosaic proxy fetch`; the page
|
||||
shows each step as it runs.
|
||||
- Init asks the bus to generate the management key (`proxy.init` with
|
||||
`generate: true`, 48 CSPRNG bytes). The key goes to the key file only; no
|
||||
- Init uses the instance-owner transport on the page, or the selected bus on the CLI,
|
||||
to generate the management key (`proxy.init` with `generate: true`, 48 CSPRNG bytes).
|
||||
The key goes to the key file only; no
|
||||
response, event or receipt carries it. A pasted key with its confirmation is
|
||||
accepted only when the page is on HTTPS or on loopback from a loopback
|
||||
peer; a plain-HTTP LAN page gets the generated key only
|
||||
@@ -183,7 +186,7 @@ state offers its next step as one button. CLI parity:
|
||||
yourself and use `fence clear --proxy-restarted`, which is unchanged.
|
||||
- `proxy-admin-busy` (one setup action at a time) is per process: the Console
|
||||
and a `mosaic proxy` command each hold their own. The writes that matter are
|
||||
still serialized across processes: init by the bus's init lock and
|
||||
still serialized across processes: init by the instance init lock and
|
||||
exclusive create, key writes by the instance-wide proxy lock, and unit
|
||||
actions by systemd.
|
||||
- The page and `status --json` carry the last ten receipts from
|
||||
@@ -196,3 +199,42 @@ state offers its next step as one button. CLI parity:
|
||||
per instance (ruling 8, deferred).
|
||||
|
||||
Receipts: `<dataRoot>/state/proxy-admin.jsonl` (labels, pids and port only).
|
||||
|
||||
### Model setup before an organization exists
|
||||
|
||||
The instance owner can fetch, initialize and start the service, connect accounts and see
|
||||
models at Settings > Model setup before creating any organization. The instance transport
|
||||
reuses the human ancestry verifier, initialization, account controller, write fence and
|
||||
provider catalogue. The private child proves its direct parent is this checkout's Console
|
||||
with the same instance config directory and checks human ancestry before admitting work.
|
||||
Resume only releases the removal hold, so it still completes when a new ancestry check would fail.
|
||||
Organization account routes and single-business Console routes retain their existing bus.
|
||||
|
||||
If setup stops, the page names the step and its reason. Try again reads current state and
|
||||
starts at the unfinished step. A service file on disk and systemd's loaded state are reported
|
||||
separately. A file the user manager cannot find often means the Console has a different HOME.
|
||||
The rendered file always carries an absolute MOSAIC_CONFIG; the displayed unit shortens HOME.
|
||||
|
||||
`mosaic proxy undo`, or **Remove unfinished setup** on Model setup, removes only an unfinished
|
||||
setup. The owner-only write is `POST /api/proxy/admin/undo` with `{}`. It removes
|
||||
only an inactive known Mosaic unit for this instance, then removes unfinished proxy state, proxy.json
|
||||
and the management key. The pinned download, config.json and append-only history stay.
|
||||
A running service, recorded successful start, connected account, riding organization,
|
||||
riding instance, non-sentinel client key, pending sign-in, held init lock, unknown file, foreign unit or drop-in prevents removal.
|
||||
Undo holds the existing init lock during removal to exclude another initialization. The new refusal
|
||||
codes are `proxy-setup-in-use` and `proxy-setup-remove-refused`. Retry and undo never widen
|
||||
who can manage an account.
|
||||
|
||||
The Lead approved a plain `message` field on every Model setup admin route error, including
|
||||
install, start and undo. This field explains the refusal in plain words and carries no absolute
|
||||
path, code-only text, key or token. A unit file under the home directory is named in its short
|
||||
`~/` form. It is an approved response field alongside the undo success message;
|
||||
it adds no route, verb, refusal code, grant or role.
|
||||
|
||||
Install checks drop-ins beside the unit file. It does not discover every system-wide or
|
||||
user.control override; an administrator must check those before changing an installation.
|
||||
A stopped-step reason is retained in the Console process only. After a Console restart,
|
||||
Continue setup still reads disk and service state and starts from the unfinished step.
|
||||
An owner IPC timeout reports an unknown outcome without stopping the child or its locked
|
||||
write. New owner calls refuse busy until the operation settles; retry reads current state.
|
||||
Disconnect closes admission and lets accepted work finish before the child exits.
|
||||
@@ -1,11 +1,13 @@
|
||||
// #1873 proxy setup controller shared by the Console page (webui proxy-admin.mjs) and
|
||||
// `mosaic proxy status|unit|init-lock|fence clear --restart`. Host actions run here; init and
|
||||
// the fence clear go to the bus, which decides them. Results and receipts carry labels, key IDs
|
||||
// and process ids only: never a key, token, absolute path or upstream text.
|
||||
// the fence clear use the owner transport or selected bus. Receipts carry labels, key IDs
|
||||
// and process ids only: never a key, token or upstream text. A unit refusal can name its file.
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { fetchPinned } from './fetch.mjs';
|
||||
import { PIN } from './common.mjs';
|
||||
import { readRide, RIDE_NAME } from './settings.mjs';
|
||||
import { PIN, sha256 } from './common.mjs';
|
||||
import { localRide, riddenOrgs } from './ride.mjs';
|
||||
import { releaseState, initState, fenceState, initLockStatus, clearInitLock, appendReceipt, recentReceipts, receiptsText, createUnitControl, FILE_LABELS, LOG_LINES, receiptHistory, serviceKeyState } from './admin.mjs';
|
||||
import { secretValues } from './redact.mjs';
|
||||
@@ -76,7 +78,7 @@ const isoTime = value => (typeof value === 'string' && /^[0-9]{4}-[0-9]{2}-[0-9]
|
||||
// #1873 ride-default: `riders()` lists the owner's active organizations for Ride all, read locally:
|
||||
// [{id, fixture, cliproxy, changes, call, status}] where `changes` is the text of the organization's
|
||||
// change log, `call(verb, args)` reaches its bus as the owner and `status()` is its bus status. `ownerModels()` answers
|
||||
// {proxy, riding, models} from the riding buses' catalogues. `move(id, models, principal)` moves a
|
||||
// {proxy, riding, models, catalogue?} from the instance owner catalogue or riding buses. `move(id, models, principal)` moves a
|
||||
// stopped fixture organization to the owner's models through the organization service.
|
||||
// #1873 settings-backend A2: a rider may also have `file()`, its organization file as the writer
|
||||
// reads it ({document, revision}), read only. `harnesses()` lists the installed harness programs.
|
||||
@@ -85,13 +87,13 @@ const isoTime = value => (typeof value === 'string' && /^[0-9]{4}-[0-9]{2}-[0-9]
|
||||
// worker-model-setup: `workerModel()`, when given, answers the Worker model card's view
|
||||
// (webui/src/worker-model-view.mjs); status() carries it as `worker`, or null when it throws.
|
||||
// status({ worker: false }) leaves it out and does not call it (the Triage snapshot).
|
||||
export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir = null, unit = null, fetch = fetchPinned, buses, orgs = async () => [], riders = async () => [], harnesses = () => installedHarnesses(dataRoot), rootAgents = null, ownerModels = async () => ({ proxy: false, riding: false, models: [] }), move = null, now = () => new Date(), env = process.env, pin = PIN, providers = PROVIDERS, workerModel = null }) {
|
||||
export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir = null, unit = null, fetch = fetchPinned, buses, orgs = async () => [], riders = async () => [], harnesses = () => installedHarnesses(dataRoot), rootAgents = null, ownerModels = async () => ({ proxy: false, riding: false, models: [] }), move = null, now = () => new Date(), env = process.env, pin = PIN, providers = PROVIDERS, workerModel = null, ownerProxy = null }) {
|
||||
const port = () => { try { return initState(configDir, dataRoot).settings?.port ?? null; } catch { return null; } };
|
||||
const control = unit ?? createUnitControl({ instance, unitDir, port, env });
|
||||
let job = { state: 'idle', step: null, receipt: null, error: null };
|
||||
// The last confirmed restart this page made. One fence clear may use it.
|
||||
let restarted = null;
|
||||
let busy = null;
|
||||
let busy = null, stoppedSetup = null;
|
||||
const receipt = record => appendReceipt(dataRoot, { time: now().toISOString(), ...record });
|
||||
const fetchRecord = () => ({ op: 'fetch', version: pin.version, panelVersion: pin.panel.version, archiveSha256: pin.archive.sha256, panelSha256: pin.panel.sha256, binarySha256: pin.binary.sha256, verified: true });
|
||||
async function exclusive(name, action) {
|
||||
@@ -252,8 +254,23 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
|
||||
}
|
||||
return {
|
||||
// #1873 models-offered (A9): models() and modelsSet(), the owner's per-provider on/off lists.
|
||||
...offeredControl({ dataRoot, riders, receipt, exclusive, rootAgents }),
|
||||
...offeredControl({ dataRoot, riders, receipt, exclusive, rootAgents, ownerCatalogue: ownerProxy ? () => ownerProxy.catalogue() : null }),
|
||||
unit: control.unit,
|
||||
// The last local failure is memory only. Reading readiness never loads history or repairs setup.
|
||||
get stoppedSetup() { return stoppedSetup ? { ...stoppedSetup } : null; },
|
||||
...(ownerProxy ? { async setupAccounts(principal) {
|
||||
try {
|
||||
const [accounts, catalogue] = await Promise.all([
|
||||
ownerProxy.call('proxy.accounts', {}, principal), ownerProxy.catalogue(),
|
||||
]);
|
||||
return { accounts: accounts.accounts, catalogue };
|
||||
} catch (error) {
|
||||
if (error?.code !== 'not-configured') throw error;
|
||||
// Before service setup there are no accounts to connect or catalogue to inspect yet.
|
||||
return { accounts: [], catalogue: null };
|
||||
}
|
||||
} } : {}),
|
||||
...(ownerProxy ? { ownerCall: (verb, args, principal) => ownerProxy.call(verb, args, principal) } : {}),
|
||||
async status({ worker: withWorker = true } = {}) {
|
||||
// The Worker model view asks each organization's bus, so it starts first and runs alongside
|
||||
// the reads below; a throw reads as null.
|
||||
@@ -288,6 +305,7 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
|
||||
// #1873 settings-backend-a3: the page's provider select, from the plugin. Id, label and sign-in kind only.
|
||||
providers: publicProviders(providers),
|
||||
busy,
|
||||
stoppedSetup,
|
||||
receipts: recentReceipts(dataRoot),
|
||||
organizations,
|
||||
// Ruling 8: the system config holds one proxy per instance; an organization's own proxy
|
||||
@@ -341,12 +359,104 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
|
||||
restarted = evidence.confirmed ? evidence : null;
|
||||
return { state, evidence, receipt: receipt({ op: 'unit.restart', unit: control.unit, confirmed: evidence.confirmed, before: { pid: evidence.before.pid }, after: { pid: evidence.after.pid, listening: evidence.after.listening }, observedAt: evidence.observedAt }) };
|
||||
}
|
||||
const state = await control[op]();
|
||||
let state;
|
||||
try { state = await control[op](); stoppedSetup = null; }
|
||||
catch (error) {
|
||||
stoppedSetup = { at: `unit-${op}`, code: proxyCode(error, 'proxy-unit-failed'), ...(error.ownerMessage ? { reason: error.ownerMessage } : {}) };
|
||||
throw error;
|
||||
}
|
||||
// Any other unit action ends the restart this page confirmed.
|
||||
restarted = null;
|
||||
return { state, receipt: receipt({ op: `unit.${op}`, unit: control.unit, active: state.active, pid: state.pid ?? null, healthy: state.healthy === true }) };
|
||||
});
|
||||
},
|
||||
// Undo only an unfinished local setup. Unknown state, credentials, riders or any successful
|
||||
// service start refuse before a unit or file is touched. The pinned download and history stay.
|
||||
async undo() {
|
||||
return exclusive('undo', () => (ownerProxy?.withRemoval ? action => ownerProxy.withRemoval(action) : action => action())(async () => {
|
||||
const state = await control.status();
|
||||
const history = receiptsText(dataRoot);
|
||||
if (history === null) throw failure('proxy-setup-remove-refused');
|
||||
let entries;
|
||||
try { entries = history.split('\n').filter(Boolean).map(JSON.parse); } catch { throw failure('proxy-setup-remove-refused'); }
|
||||
const lastUndo = entries.findLastIndex(r => r.op === 'setup.undo');
|
||||
if (state.healthy || state.active === 'active' || entries.slice(lastUndo + 1).some(r => /^unit\.(start|restart)$/.test(r.op) && (r.healthy === true || r.confirmed === true))) throw failure('proxy-setup-in-use');
|
||||
if (!['inactive', 'failed'].includes(state.active)) throw failure('proxy-setup-remove-refused');
|
||||
const list = await riders();
|
||||
if (!Array.isArray(list) || list.some(r => typeof r.cliproxy !== 'boolean')) throw failure('proxy-setup-remove-refused');
|
||||
if (list.some(r => r.cliproxy)) throw failure('proxy-setup-in-use');
|
||||
// Instance rides are named under the same user's canonical config home. Never read keys.
|
||||
const configHome = path.join(homedir(), '.config');
|
||||
const ownerName = instance ?? (path.basename(configDir).startsWith('mosaic-') ? path.basename(configDir).slice(7) : null);
|
||||
if (ownerName) {
|
||||
let actual, named;
|
||||
try { actual = fs.realpathSync(configDir); named = fs.realpathSync(path.join(configHome, `mosaic-${ownerName}`)); }
|
||||
catch { throw failure('proxy-setup-remove-refused'); }
|
||||
if (actual !== named) throw failure('proxy-setup-remove-refused');
|
||||
let names; try { names = fs.readdirSync(configHome); } catch { throw failure('proxy-setup-remove-refused'); }
|
||||
for (const name of names) {
|
||||
if (!name.startsWith('mosaic-') || !RIDE_NAME.test(name.slice(7)) || name === `mosaic-${ownerName}`) continue;
|
||||
try { if (readRide(path.join(configHome, name))?.instance === ownerName) throw failure('proxy-setup-in-use'); }
|
||||
catch (error) { throw failure(error.code === 'proxy-setup-in-use' ? error.code : 'proxy-setup-remove-refused'); }
|
||||
}
|
||||
}
|
||||
const files = { settings: path.join(configDir, 'proxy.json'), key: path.join(configDir, 'secrets', 'proxy-management.key'), lock: path.join(configDir, '.proxy-init.lock'), proxy: path.join(dataRoot, 'proxy') };
|
||||
const snapshots = new Map();
|
||||
const inspect = file => {
|
||||
let st; try { st = fs.lstatSync(file); } catch (e) { if (e.code === 'ENOENT') return null; throw failure('proxy-setup-remove-refused'); }
|
||||
if (st.isSymbolicLink() || st.uid !== process.getuid() || (st.mode & 0o022) || fs.realpathSync(file) !== path.resolve(file) || (!st.isFile() && !st.isDirectory()) || (st.isFile() && st.nlink !== 1)) throw failure('proxy-setup-remove-refused');
|
||||
snapshots.set(file, st); return st;
|
||||
};
|
||||
for (const file of Object.values(files)) inspect(file);
|
||||
// An init lock cannot prove its holder is gone. Keep it for the existing stale-lock flow.
|
||||
if (snapshots.has(files.lock)) throw failure('proxy-setup-remove-refused');
|
||||
if (snapshots.has(files.proxy)) {
|
||||
const allowed = new Set(['config.yaml', 'auth', 'logs', 'mosaic-proxy.identity']);
|
||||
for (const name of fs.readdirSync(files.proxy)) {
|
||||
if (!allowed.has(name)) throw failure('proxy-setup-remove-refused');
|
||||
const file = path.join(files.proxy, name), st = inspect(file);
|
||||
if (name === 'auth') { if (!st.isDirectory() || fs.readdirSync(file).length) throw failure('proxy-setup-in-use'); }
|
||||
else if (name === 'config.yaml') {
|
||||
if (!st.isFile()) throw failure('proxy-setup-remove-refused');
|
||||
let cfg; try { cfg = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { throw failure('proxy-setup-remove-refused'); }
|
||||
const access = cfg.access;
|
||||
if (access !== undefined) {
|
||||
const sentinel = new RegExp(`^msk-${sha256(configDir).slice(0, 12)}-sentinel-[A-Za-z0-9_-]{43}$`);
|
||||
if (!access || typeof access !== 'object' || Array.isArray(access) || Object.keys(access).some(k => k !== 'api-keys')
|
||||
|| !Array.isArray(access['api-keys']) || access['api-keys'].length > 1 || access['api-keys'].some(k => typeof k !== 'string' || !sentinel.test(k))) throw failure('proxy-setup-in-use');
|
||||
}
|
||||
if (Object.keys(cfg).some(k => !['config-version', 'server', 'management', 'access', 'oauth', 'observability', 'routing'].includes(k))) throw failure('proxy-setup-in-use');
|
||||
} else if (name === 'logs') {
|
||||
if (!st.isDirectory()) throw failure('proxy-setup-remove-refused');
|
||||
for (const log of fs.readdirSync(file)) if (!inspect(path.join(file, log))?.isFile()) throw failure('proxy-setup-remove-refused');
|
||||
} else if (!st.isFile()) throw failure('proxy-setup-remove-refused');
|
||||
}
|
||||
}
|
||||
// Recheck every identity after preflight, before performing the removal.
|
||||
for (const [file, before] of snapshots) {
|
||||
const after = fs.lstatSync(file);
|
||||
if (after.dev !== before.dev || after.ino !== before.ino || after.mtimeMs !== before.mtimeMs) throw failure('proxy-setup-remove-refused');
|
||||
}
|
||||
// Hold init's existing exclusive lock across the asynchronous unit removal, so another
|
||||
// Console or CLI cannot initialize new state while this operation removes old state.
|
||||
let guard;
|
||||
try { guard = fs.openSync(files.lock, 'wx', 0o600); } catch { throw failure('proxy-setup-remove-refused'); }
|
||||
const identity = fs.fstatSync(guard);
|
||||
try {
|
||||
// With no settings yet there can be no proxy unit that this setup installed.
|
||||
if (snapshots.has(files.settings)) await control.remove();
|
||||
else if (state.installed) throw failure('proxy-setup-remove-refused');
|
||||
for (const key of ['settings', 'key']) if (snapshots.has(files[key])) fs.unlinkSync(files[key]);
|
||||
if (snapshots.has(files.proxy)) fs.rmSync(files.proxy, { recursive: true });
|
||||
stoppedSetup = null; restarted = null;
|
||||
return { removed: true, message: 'Unfinished setup removed. You can set it up again.', receipt: receipt({ op: 'setup.undo' }) };
|
||||
} finally {
|
||||
fs.closeSync(guard);
|
||||
const after = fs.lstatSync(files.lock);
|
||||
if (after.ino === identity.ino && after.dev === identity.dev) fs.unlinkSync(files.lock);
|
||||
}
|
||||
}));
|
||||
},
|
||||
// Only after this page restarted the proxy and saw the new process. The bus re-proves it.
|
||||
async fenceClear(call) {
|
||||
return exclusive('fence-clear', async () => {
|
||||
@@ -393,7 +503,7 @@ export function createProxyAdmin({ dataRoot, configDir, instance = null, unitDir
|
||||
if (typeof move !== 'function') return { org, moved: false, reason: 'not-available' };
|
||||
const owner = await ownerModels();
|
||||
if (owner?.proxy !== true) return { org, moved: false, reason: 'no-proxy' };
|
||||
if (owner.riding !== true) return { org, moved: false, reason: 'no-riding-bus' };
|
||||
if (owner.riding !== true && owner.catalogue !== 'ready') return { org, moved: false, reason: 'no-riding-bus' };
|
||||
let result;
|
||||
try { result = await move(org, owner.models, principal); }
|
||||
catch (error) { result = { moved: false, reason: failCode(error) }; }
|
||||
|
||||
@@ -7,6 +7,7 @@ import path from 'node:path';
|
||||
import net from 'node:net';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { ownedUnit, checkDropins } from './unit-file.mjs';
|
||||
import { PIN, refuse } from './common.mjs';
|
||||
import { installPaths, loadProxy, verifyInstall } from './settings.mjs';
|
||||
import { holdsSecret, redactLine, redactValue } from './redact.mjs';
|
||||
@@ -277,9 +278,9 @@ export function unitName(instance) {
|
||||
return instance && instance !== 'dev' ? `mosaic-proxy-${instance}.service` : 'mosaic-proxy.service';
|
||||
}
|
||||
|
||||
export function defaultRun(command, args, { env, timeout = 60000 } = {}) {
|
||||
export function defaultRun(command, args, { env, timeout = 60000, signal } = {}) {
|
||||
return new Promise(resolve => {
|
||||
execFile(command, args, { env, timeout, maxBuffer: 1024 * 1024, killSignal: 'SIGKILL' }, (error, stdout, stderr) => {
|
||||
execFile(command, args, { env, timeout, signal, maxBuffer: 1024 * 1024, killSignal: 'SIGKILL' }, (error, stdout, stderr) => {
|
||||
resolve({ code: error ? (typeof error.code === 'number' ? error.code : 1) : 0, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') });
|
||||
});
|
||||
});
|
||||
@@ -305,11 +306,22 @@ export function createUnitControl({ instance = null, port = () => null, unitDir
|
||||
const unit = unitName(instance);
|
||||
if (unitDir !== null && (typeof unitDir !== 'string' || !path.isAbsolute(unitDir))) refuse('proxy-unit-path');
|
||||
const script = path.join(repo, 'scripts', 'proxy-service.sh');
|
||||
const unitFile = path.join(unitDir ?? path.join(env.XDG_CONFIG_HOME ?? path.join(env.HOME ?? '', '.config'), 'systemd', 'user'), unit);
|
||||
if (!path.isAbsolute(unitFile)) refuse('proxy-unit-path');
|
||||
const home = env.HOME;
|
||||
const displayUnit = home && path.isAbsolute(home) && unitFile.startsWith(home + path.sep) ? '~/' + path.relative(home, unitFile) : `${unit} in your user systemd folder`;
|
||||
const foreignMessage = () => `The service file ${displayUnit} differs from the file this setup would install. Nothing was replaced or removed. If it is an unused Mosaic setup, remove unfinished setup below. Otherwise ask its installer to move it aside, then try again.`;
|
||||
const requireOwned = expected => {
|
||||
try { return ownedUnit(unitFile, expected); }
|
||||
catch (error) { if (error.code === 'proxy-unit-exists') error.ownerMessage = foreignMessage(); throw error; }
|
||||
};
|
||||
const missingMessage = () => `The service file is at ${displayUnit}, but the user service manager cannot find it. This can happen when the Console uses a different home directory. Remove this unfinished setup below, then open the Console under your usual home and set it up again.`;
|
||||
const instanceArgs = instance && instance !== 'dev' ? ['--instance', instance] : [];
|
||||
async function service(op) {
|
||||
const result = await run('bash', [script, ...instanceArgs, op, ...(unitDir && op === 'install' ? ['--dir', unitDir] : [])], { env });
|
||||
if (result.code === 0) return result;
|
||||
const code = /^proxy-service: (proxy-[a-z-]+)$/m.exec(result.stderr)?.[1];
|
||||
if (code === 'proxy-unit-exists') throw Object.assign(new Error(code), { code, ownerMessage: foreignMessage() });
|
||||
refuse(UNIT_CODES.includes(code) ? code : 'proxy-unit-failed');
|
||||
}
|
||||
async function status() {
|
||||
@@ -322,7 +334,9 @@ export function createUnitControl({ instance = null, port = () => null, unitDir
|
||||
const listening = fields.ActiveState === 'active' && Number.isInteger(p) ? await probe(p) : false;
|
||||
return {
|
||||
unit,
|
||||
installed: fields.LoadState === 'loaded',
|
||||
installed: present(unitFile) || fields.LoadState === 'loaded',
|
||||
filePresent: present(unitFile),
|
||||
...(present(unitFile) && fields.LoadState !== 'loaded' ? { problem: missingMessage() } : {}),
|
||||
load: fields.LoadState ?? 'unknown', active: fields.ActiveState ?? 'unknown', sub: fields.SubState ?? 'unknown',
|
||||
pid, since, restarts: /^[0-9]+$/.test(fields.NRestarts ?? '') ? Number(fields.NRestarts) : null,
|
||||
port: Number.isInteger(p) ? p : null, listening,
|
||||
@@ -342,6 +356,10 @@ export function createUnitControl({ instance = null, port = () => null, unitDir
|
||||
const result = await run('systemctl', ['--user', verb, unit], { env, timeout: 90000 });
|
||||
if (result.code !== 0) refuse('proxy-unit-failed');
|
||||
}
|
||||
function requireInactive(state) {
|
||||
if (['active', 'activating'].includes(state.active) || state.healthy) refuse('proxy-setup-in-use');
|
||||
if (!['inactive', 'failed'].includes(state.active)) refuse('proxy-setup-remove-refused');
|
||||
}
|
||||
return {
|
||||
unit,
|
||||
status,
|
||||
@@ -349,9 +367,32 @@ export function createUnitControl({ instance = null, port = () => null, unitDir
|
||||
log(lines, { secrets = [] } = {}) { return unitLog({ run, unit, lines, env, secrets }); },
|
||||
async render() { return (await service('render')).stdout; },
|
||||
async install() { await service('install'); return status(); },
|
||||
async remove() {
|
||||
checkDropins(unitFile);
|
||||
const state = await status();
|
||||
if (!present(unitFile) && !state.installed) return;
|
||||
requireInactive(state);
|
||||
const expected = (await service('render')).stdout;
|
||||
const before = requireOwned(expected);
|
||||
if (!before && state.installed) throw Object.assign(new Error('proxy-unit-exists'), { code: 'proxy-unit-exists', ownerMessage: foreignMessage() });
|
||||
if (before) {
|
||||
// A different Console or CLI may have started it during the ownership preflight.
|
||||
requireInactive(await status());
|
||||
// Keep the final file identity check and unlink synchronous after the status await.
|
||||
const again = requireOwned(expected);
|
||||
if (!again || again.ino !== before.ino || again.dev !== before.dev || again.text !== before.text) refuse('proxy-unit-exists');
|
||||
fs.unlinkSync(unitFile);
|
||||
const r = await run('systemctl', ['--user', 'daemon-reload'], { env, timeout: 15000 });
|
||||
if (r.code !== 0) refuse('proxy-unit-failed');
|
||||
// A start during reload must leave the setup state in place for the running service.
|
||||
requireInactive(await status());
|
||||
}
|
||||
},
|
||||
async start() {
|
||||
const before = await status();
|
||||
if (!before.installed) refuse('proxy-unit-missing');
|
||||
if (before.filePresent) { checkDropins(unitFile); requireOwned((await service('render')).stdout); }
|
||||
if (before.filePresent && before.load !== 'loaded') throw Object.assign(new Error('proxy-unit-missing'), { code: 'proxy-unit-missing', ownerMessage: missingMessage() });
|
||||
await systemctl('start');
|
||||
const after = await waitFor(s => s.healthy);
|
||||
if (!after.healthy) refuse('proxy-unit-unhealthy');
|
||||
@@ -360,6 +401,8 @@ export function createUnitControl({ instance = null, port = () => null, unitDir
|
||||
async stop() {
|
||||
const before = await status();
|
||||
if (!before.installed) refuse('proxy-unit-missing');
|
||||
if (before.filePresent) { checkDropins(unitFile); requireOwned((await service('render')).stdout); }
|
||||
if (before.filePresent && before.load !== 'loaded') throw Object.assign(new Error('proxy-unit-missing'), { code: 'proxy-unit-missing', ownerMessage: missingMessage() });
|
||||
await systemctl('stop');
|
||||
return waitFor(s => s.active === 'inactive' || s.active === 'failed');
|
||||
},
|
||||
@@ -368,6 +411,8 @@ export function createUnitControl({ instance = null, port = () => null, unitDir
|
||||
async restart() {
|
||||
const before = await status();
|
||||
if (!before.installed) refuse('proxy-unit-missing');
|
||||
if (before.filePresent) { checkDropins(unitFile); requireOwned((await service('render')).stdout); }
|
||||
if (before.filePresent && before.load !== 'loaded') throw Object.assign(new Error('proxy-unit-missing'), { code: 'proxy-unit-missing', ownerMessage: missingMessage() });
|
||||
await systemctl('restart');
|
||||
const changed = s => s.healthy && s.pid !== null && s.pid !== before.pid && s.since !== null && (before.since === null || s.since > before.since);
|
||||
const after = await waitFor(changed);
|
||||
|
||||
@@ -138,7 +138,7 @@ export function rootModelsNamed(root, orgId) {
|
||||
return modelsNamed({ agents: taken, definitions: root.definitions ?? {} });
|
||||
}
|
||||
|
||||
export function offeredControl({ dataRoot, riders, receipt, exclusive, rootAgents = null, uid = process.getuid() }) {
|
||||
export function offeredControl({ dataRoot, riders, receipt, exclusive, rootAgents = null, ownerCatalogue = null, uid = process.getuid() }) {
|
||||
const readFile = () => {
|
||||
const file = readOffered(dataRoot, { uid });
|
||||
if (file.state === 'damaged') throw failure('outcome-unknown');
|
||||
@@ -158,7 +158,7 @@ export function offeredControl({ dataRoot, riders, receipt, exclusive, rootAgent
|
||||
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);
|
||||
const unanswered = new Set(named.filter(r => typeof r.cliproxy !== 'boolean').map(r => r.id));
|
||||
if (!riding.length) throw failure(unanswered.size ? 'proxy-down' : 'not-configured');
|
||||
if (!riding.length && !ownerCatalogue) throw failure(unanswered.size ? 'proxy-down' : 'not-configured');
|
||||
let root;
|
||||
try { root = typeof rootAgents === 'function' ? await rootAgents() : undefined; } catch { root = undefined; }
|
||||
const answers = await Promise.all(riding.map(async r => {
|
||||
@@ -173,6 +173,17 @@ export function offeredControl({ dataRoot, riders, receipt, exclusive, rootAgent
|
||||
}));
|
||||
const providers = new Map(), usedBy = new Map();
|
||||
let ready = false;
|
||||
if (ownerCatalogue) {
|
||||
const c = await ownerCatalogue();
|
||||
if (c?.status !== 'ready' || !Array.isArray(c.models)) throw failure('proxy-down');
|
||||
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);
|
||||
}
|
||||
}
|
||||
for (const { id, routes, noLaunch } of answers) {
|
||||
// routes explicitly refuses before reading a catalogue when the organization has no launch.
|
||||
if (noLaunch) continue;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// Private transport to the bus-side owner process. No management client or key enters the Console.
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { fork } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
const runtime = fileURLToPath(new URL('../../bus/src/proxy-owner.mjs', import.meta.url));
|
||||
const failure = code => Object.assign(new Error(code), { code });
|
||||
export function createOwnerProxy({ configDir, dataRoot, forkProcess = fork, timeoutMs = 30000 }) {
|
||||
let child = null, sequence = 0;
|
||||
const pending = new Map();
|
||||
function disconnect() {
|
||||
child = null;
|
||||
for (const { reject, timer } of pending.values()) { clearTimeout(timer); reject(failure('outcome-unknown')); }
|
||||
pending.clear();
|
||||
}
|
||||
function start() {
|
||||
if (child) return;
|
||||
const launched = forkProcess(runtime, ['--owner-ipc', configDir, dataRoot], { stdio: ['ignore', 'ignore', 'ignore', 'ipc'], execArgv: [], env: { ...process.env, MOSAIC_BUS_CLI_NONCE: randomBytes(32).toString('hex') } });
|
||||
child = launched;
|
||||
child.on('message', message => {
|
||||
const item = pending.get(message?.id); if (!item) return;
|
||||
pending.delete(message.id); clearTimeout(item.timer);
|
||||
if (!pending.size) { child?.unref(); child?.channel?.unref(); }
|
||||
message.error ? item.reject(failure(message.error)) : item.resolve(message.result);
|
||||
});
|
||||
const ended = () => { if (child === launched) disconnect(); };
|
||||
child.once('exit', ended); child.once('error', ended);
|
||||
child.unref(); child.channel?.unref();
|
||||
}
|
||||
function request(type, value = {}) {
|
||||
if ([...pending.values()].some(item => item.timedOut)) return Promise.reject(failure('proxy-admin-busy'));
|
||||
start(); const id = ++sequence;
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = ['pause', 'resume'].includes(type) ? null : setTimeout(() => {
|
||||
// Keep the same child and its locks alive. Late completion clears this uncertain request;
|
||||
// until then another request refuses busy and the page reads actual setup status.
|
||||
const item = pending.get(id);
|
||||
if (item) { item.timedOut = true; reject(failure('outcome-unknown')); }
|
||||
}, timeoutMs);
|
||||
pending.set(id, { resolve, reject, timer }); child.ref(); child.channel?.ref();
|
||||
child.send({ id, type, ...value }, error => { if (error) { if (child?.connected) child.disconnect(); disconnect(); } });
|
||||
});
|
||||
}
|
||||
return {
|
||||
call: (verb, args, principal) => request('call', { verb, args, principal }),
|
||||
catalogue: () => request('catalogue'),
|
||||
reset: () => request('reset'),
|
||||
async withRemoval(action) {
|
||||
await request('pause');
|
||||
try { return await action(); } finally { await request('resume'); }
|
||||
},
|
||||
close() { if (child?.connected) child.disconnect(); },
|
||||
};
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
// Console wiring (webui cli.mjs) reads each organization and its bus, and admin-control runs them.
|
||||
import { usableModel } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
|
||||
export { usableModel };
|
||||
export { usableModel, ownerModelsAvailable } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
const has = (list, name) => Array.isArray(list) && list.includes(name);
|
||||
|
||||
// The model providers one change-log change shows before and after, by the change's path: the
|
||||
@@ -98,12 +98,41 @@ export function readRider({ id, read, readLog, isFixture }) {
|
||||
cliproxy: ok ? (Array.isArray(doc.plugins?.['model-provider']) ? doc.plugins['model-provider'] : []).includes('cliproxy') : undefined, changes };
|
||||
}
|
||||
|
||||
// The owner's models: `proxy` is true when the instance's proxy.json names a port. Each organization
|
||||
// that lists cliproxy is asked for its routes at once, so a hung bus costs one timeout, not one each.
|
||||
// It rides when its bus answers a ready catalogue; the models are the cliproxy rows those
|
||||
// catalogues list, once each.
|
||||
export async function ownerModelsFrom({ proxy, riders }) {
|
||||
// Only organization mode uses the owner transport. Single-business and SSO Consoles keep
|
||||
// reading their riding buses. The CLI and HTTP fixtures share this admission choice.
|
||||
export function ownerModelsReader({ proxy, organizations, ownerProxy, rideRiders, timeoutMs }) {
|
||||
return async () => {
|
||||
let configured = false;
|
||||
try { configured = proxy() === true; } catch {}
|
||||
return ownerModelsFrom({ proxy: configured,
|
||||
riders: configured && !organizations ? await rideRiders() : [],
|
||||
...(organizations ? { ownerCatalogue: () => ownerProxy.catalogue() } : {}),
|
||||
...(timeoutMs === undefined ? {} : { timeoutMs }),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
// The instance owner catalogue is authoritative when supplied: it works before the first
|
||||
// organization and reads the same offered-model rule as the Models page. Never merge it with
|
||||
// stale bus rows or fall back after a refused read. Other callers keep their riding-bus truth.
|
||||
// `catalogue` is read evidence, not persisted state; `riding` still describes a bus catalogue.
|
||||
export async function ownerModelsFrom({ proxy, riders, ownerCatalogue = null, timeoutMs = 5000 }) {
|
||||
if (proxy !== true) return { proxy: false, riding: false, models: [] };
|
||||
if (typeof ownerCatalogue === 'function') {
|
||||
// The bound stops waiting; it does not cancel the owner read.
|
||||
let timer;
|
||||
try {
|
||||
const catalogue = await Promise.race([
|
||||
Promise.resolve().then(ownerCatalogue),
|
||||
new Promise(resolve => { timer = setTimeout(() => resolve(null), timeoutMs); }),
|
||||
]);
|
||||
if (catalogue?.status === 'ready' && Array.isArray(catalogue.models)) return {
|
||||
proxy: true, riding: false, catalogue: 'ready', models: catalogue.models.filter(m => m?.module === 'cliproxy'),
|
||||
};
|
||||
} catch { /* A failed read carries no upstream text and grants no bus fallback. */ }
|
||||
finally { clearTimeout(timer); }
|
||||
return { proxy: true, riding: false, catalogue: 'unavailable', models: [] };
|
||||
}
|
||||
const catalogues = await Promise.all((Array.isArray(riders) ? riders : []).filter(r => r?.cliproxy === true)
|
||||
.map(async r => { try { return (await r.call('routes'))?.catalogue; } catch { return null; } }));
|
||||
const models = new Map(); let riding = false;
|
||||
|
||||
@@ -8,6 +8,8 @@ try {
|
||||
const result = spawnSync(process.execPath, [path.join(repo, 'scripts/mosaic-config.mjs'), 'validate'], { encoding: 'utf8', env: process.env });
|
||||
if (result.status !== 0) throw Error('proxy-config-invalid');
|
||||
const config = JSON.parse(result.stdout);
|
||||
// proxy-ride: a riding instance runs no proxy of its own; the owner's unit serves it.
|
||||
if (config.proxy?.owner) delete config.proxy;
|
||||
const child = startVerifiedProxy(config, {
|
||||
onError: code => { process.stderr.write(code + '\n'); process.exitCode = 3; },
|
||||
onExit: code => { process.exitCode = code; },
|
||||
|
||||
@@ -34,6 +34,59 @@ export function loadProxy(configDir, dataRoot) {
|
||||
refuse('proxy-config-invalid');
|
||||
}
|
||||
}
|
||||
// proxy-ride first slice (Jason 2026-11-21): <configDir>/proxy-ride.json names another instance
|
||||
// of the same OS user whose model proxy this instance's worker runs use. It names an instance,
|
||||
// never a path. scripts/mosaic-config.mjs resolves the name the way --instance does.
|
||||
export const RIDE_FILE = 'proxy-ride.json';
|
||||
export const RIDE_NAME = /^[a-z][a-z0-9]{1,15}$/;
|
||||
// One owner line per refusal. packages/bus/src/refusals.mjs carries the same text.
|
||||
export const RIDE_LINES = Object.freeze({
|
||||
'proxy-ride-invalid': 'proxy-ride.json is not a valid ride file, or it names this instance. Run mosaic proxy ride --off, then mosaic proxy ride --instance NAME with the instance whose proxy this one should use.',
|
||||
'proxy-ride-owner-missing': 'The instance named in proxy-ride.json has no valid model proxy, or it rides another instance itself. Set up the proxy on that instance, or run mosaic proxy ride --off.',
|
||||
'proxy-ride-conflict': 'This instance has its own proxy.json and a proxy-ride.json. Run mosaic proxy ride --off to keep its own proxy.',
|
||||
});
|
||||
// undefined when the file is absent. Present beside proxy.json refuses proxy-ride-conflict, before
|
||||
// the file is read. Otherwise it must be a regular 0600 file of the running user holding exactly
|
||||
// {"version":1,"instance":NAME}; anything else refuses proxy-ride-invalid.
|
||||
export function readRide(configDir) {
|
||||
const file = path.join(configDir, RIDE_FILE);
|
||||
let stat;
|
||||
try { stat = fs.lstatSync(file); } catch (e) { if (e.code === 'ENOENT') return undefined; refuse('proxy-ride-invalid'); }
|
||||
let own = true;
|
||||
try { fs.lstatSync(path.join(configDir, 'proxy.json')); } catch (e) { if (e.code === 'ENOENT') own = false; }
|
||||
if (own) refuse('proxy-ride-conflict');
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid() || (stat.mode & 0o777) !== 0o600 || stat.size > 4096) refuse('proxy-ride-invalid');
|
||||
let value;
|
||||
try { value = JSON.parse(regularBytes(file, 'proxy-ride-invalid')); } catch { refuse('proxy-ride-invalid'); }
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).sort().join(',') !== 'instance,version'
|
||||
|| value.version !== 1 || typeof value.instance !== 'string' || !RIDE_NAME.test(value.instance)) refuse('proxy-ride-invalid');
|
||||
return { instance: value.instance };
|
||||
}
|
||||
// The verb's write: exclusive creation, 0600, so an existing file is never rewritten. Returns a
|
||||
// function that removes the file only while it is still the one this call created.
|
||||
export function createRide(configDir, instance) {
|
||||
if (typeof instance !== 'string' || !RIDE_NAME.test(instance)) refuse('proxy-ride-invalid');
|
||||
safePath(configDir, 'proxy-ride-invalid');
|
||||
const file = path.join(configDir, RIDE_FILE);
|
||||
let fd;
|
||||
try { fd = fs.openSync(file, 'wx', 0o600); } catch { refuse('proxy-ride-invalid'); }
|
||||
try { fs.writeFileSync(fd, JSON.stringify({ version: 1, instance }) + '\n'); }
|
||||
finally { fs.closeSync(fd); }
|
||||
const { ino, dev } = fs.lstatSync(file);
|
||||
return () => {
|
||||
try { const now = fs.lstatSync(file); if (now.ino === ino && now.dev === dev) fs.unlinkSync(file); } catch { /* already gone */ }
|
||||
};
|
||||
}
|
||||
// The verb's --off: removes the ride file, never following a link. False when there was none.
|
||||
export function removeRide(configDir) {
|
||||
safePath(configDir, 'proxy-ride-invalid');
|
||||
const file = path.join(configDir, RIDE_FILE);
|
||||
let stat;
|
||||
try { stat = fs.lstatSync(file); } catch (e) { if (e.code === 'ENOENT') return false; refuse('proxy-ride-invalid'); }
|
||||
if (stat.isDirectory()) refuse('proxy-ride-invalid');
|
||||
fs.unlinkSync(file);
|
||||
return true;
|
||||
}
|
||||
export function verifyInstall(dataRoot, pin = PIN) {
|
||||
const paths = installPaths(dataRoot, pin);
|
||||
for (const [file, hash] of [[paths.binary, pin.binary.sha256], [paths.panel, pin.panel.sha256]]) {
|
||||
@@ -74,6 +127,8 @@ export async function initializeProxy({ configDir, dataRoot, key, port, pin = PI
|
||||
for (const file of [settingsFile, proxyDir, keyFile]) {
|
||||
try { fs.lstatSync(file); refuse('proxy-already-initialized'); } catch (e) { if (e.code !== 'ENOENT') throw e; }
|
||||
}
|
||||
// A riding instance uses another instance's proxy; its own init would make both files.
|
||||
try { fs.lstatSync(path.join(configDir, RIDE_FILE)); refuse('proxy-ride-conflict'); } catch (e) { if (e.code !== 'ENOENT') throw e; }
|
||||
const lockFile = path.join(configDir, '.proxy-init.lock');
|
||||
let lock;
|
||||
try { lock = fs.openSync(lockFile, 'wx', 0o600); } catch { refuse('proxy-init-busy'); }
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
// Readiness only. Never calls offeredControl.models(), which seeds the offered-model file.
|
||||
// The management client remains bus-only; account metadata comes from its existing owner read.
|
||||
import { releaseState, initState, fenceState, createUnitControl, defaultRun } from './admin.mjs';
|
||||
import { loadProxy } from './settings.mjs';
|
||||
import { offeredProvider, usesModelService } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
|
||||
export async function readService({ configDir, dataRoot, instance, unitDir = null, signal, run = defaultRun }) {
|
||||
const release = releaseState(dataRoot), init = initState(configDir, dataRoot);
|
||||
const fence = fenceState(dataRoot);
|
||||
// An untouched instance needs no systemd call. A partial install still reports a failure.
|
||||
if (!release.fetched && !init.initialized && !init.partial) return { release, init, unit: {}, fence: { set: !!fence } };
|
||||
const unit = await createUnitControl({ instance, unitDir,
|
||||
port: () => loadProxy(configDir, dataRoot)?.port ?? null,
|
||||
run: (command, args, options) => run(command, args, { ...options, timeout: 1000, signal }),
|
||||
}).status();
|
||||
return { release, init, unit, fence: { set: !!fence } };
|
||||
}
|
||||
|
||||
// Membership includes the admitted organization document. Unknown documents still need a
|
||||
// check; an invalid member or a failed membership read must never become a silent pass.
|
||||
function proxyMembers(ctx) {
|
||||
const members = ctx.members;
|
||||
if (members?.some(org => org.invalid)) throw Error('organization unavailable');
|
||||
return members?.filter(org => !org.doc || usesModelService(org.doc));
|
||||
}
|
||||
const notNeeded = members => ({ state: 'not-applicable', reason: members.length > 1 ? 'Your organizations answer without the model service.' : 'Your organization answers without the model service.' });
|
||||
|
||||
// The host can supply the instance account reader without requiring an organization.
|
||||
export async function accountState(ctx) {
|
||||
const members = proxyMembers(ctx);
|
||||
if (ctx.members.length && !members.length) return notNeeded(ctx.members);
|
||||
const read = !ctx.members.length && ctx.accounts ? [ctx.accounts] : members.map(org => async () => {
|
||||
const routes = await ctx.read(org, 'routes');
|
||||
if (['unavailable', 'disabled'].includes(routes?.catalogue?.status)) return { catalogue: routes.catalogue };
|
||||
const accounts = await ctx.read(org, 'accounts');
|
||||
return { ...accounts, catalogue: routes?.catalogue };
|
||||
});
|
||||
if (!read.length) return { state: 'next', reason: 'Connect an account in Model setup so your agents can answer.' };
|
||||
const answers = await Promise.allSettled(read.map(async reader => {
|
||||
const a = await reader();
|
||||
if (['unavailable', 'disabled'].includes(a?.catalogue?.status))
|
||||
return { state: 'next', reason: 'Open Model setup to connect an account and load the models it offers.' };
|
||||
if (!Array.isArray(a?.accounts)) throw Error('accounts unavailable');
|
||||
const active = a.accounts.some(account => ['active', 'ready'].includes(account.status));
|
||||
if (!a.accounts.length) return { state: 'next', reason: 'Connect an account in Model setup so your agents can answer.' };
|
||||
if (!active) return { state: 'failed', reason: 'Your connected accounts are not ready. Open Model setup to sign in or add an account.' };
|
||||
if (a.catalogue?.status !== 'ready' || !Array.isArray(a.catalogue.models)) throw Error('catalogue unavailable');
|
||||
if (a.catalogue.models.some(model => model.available === true && typeof model.upstream === 'string' && a.accounts.some(account =>
|
||||
['active', 'ready'].includes(account.status) && typeof account.provider === 'string' && account.provider === offeredProvider(model.upstream)))) return { state: 'done', reason: 'An account is connected and offers a model.' };
|
||||
return { state: 'next', reason: 'The account is connected but has no model available. Choose a model in Model setup.' };
|
||||
}));
|
||||
const found = answers.filter(a => a.status === 'fulfilled').map(a => a.value);
|
||||
return found.find(a => a.state === 'done') ?? found.find(a => a.state === 'failed') ?? found[0] ?? Promise.reject(Error('account read unavailable'));
|
||||
}
|
||||
|
||||
export const setupState = Object.freeze([
|
||||
{
|
||||
id: 'model-service.running', title: 'Start the model service',
|
||||
purpose: "The program on this computer that carries your agents' questions to the models you connect.",
|
||||
fix: { page: '#/settings/model-setup', step: 1, label: 'Set up model service' }, order: { after: [] }, required: true,
|
||||
async check(ctx) {
|
||||
const members = proxyMembers(ctx);
|
||||
if (ctx.members?.length && !members.length) return notNeeded(ctx.members);
|
||||
const s = await ctx.service();
|
||||
if (!s || !s.release || !s.init || !s.unit) throw Error('service state unavailable');
|
||||
if (!s.release.fetched && s.release.problem && s.release.problem !== 'proxy-install-missing') throw Error('release state unavailable');
|
||||
if (s.release.verified && s.init.initialized && s.unit.active === 'active' && s.unit.healthy === true && s.unit.listening === true && !s.fence?.set)
|
||||
return { state: 'done', reason: 'The model service is running and answers on this computer.' };
|
||||
if (s.stoppedSetup) return { state: 'failed', reason: 'Setup stopped. Open Model setup to see why and try again.', fix: { page: '#/settings/model-setup', step: 1, label: 'Try again' } };
|
||||
if (s.release.fetched || s.release.verified || s.init.initialized || s.init.partial || s.unit.active === 'failed' || s.fence?.set)
|
||||
return { state: 'failed', reason: 'The model service is not ready. Open Model setup to check it and continue.' };
|
||||
return { state: 'next', reason: "Mosaic downloads the model service, checks the download and starts it on this computer. You don't need an account for this step." };
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'model-account.connected', title: 'Connect a model account',
|
||||
purpose: "Sign in to an account or add a model key in Model setup. This account pays for your agents' answers.",
|
||||
fix: { page: '#/settings/model-setup', step: 2, label: 'Connect an account' },
|
||||
order: { after: ['model-service.running'] }, required: true, check: accountState,
|
||||
},
|
||||
]);
|
||||
@@ -0,0 +1,47 @@
|
||||
// A complete known template and the exact instance config identify a Mosaic unit. A comment
|
||||
// alone is never ownership. Older checkouts/node paths are accepted only in the two fixed fields.
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { refuse } from './common.mjs';
|
||||
export function sameInstanceUnit(text, expected) {
|
||||
const normalize = value => {
|
||||
const root = /^WorkingDirectory=(\/[A-Za-z0-9/._+:-]+)$/m.exec(value)?.[1];
|
||||
const start = /^ExecStart=(\/[A-Za-z0-9/._+:-]+) (\/[A-Za-z0-9/._+:-]+)\/packages\/model-proxy\/src\/run.mjs$/m.exec(value);
|
||||
if (!root || !start || start[2] !== root) return null;
|
||||
return value.replace(`WorkingDirectory=${root}\n`, 'WorkingDirectory=@ROOT@\n')
|
||||
.replace(start[0], 'ExecStart=@NODE@ @ROOT@/packages/model-proxy/src/run.mjs');
|
||||
};
|
||||
const a = normalize(text), b = normalize(expected);
|
||||
return a !== null && b !== null && a === b;
|
||||
}
|
||||
export function ownedUnit(file, expected) {
|
||||
let fd;
|
||||
try { fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK); }
|
||||
catch (e) { if (e.code === 'ENOENT') return null; refuse('proxy-unit-exists'); }
|
||||
try {
|
||||
const st = fs.fstatSync(fd);
|
||||
if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o022) || st.nlink !== 1 || st.size > 16384) refuse('proxy-unit-exists');
|
||||
const text = fs.readFileSync(fd, 'utf8');
|
||||
if (!sameInstanceUnit(text, expected)) refuse('proxy-unit-exists');
|
||||
return { dev: st.dev, ino: st.ino, text };
|
||||
} finally { fs.closeSync(fd); }
|
||||
}
|
||||
export function checkDropins(file) {
|
||||
for (const name of [path.basename(file) + '.d', 'mosaic-proxy-.service.d', 'mosaic-.service.d', 'service.d']) {
|
||||
try { fs.lstatSync(path.join(path.dirname(file), name)); } catch (e) { if (e.code === 'ENOENT') continue; }
|
||||
refuse('proxy-unit-dropin');
|
||||
}
|
||||
}
|
||||
export function installUnit(file, text) {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
checkDropins(file);
|
||||
const before = ownedUnit(file, text);
|
||||
if (!before) { fs.writeFileSync(file, text, { flag: 'wx', mode: 0o644 }); return; }
|
||||
// An existing file is never rewritten, including its inode, timestamps and running target.
|
||||
if (before.text !== text) refuse('proxy-unit-exists');
|
||||
}
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
try { installUnit(process.argv[2], fs.readFileSync(0, 'utf8')); }
|
||||
catch (e) { process.stderr.write(`proxy-service: ${['proxy-unit-exists', 'proxy-unit-dropin'].includes(e.code) ? e.code : 'proxy-unit-exists'}\n`); process.exitCode = 3; }
|
||||
}
|
||||
@@ -34,7 +34,7 @@ function fixture(t, { unitState = { installed: false, active: 'inactive', health
|
||||
restart: async () => { ops.push('restart'); return restart ?? { state: unitState, evidence: { unit: 'mosaic-proxy-zz.service', confirmed: true, before: { pid: 10, since: 1, active: 'active' }, after: { pid: 11, since: 2, active: 'active', listening: true }, observedAt: new Date(0).toISOString() } }; },
|
||||
};
|
||||
const admin = createProxyAdmin({ dataRoot, configDir, unit, buses: stopped, fetch: fetch ?? (async () => ({})), now: () => new Date(0), orgs: async () => [{ id: 'acme', catalogue: 'ready' }], pin, ...extra });
|
||||
return { root, configDir, dataRoot, admin, ops, files: initFiles(configDir, dataRoot) };
|
||||
return { root, configDir, dataRoot, unit, admin, ops, files: initFiles(configDir, dataRoot) };
|
||||
}
|
||||
const receipts = dataRoot => { try { return fs.readFileSync(receiptFile(dataRoot), 'utf8').trim().split('\n').filter(Boolean).map(JSON.parse); } catch { return []; } };
|
||||
|
||||
@@ -244,7 +244,7 @@ function a1Fixture(t, { unitState = { installed: true, active: 'active', healthy
|
||||
...(log === undefined ? { log: async (lines, options) => { calls.push({ lines, options }); return { unit: 'mosaic-proxy-zz.service', lines: ['ok'], redacted: 0, dropped: 0 }; } } : log === null ? {} : { log }),
|
||||
};
|
||||
const admin = createProxyAdmin({ dataRoot, configDir, unit, buses: stopped, now: () => new Date(0), env });
|
||||
return { admin, calls, configDir, dataRoot };
|
||||
return { unit, admin, calls, configDir, dataRoot };
|
||||
}
|
||||
|
||||
test('log reads the unit journal with the env secrets; a missing unit or log reader is not-configured, an unreadable state outcome-unknown', async t => {
|
||||
@@ -661,3 +661,90 @@ test('the worker view starts before the ride read and runs alongside it, so a sl
|
||||
assert.equal(order[0], 'worker-start');
|
||||
assert.ok(order.indexOf('riders') < order.indexOf('worker-end'), order.join(' '));
|
||||
});
|
||||
|
||||
test('undo removes only unfinished state and keeps release and history', async t => {
|
||||
const f = fixture(t); const files = initFiles(f.configDir, f.dataRoot);
|
||||
fs.mkdirSync(files.proxyDir); fs.mkdirSync(join(files.proxyDir, 'auth')); fs.mkdirSync(join(files.proxyDir, 'logs'));
|
||||
fs.writeFileSync(join(files.proxyDir, 'config.yaml'), '{}', { mode: 0o600 });
|
||||
fs.mkdirSync(join(f.configDir, 'secrets')); fs.writeFileSync(files.key, 'dummy', { mode: 0o600 });
|
||||
fs.writeFileSync(files.settings, '{}', { mode: 0o600 });
|
||||
f.unit.remove = async () => { f.ops.push('remove'); };
|
||||
const result = await f.admin.undo();
|
||||
assert.equal(result.removed, true); assert.deepEqual(f.ops, ['remove']);
|
||||
for (const name of ['settings', 'key', 'proxyDir']) assert.equal(fs.existsSync(files[name]), false);
|
||||
assert.equal(fs.existsSync(receiptFile(f.dataRoot)), true);
|
||||
});
|
||||
|
||||
test('undo refuses a running service, connected accounts and riding organizations', async t => {
|
||||
const active = fixture(t, { unitState: { installed: true, active: 'active', healthy: true } });
|
||||
await assert.rejects(active.admin.undo(), code('proxy-setup-in-use'));
|
||||
const account = fixture(t); const dir = join(account.dataRoot,'proxy','auth');fs.mkdirSync(dir,{recursive:true});fs.writeFileSync(join(dir,'account.json'),'{}');
|
||||
await assert.rejects(account.admin.undo(), code('proxy-setup-in-use'));
|
||||
const riding = fixture(t, { extra: { riders: async () => [{ id: 'team', cliproxy: true, fixture: false }] } });
|
||||
await assert.rejects(riding.admin.undo(), code('proxy-setup-in-use'));
|
||||
});
|
||||
|
||||
test('undo refuses unsafe files and a previously successful service even after it stops', async t => {
|
||||
const finished=fixture(t);fs.mkdirSync(join(finished.dataRoot,'state'));fs.writeFileSync(receiptFile(finished.dataRoot),JSON.stringify({op:'unit.start',healthy:true})+'\n',{mode:0o600});
|
||||
await assert.rejects(finished.admin.undo(),code('proxy-setup-in-use'));
|
||||
const unavailable=fixture(t,{unitState:{installed:true,active:'unknown'}});
|
||||
await assert.rejects(unavailable.admin.undo(),code('proxy-setup-remove-refused'));
|
||||
const unknown=fixture(t);fs.mkdirSync(unknown.files.proxyDir);fs.writeFileSync(join(unknown.files.proxyDir,'foreign'),'keep');
|
||||
await assert.rejects(unknown.admin.undo(),code('proxy-setup-remove-refused'));
|
||||
assert.equal(fs.readFileSync(join(unknown.files.proxyDir,'foreign'),'utf8'),'keep');
|
||||
});
|
||||
|
||||
|
||||
test('undo keeps an existing init lock and holds that lock during unit removal', async t => {
|
||||
const locked=fixture(t); fs.writeFileSync(join(locked.configDir,'.proxy-init.lock'),'');
|
||||
await assert.rejects(locked.admin.undo(),code('proxy-setup-remove-refused'));
|
||||
assert.equal(fs.existsSync(join(locked.configDir,'.proxy-init.lock')),true);
|
||||
const f=fixture(t); fs.writeFileSync(f.files.settings,'{}',{mode:0o600});
|
||||
f.unit.remove=async()=>{
|
||||
assert.equal(fs.existsSync(join(f.configDir,'.proxy-init.lock')),true);
|
||||
assert.throws(()=>fs.writeFileSync(join(f.configDir,'.proxy-init.lock'),'',{flag:'wx'}),{code:'EEXIST'});
|
||||
};
|
||||
await f.admin.undo();
|
||||
assert.equal(fs.existsSync(join(f.configDir,'.proxy-init.lock')),false);
|
||||
});
|
||||
|
||||
test('undo refuses access keys handed to riders', async t => {
|
||||
const f=fixture(t);fs.mkdirSync(f.files.proxyDir);fs.writeFileSync(join(f.files.proxyDir,'config.yaml'),JSON.stringify({access:{'api-keys':['rider-client-key']}}));
|
||||
await assert.rejects(f.admin.undo(),code('proxy-setup-in-use'));assert.equal(fs.existsSync(f.files.proxyDir),true);
|
||||
});
|
||||
test('undo refuses another instance riding this owner',async t=>{
|
||||
const f=fixture(t),owner=join(f.root,'.config','mosaic-owner'),other=join(f.root,'.config','mosaic-rider');
|
||||
fs.mkdirSync(owner,{recursive:true});fs.mkdirSync(other);
|
||||
fs.writeFileSync(join(other,'proxy-ride.json'),JSON.stringify({version:1,instance:'owner'}),{mode:0o600});
|
||||
const home=process.env.HOME;t.after(()=>{process.env.HOME=home;});process.env.HOME=f.root;
|
||||
const admin=createProxyAdmin({dataRoot:f.dataRoot,configDir:owner,instance:'owner',env:{HOME:f.root},unit:f.unit,buses:stopped});
|
||||
await assert.rejects(admin.undo(),code('proxy-setup-in-use'));assert.equal(fs.existsSync(join(other,'proxy-ride.json')),true);
|
||||
});
|
||||
|
||||
test('undo finds a riding instance through a symlinked owner config directory', async t => {
|
||||
const f = fixture(t), configHome = join(f.root, '.config'), owner = join(configHome, 'mosaic-owner'), other = join(configHome, 'mosaic-rider');
|
||||
fs.mkdirSync(owner, { recursive: true }); fs.mkdirSync(other);
|
||||
fs.mkdirSync(f.files.proxyDir); fs.writeFileSync(join(f.files.proxyDir, 'config.yaml'), '{}', { mode: 0o600 });
|
||||
fs.writeFileSync(join(other, 'proxy-ride.json'), JSON.stringify({ version: 1, instance: 'owner' }), { mode: 0o600 });
|
||||
const alias = join(f.root, 'alias'); fs.symlinkSync(configHome, alias);
|
||||
const home = process.env.HOME; t.after(() => { process.env.HOME = home; }); process.env.HOME = f.root;
|
||||
// Riders use the OS user's home, even if a controller was given another HOME.
|
||||
const admin = createProxyAdmin({ dataRoot: f.dataRoot, configDir: join(alias, 'mosaic-owner', '..', 'mosaic-owner'), instance: 'owner', env: { HOME: join(f.root, 'decoy') }, unit: f.unit, buses: stopped });
|
||||
await assert.rejects(admin.undo(), code('proxy-setup-in-use'));
|
||||
assert.equal(fs.existsSync(join(f.files.proxyDir, 'config.yaml')), true);
|
||||
assert.deepEqual(f.ops, []);
|
||||
});
|
||||
|
||||
for (const kind of ['missing', 'different']) test(`undo refuses a named owner whose canonical config is ${kind}`, async t => {
|
||||
const f = fixture(t), canonical = join(f.root, '.config', 'mosaic-owner');
|
||||
if (kind === 'different') fs.mkdirSync(canonical, { recursive: true });
|
||||
const home = process.env.HOME; t.after(() => { process.env.HOME = home; }); process.env.HOME = f.root;
|
||||
const admin = createProxyAdmin({ dataRoot: f.dataRoot, configDir: f.configDir, instance: 'owner', unit: f.unit, buses: stopped });
|
||||
await assert.rejects(admin.undo(), code('proxy-setup-remove-refused'));
|
||||
assert.deepEqual(f.ops, []);
|
||||
});
|
||||
test('undo before a first receipt is allowed and explains what was removed', async t => {
|
||||
const f=fixture(t);fs.mkdirSync(f.files.proxyDir);fs.writeFileSync(join(f.files.proxyDir,'config.yaml'),'{}');
|
||||
const result=await f.admin.undo();assert.equal(result.removed,true);assert.match(result.message,/Unfinished setup removed/);
|
||||
assert.doesNotMatch(result.message,/\/|proxy-setup-|msk-/);
|
||||
});
|
||||
@@ -1,11 +1,12 @@
|
||||
// The real config loader and unit renderers with made-up HOME/config/data only.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, statSync, existsSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { createUnitControl } from '../src/admin.mjs';
|
||||
import { installPaths } from '../src/settings.mjs';
|
||||
const repo=fileURLToPath(new URL('../../../',import.meta.url));
|
||||
function fixture(name='dev'){const root=mkdtempSync(join(tmpdir(),'p1-unit-')),configDir=join(root,'.config',`mosaic-${name}`),dataRoot=join(root,'data');mkdirSync(configDir,{recursive:true});mkdirSync(dataRoot);const file=join(configDir,'config.json');writeFileSync(file,JSON.stringify({configVersion:1,environment:'development',dataRoot,execution:{backend:'docker',provider:'fixture',model:'fixture'}}));if(name!=='dev')writeFileSync(join(dataRoot,'instance.json'),JSON.stringify({instanceVersion:1,name}));const env={PATH:process.env.PATH,HOME:root,MOSAIC_CONFIG:file};return {root,configDir,dataRoot,file,env};}
|
||||
@@ -18,9 +19,121 @@ test('proxy-not-configured: runner and unit render refuse absent sidecar',()=>{c
|
||||
test('proxy-install-invalid: unit runner refuses tampered executable before spawning',()=>{const f=fixture(),p=installPaths(f.dataRoot);mkdirSync(dirname(p.binary),{recursive:true});writeFileSync(p.binary,'#!/bin/sh\ntouch '+join(f.root,'executed')+'\n',{mode:0o755});proxy(f);const r=run(f,'packages/model-proxy/src/run.mjs');assert.equal(r.status,3);assert.match(r.stderr,/proxy-install-invalid/);assert.equal(existsSync(join(f.root,'executed')),false);});
|
||||
for(const [label,args,prep]of [['proxy-unit-usage',['bad'],()=>{}],['proxy-unit-exists',['install','--no-reload'],(f,dir)=>{mkdirSync(dir);writeFileSync(join(dir,'mosaic-proxy.service'),'old');}],['proxy-unit-dropin',['install','--no-reload'],(f,dir)=>{mkdirSync(join(dir,'service.d'),{recursive:true});}],['proxy-unit-path',['install','--no-reload','--dir','/invalid space'],()=>{}]])test(label,()=>{const f=fixture();proxy(f);const dir=join(f.root,'units');prep(f,dir);const r=run(f,'scripts/proxy-service.sh',[...args,...(label==='proxy-unit-path'?[]:['--dir',dir])]);assert.notEqual(r.status,0);assert.match(r.stderr,new RegExp(label));});
|
||||
test('proxy-config-invalid: instance selection also refuses invalid present sidecar',()=>{const f=fixture();writeFileSync(join(f.configDir,'proxy.json'),'{');const r=run(f,'scripts/mosaic-config.mjs',['instance']);assert.equal(r.status,2);assert.match(r.stderr,/proxy-config-invalid/);});
|
||||
test('explicit unit install writes only a scratch user unit and refuses a repeat',()=>{const f=fixture();proxy(f);const dir=join(f.root,'units');let r=run(f,'scripts/proxy-service.sh',['install','--dir',dir,'--no-reload']);assert.equal(r.status,0,r.stderr);const file=join(dir,'mosaic-proxy.service'),before=readFileSync(file);r=run(f,'scripts/proxy-service.sh',['install','--dir',dir,'--no-reload']);assert.equal(r.status,3);assert.match(r.stderr,/proxy-unit-exists/);assert.deepEqual(readFileSync(file),before);});
|
||||
test('identical unit installation is a no-op on retry',()=>{const f=fixture();proxy(f);const dir=join(f.root,'units');let r=run(f,'scripts/proxy-service.sh',['install','--dir',dir,'--no-reload']);assert.equal(r.status,0,r.stderr);const file=join(dir,'mosaic-proxy.service'),before=readFileSync(file),identity=statSync(file);r=run(f,'scripts/proxy-service.sh',['install','--dir',dir,'--no-reload']);assert.equal(r.status,0,r.stderr);assert.deepEqual(readFileSync(file),before);assert.equal(statSync(file).ino,identity.ino);assert.equal(statSync(file).mtimeMs,identity.mtimeMs);});
|
||||
test('proxy-unit-copy: renderer refuses an unknown or unpinned stack copy',()=>{const f=fixture();proxy(f);const r=run(f,'scripts/proxy-service.sh',['render','--copy','a'.repeat(40),'--copies',join(f.root,'missing-copies')]);assert.equal(r.status,3);assert.match(r.stderr,/proxy-unit-copy/);});
|
||||
test('historical no-proxy config loader works without new package dependency',()=>{const f=fixture();const copy=join(f.root,'historical/scripts');mkdirSync(copy,{recursive:true});writeFileSync(join(copy,'mosaic-config.mjs'),readFileSync(join(repo,'scripts/mosaic-config.mjs')));const r=spawnSync(process.execPath,[join(copy,'mosaic-config.mjs'),'validate'],{env:f.env,encoding:'utf8',timeout:10000});assert.equal(r.status,0,r.stderr);assert.equal(Object.hasOwn(JSON.parse(r.stdout),'proxy'),false);});
|
||||
function customConfig(f,file){const bytes=readFileSync(f.file);mkdirSync(dirname(file),{recursive:true});writeFileSync(file,bytes);f.file=file;f.configDir=dirname(file);f.env.MOSAIC_CONFIG=file;proxy(f);}
|
||||
test('configured default bus and proxy units bind the same explicit MOSAIC_CONFIG',()=>{const f=fixture();customConfig(f,join(f.root,'custom/config.json'));for(const script of ['scripts/bus-service.sh','scripts/proxy-service.sh']){const r=run(f,script,['render']);assert.equal(r.status,0,r.stderr);assert.ok(r.stdout.includes(`Environment=MOSAIC_CONFIG=${f.file}\n`),r.stdout);}});
|
||||
test('proxy-config-invalid: configured bus refuses a config path systemd cannot carry',()=>{const f=fixture();customConfig(f,join(f.root,'custom config/config.json'));const r=run(f,'scripts/bus-service.sh',['render']);assert.equal(r.status,1);assert.match(r.stderr,/proxy-config-invalid/);});
|
||||
|
||||
test('an edited unit and another instance unit are foreign and never replaced',()=>{
|
||||
for (const edit of [s=>s+'Environment=EXTRA=yes\n',s=>s.replace('Description=Mosaic model proxy [dev]','Description=Mosaic model proxy [other]')]) {
|
||||
const f=fixture();proxy(f);const dir=join(f.root,'units');
|
||||
assert.equal(run(f,'scripts/proxy-service.sh',['install','--dir',dir,'--no-reload']).status,0);
|
||||
const file=join(dir,'mosaic-proxy.service'), foreign=edit(readFileSync(file,'utf8'));writeFileSync(file,foreign);
|
||||
const r=run(f,'scripts/proxy-service.sh',['install','--dir',dir,'--no-reload']);
|
||||
assert.equal(r.status,3);assert.match(r.stderr,/proxy-unit-exists/);assert.equal(readFileSync(file,'utf8'),foreign);
|
||||
}
|
||||
});
|
||||
|
||||
test('disk installation, retry and undo stay honest when systemd cannot see scratch HOME',async()=>{
|
||||
const f=fixture('modelfirst'),dir=join(f.root,'units');proxy(f);
|
||||
const unitCalls=[];
|
||||
const control=createUnitControl({instance:'modelfirst',unitDir:dir,env:f.env,port:()=>18432,
|
||||
run:async(command,args)=>{
|
||||
if(command==='bash') {const r=spawnSync(command,[...args,...(args.includes('install')?['--no-reload']:[])],{env:f.env,encoding:'utf8'});return {code:r.status,stdout:r.stdout,stderr:r.stderr};}
|
||||
unitCalls.push(args);return {code:0,stdout:args.includes('show')?'LoadState=not-found\nActiveState=inactive\nMainPID=0\n':'',stderr:''};
|
||||
}});
|
||||
const state=await control.install();assert.equal(state.installed,true);assert.equal(state.filePresent,true);assert.equal(state.load,'not-found');
|
||||
assert.match(state.problem,/user service manager cannot find it/);assert.match(state.problem,/~\/units\//);assert.equal(JSON.stringify(state).includes(f.root),false);
|
||||
await assert.rejects(control.start(),e=>e.code==='proxy-unit-missing'&&e.ownerMessage.includes('~/units/mosaic-proxy-modelfirst.service') && !e.ownerMessage.includes(f.root));
|
||||
assert.equal((await control.install()).installed,true);
|
||||
const file=join(dir,'mosaic-proxy-modelfirst.service'),known=readFileSync(file,'utf8');
|
||||
writeFileSync(file,'foreign unit');
|
||||
await assert.rejects(control.remove(),e=>e.code==='proxy-unit-exists'&&e.ownerMessage.includes('~/units/mosaic-proxy-modelfirst.service') && !e.ownerMessage.includes(f.root)&&e.ownerMessage.includes('move it aside'));
|
||||
for(const op of ['start','stop','restart']) await assert.rejects(control[op](),e=>e.code==='proxy-unit-exists'&&e.ownerMessage.includes('~/units/mosaic-proxy-modelfirst.service') && !e.ownerMessage.includes(f.root));
|
||||
assert.equal(unitCalls.some(args=>args.some(a=>['start','stop','restart'].includes(a))),false);
|
||||
assert.equal(readFileSync(file,'utf8'),'foreign unit');writeFileSync(file,known);
|
||||
await control.remove();assert.equal(existsSync(file),false);
|
||||
});
|
||||
|
||||
|
||||
test('a previous checkout or another config is never replaced',()=>{
|
||||
const f=fixture();proxy(f);const dir=join(f.root,'units');
|
||||
assert.equal(run(f,'scripts/proxy-service.sh',['install','--dir',dir,'--no-reload']).status,0);
|
||||
const file=join(dir,'mosaic-proxy.service'), expected=readFileSync(file,'utf8');
|
||||
const previous=expected.replace(/^WorkingDirectory=.*$/m,'WorkingDirectory=/previous/checkout')
|
||||
.replace(/^ExecStart=.*$/m,'ExecStart=/previous/node /previous/checkout/packages/model-proxy/src/run.mjs');
|
||||
writeFileSync(file,previous);
|
||||
let r=run(f,'scripts/proxy-service.sh',['install','--dir',dir,'--no-reload']);
|
||||
assert.equal(r.status,3,r.stderr);assert.equal(readFileSync(file,'utf8'),previous);
|
||||
const foreign=expected.replace(`Environment=MOSAIC_CONFIG=${f.file}`,`Environment=MOSAIC_CONFIG=${f.root}/other/config.json`);
|
||||
writeFileSync(file,foreign);r=run(f,'scripts/proxy-service.sh',['install','--dir',dir,'--no-reload']);
|
||||
assert.equal(r.status,3);assert.match(r.stderr,/proxy-unit-exists/);assert.equal(readFileSync(file,'utf8'),foreign);
|
||||
});
|
||||
|
||||
test('active units cannot be changed or removed', async () => {
|
||||
const f=fixture();proxy(f);const dir=join(f.root,'units');
|
||||
assert.equal(run(f,'scripts/proxy-service.sh',['install','--dir',dir,'--no-reload']).status,0);
|
||||
const file=join(dir,'mosaic-proxy.service'),before=readFileSync(file,'utf8'),identity=statSync(file),calls=[];
|
||||
const control=createUnitControl({unitDir:dir,env:f.env,run:async(command,args)=>{
|
||||
if(command==='bash'){const r=spawnSync(command,[...args,...(args.includes('install')?['--no-reload']:[])],{env:f.env,encoding:'utf8'});return {code:r.status,stdout:r.stdout,stderr:r.stderr};}
|
||||
calls.push(args);return {code:0,stdout:args.includes('show')?'LoadState=loaded\nActiveState=active\nMainPID=42\n':'',stderr:''};
|
||||
}});
|
||||
await control.install();assert.equal(statSync(file).ino,identity.ino);assert.equal(statSync(file).mtimeMs,identity.mtimeMs);
|
||||
await assert.rejects(control.remove(),e=>e.code==='proxy-setup-in-use');
|
||||
assert.equal(readFileSync(file,'utf8'),before);assert.equal(calls.some(a=>a.includes('stop')),false);
|
||||
});
|
||||
|
||||
for (const active of ['active', 'activating']) test(`undo keeps a unit that becomes ${active} before deletion`, async () => {
|
||||
const f = fixture(); proxy(f); const dir = join(f.root, 'units');
|
||||
assert.equal(run(f, 'scripts/proxy-service.sh', ['install', '--dir', dir, '--no-reload']).status, 0);
|
||||
const file = join(dir, 'mosaic-proxy.service'), before = readFileSync(file, 'utf8');
|
||||
let started = false, checks = 0; const mutations = [];
|
||||
const control = createUnitControl({ unitDir: dir, env: f.env, run: async (command, args) => {
|
||||
if (command === 'bash') {
|
||||
const r = spawnSync(command, args, { env: f.env, encoding: 'utf8' });
|
||||
// Another caller starts the service after the initial status read.
|
||||
started = true;
|
||||
return { code: r.status, stdout: r.stdout, stderr: r.stderr };
|
||||
}
|
||||
if (!args.includes('show')) { mutations.push(args); return { code: 0, stdout: '', stderr: '' }; }
|
||||
checks++;
|
||||
return { code: 0, stdout: `LoadState=loaded\nActiveState=${started ? active : 'inactive'}\nMainPID=${started ? 42 : 0}\n`, stderr: '' };
|
||||
} });
|
||||
await assert.rejects(control.remove(), e => e.code === 'proxy-setup-in-use');
|
||||
assert.equal(checks, 2);
|
||||
assert.deepEqual(mutations, [], 'no stop or reload may run after the start');
|
||||
assert.equal(readFileSync(file, 'utf8'), before);
|
||||
});
|
||||
|
||||
test('undo detects a start during daemon reload before allowing setup state removal', async () => {
|
||||
const f = fixture(); proxy(f); const dir = join(f.root, 'units');
|
||||
assert.equal(run(f, 'scripts/proxy-service.sh', ['install', '--dir', dir, '--no-reload']).status, 0);
|
||||
let started = false;
|
||||
const control = createUnitControl({ unitDir: dir, env: f.env, run: async (command, args) => {
|
||||
if (command === 'bash') {
|
||||
const r = spawnSync(command, args, { env: f.env, encoding: 'utf8' });
|
||||
return { code: r.status, stdout: r.stdout, stderr: r.stderr };
|
||||
}
|
||||
if (args.includes('daemon-reload')) started = true;
|
||||
return { code: 0, stdout: args.includes('show') ? `LoadState=loaded\nActiveState=${started ? 'active' : 'inactive'}\nMainPID=${started ? 42 : 0}\n` : '', stderr: '' };
|
||||
} });
|
||||
await assert.rejects(control.remove(), e => e.code === 'proxy-setup-in-use');
|
||||
assert.equal(readFileSync(join(f.configDir, 'proxy.json'), 'utf8').length > 0, true);
|
||||
});
|
||||
test('unit state refuses a relative user configuration folder', () => {
|
||||
assert.throws(()=>createUnitControl({env:{PATH:process.env.PATH}}),e=>e.code==='proxy-unit-path');
|
||||
});
|
||||
|
||||
test('undo can remove an inactive known unit from a stale checkout',async()=>{
|
||||
const f=fixture();proxy(f);const dir=join(f.root,'units');
|
||||
assert.equal(run(f,'scripts/proxy-service.sh',['install','--dir',dir,'--no-reload']).status,0);
|
||||
const file=join(dir,'mosaic-proxy.service'),old=readFileSync(file,'utf8').replace(/^WorkingDirectory=.*$/m,'WorkingDirectory=/previous/checkout').replace(/^ExecStart=.*$/m,'ExecStart=/previous/node /previous/checkout/packages/model-proxy/src/run.mjs');
|
||||
writeFileSync(file,old);
|
||||
const control=createUnitControl({unitDir:dir,env:f.env,run:async(command,args)=>{
|
||||
if(command==='bash'){const r=spawnSync(command,args,{env:f.env,encoding:'utf8'});return {code:r.status,stdout:r.stdout,stderr:r.stderr};}
|
||||
return {code:0,stdout:args.includes('show')?'LoadState=loaded\nActiveState=inactive\nMainPID=0\n':'',stderr:''};
|
||||
}});
|
||||
await control.remove();assert.equal(existsSync(file),false);
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { createOwnerProxyRuntime as createOwnerProxy } from '../../bus/src/proxy-owner.mjs';
|
||||
import { initializeProxy, installPaths } from '../src/settings.mjs';
|
||||
import { createProxyAdmin } from '../src/admin-control.mjs';
|
||||
import { PIN } from '../src/common.mjs';
|
||||
const sha = value => createHash('sha256').update(value).digest('hex');
|
||||
const code = expected => error => error.code === expected;
|
||||
function fixture(t) {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'ow-')); t.after(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
const configDir = join(root, 'config'), dataRoot = join(root, 'data'); fs.mkdirSync(configDir); fs.mkdirSync(dataRoot);
|
||||
const pin = { ...PIN, binary: { sha256: sha('binary') }, panel: { ...PIN.panel, sha256: sha('panel') } };
|
||||
const paths = installPaths(dataRoot, pin); fs.mkdirSync(join(paths.dir, 'static'), { recursive: true });
|
||||
fs.writeFileSync(paths.binary, 'binary'); fs.writeFileSync(paths.panel, 'panel');
|
||||
let groups = [];
|
||||
const client = { getCredentials: async () => ({ files: [] }), getUpstreamGroups: async () => structuredClone(groups),
|
||||
putUpstreamGroups: async value => { groups = value.map((g, i) => ({ ...g, keys: g.keys.map((k, j) => ({ ...k, auth_index: `account-${i}-${j}` })) })); },
|
||||
getKeys: async () => [], oauthStart: async () => ({ state: 'state1', url: 'https://claude.ai/oauth/authorize?state=state1' }),
|
||||
oauthStatus: async () => ({ status: 'wait' }), oauthCancel: async () => ({ status: 'ok' }) };
|
||||
const owner = createOwnerProxy({ configDir, dataRoot, checkHuman: () => {}, init: args => initializeProxy({ ...args, pin }), load: async () => client });
|
||||
return { configDir, dataRoot, owner, pin, client };
|
||||
}
|
||||
test('the owner initializes, connects an account and sees its models without an organization', async t => {
|
||||
const f = fixture(t); const admin = createProxyAdmin({ ...f, ownerProxy: f.owner, unit: { unit: 'mosaic-proxy-test.service', status: async () => ({ installed: false, active: 'inactive' }) }, buses: async () => ({ stopped: true }), riders: async () => [] });
|
||||
const init = await admin.init(f.owner.call, { generate: true });
|
||||
assert.equal(init.receipt.generated, true); assert.equal(JSON.stringify(init).includes('secret-key'), false);
|
||||
assert.deepEqual((await f.owner.call('proxy.accounts')).accounts, []);
|
||||
await f.owner.call('proxy.apikey.add', { provider: 'z.ai', key: 'dummy-account-key' });
|
||||
const accounts = await f.owner.call('proxy.accounts'); assert.equal(accounts.accounts.length, 1);
|
||||
await f.owner.call('proxy.group.models.set', { accountId: accounts.accounts[0].accountId, models: ['glm-fixture'] });
|
||||
const view = await admin.models({ seed: true }); assert.equal(view.providers[0].provider, 'z.ai'); assert.equal(view.providers[0].models[0].id, 'glm-fixture');
|
||||
await assert.rejects(f.owner.call('plugins.set', {}), code('invalid-request'));
|
||||
});
|
||||
test('pending sign-in and an in-flight account request prevent removal', async t => {
|
||||
const f = fixture(t); await f.owner.call('proxy.init', { generate: true });
|
||||
let release; f.client.getCredentials = () => new Promise(resolve => { release = () => resolve({ files: [] }); });
|
||||
const read = f.owner.call('proxy.accounts'); while (!release) await new Promise(resolve => setImmediate(resolve));
|
||||
await assert.rejects(f.owner.withRemoval(async () => {}), code('proxy-admin-busy')); release(); await read;
|
||||
const principal = { provider: 'fixture', iss: 'fixture', sub: 'owner' };
|
||||
await f.owner.call('proxy.login.start', { provider: 'claude' }, principal);
|
||||
await assert.rejects(f.owner.withRemoval(async () => {}), code('proxy-admin-busy'));
|
||||
await assert.rejects(f.owner.call('proxy.login.status', { state: 'state1' }, { ...principal, sub: 'other-owner' }), code('login-state-unknown'));
|
||||
await f.owner.call('proxy.login.cancel', { state: 'state1' }, principal);
|
||||
await f.owner.withRemoval(async () => {});
|
||||
});
|
||||
test('the instance transport retains the human ancestry gate before reading config', () => {
|
||||
const source = `import { createOwnerProxy } from ${JSON.stringify(new URL('../src/owner-call.mjs', import.meta.url).href)}; try { await createOwnerProxy({ configDir: '/unread', dataRoot: '/unread' }).call('proxy.init', {generate:true}); process.exit(1); } catch(e) { process.exit(e.code==='human-required'?0:2); }`;
|
||||
const r = spawnSync(process.execPath, ['--input-type=module', '-e', source], { env: { ...process.env, MOSAIC_AGENT_RUN: 'owner-transport-test' }, encoding: 'utf8' });
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
});
|
||||
|
||||
test('catalogue and reset refuse during unfinished setup removal',async t=>{
|
||||
const f=fixture(t);await f.owner.call('proxy.init',{generate:true});
|
||||
let release;const removal=f.owner.withRemoval(()=>new Promise(resolve=>{release=resolve;}));
|
||||
while(!release)await new Promise(r=>setImmediate(r));
|
||||
await assert.rejects(f.owner.catalogue(),code('proxy-admin-busy'));
|
||||
assert.throws(()=>f.owner.reset(),code('proxy-admin-busy'));
|
||||
release();await removal;
|
||||
});
|
||||
|
||||
test('owner account and catalogue reads do not seed files before a later locked mutation', async t => {
|
||||
const f = fixture(t);
|
||||
await initializeProxy({ configDir: f.configDir, dataRoot: f.dataRoot, key: 'fixture-management-value', pin: f.pin });
|
||||
const snapshot = dir => fs.readdirSync(dir, { recursive: true }).sort().map(name => {
|
||||
const file = join(dir, name); return [name, fs.lstatSync(file).isDirectory() ? null : fs.readFileSync(file).toString('base64')];
|
||||
});
|
||||
const before = [snapshot(f.configDir), snapshot(f.dataRoot)];
|
||||
assert.deepEqual((await f.owner.call('proxy.accounts')).accounts, []);
|
||||
assert.equal((await f.owner.catalogue()).status, 'ready');
|
||||
assert.deepEqual([snapshot(f.configDir), snapshot(f.dataRoot)], before);
|
||||
await f.owner.call('proxy.apikey.add', { provider: 'z.ai', key: 'dummy-account-key' });
|
||||
assert.equal(fs.existsSync(join(f.dataRoot, 'proxy', 'mosaic-proxy.identity')), true);
|
||||
assert.equal((await f.owner.call('proxy.accounts')).accounts.length, 1);
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { fork } from 'node:child_process';
|
||||
import { EventEmitter, once } from 'node:events';
|
||||
import * as runtime from '../../bus/src/proxy-owner.mjs';
|
||||
import { createOwnerProxy } from '../src/owner-call.mjs';
|
||||
const code = name => error => error.code === name;
|
||||
const consolePath = new URL('../../webui/src/cli.mjs', import.meta.url).pathname;
|
||||
const ownerPath = new URL('../../bus/src/proxy-owner.mjs', import.meta.url).pathname;
|
||||
|
||||
test('resume releases a paused owner even when authorization would throw', async () => {
|
||||
const channel = new EventEmitter(); channel.connected = true;
|
||||
channel.send = message => channel.emit('reply', message);
|
||||
let allowed = true, checks = 0;
|
||||
const authorize = () => { checks++; if (!allowed) throw Object.assign(Error(), { code: 'human-required' }); };
|
||||
const owner = runtime.createOwnerProxyRuntime({ configDir: '/unread', dataRoot: '/unread', checkHuman: authorize });
|
||||
runtime.attachOwnerIPC(channel, owner, authorize);
|
||||
async function request(message) {
|
||||
const reply = once(channel, 'reply'); channel.emit('message', message); return (await reply)[0];
|
||||
}
|
||||
assert.deepEqual(await request({ id: 1, type: 'pause' }), { id: 1, result: true });
|
||||
assert.throws(() => owner.reset(), code('proxy-admin-busy'));
|
||||
allowed = false;
|
||||
try {
|
||||
assert.deepEqual(await request({ id: 2, type: 'resume' }), { id: 2, result: true });
|
||||
assert.equal(checks, 1, 'cleanup must not depend on a new authorization check');
|
||||
allowed = true;
|
||||
assert.deepEqual(await request({ id: 3, type: 'reset' }), { id: 3, result: true });
|
||||
allowed = false;
|
||||
assert.deepEqual(await request({ id: 4, type: 'pause' }), { id: 4, error: 'human-required' });
|
||||
} finally { channel.emit('disconnect'); }
|
||||
});
|
||||
function ancestry() {
|
||||
const env = { MOSAIC_BUS_CLI_NONCE: 'a'.repeat(64) };
|
||||
const rows = new Map([
|
||||
[30, { pid:30,ppid:20,startTime:'30',uid:process.getuid(),argv:[process.execPath,ownerPath,'--owner-ipc','/scratch/config','/scratch/data'],env }],
|
||||
[20, { pid:20,ppid:1,startTime:'20',uid:process.getuid(),argv:[process.execPath,consolePath,'serve'],env:{} }],
|
||||
]);
|
||||
return { rows, options: { pid:30,configDir:'/scratch/config',nonce:env.MOSAIC_BUS_CLI_NONCE,readProcess:id=>structuredClone(rows.get(id)),parentConfigDir:()=>'/scratch/config' } };
|
||||
}
|
||||
test('owner IPC proves its direct Console parent, instance and live ancestry', () => {
|
||||
const f=ancestry(); runtime.verifyOwnerConsole(f.options);
|
||||
f.rows.get(20).argv=[process.execPath,'/some/other.mjs','serve'];
|
||||
assert.throws(()=>runtime.verifyOwnerConsole(f.options),code('human-required'));
|
||||
const wrong=ancestry();wrong.options.parentConfigDir=()=>'/other/config';
|
||||
assert.throws(()=>runtime.verifyOwnerConsole(wrong.options),code('human-required'));
|
||||
const agent=ancestry();agent.options.launches=[{pid:20,startTime:'20'}];
|
||||
assert.throws(()=>runtime.verifyOwnerConsole(agent.options),code('human-required'));
|
||||
});
|
||||
function fixture(t) {
|
||||
const root=fs.mkdtempSync(join(tmpdir(),'ipc-'));t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
|
||||
const file=join(root,'child.mjs'),marker=join(root,'done');
|
||||
fs.writeFileSync(file,`import fs from 'node:fs';import { attachOwnerIPC } from ${JSON.stringify(new URL('../../bus/src/proxy-owner.mjs',import.meta.url).href)};
|
||||
let paused=false,active=false;
|
||||
const owner={async call(verb){if(paused||active)throw Object.assign(Error(),{code:'proxy-admin-busy'});active=true;try{if(verb==='slow'){await new Promise(r=>setTimeout(r,200));fs.writeFileSync(${JSON.stringify(marker)},'finished');}return {done:true};}finally{active=false;}},async catalogue(){if(paused)throw Object.assign(Error(),{code:'proxy-admin-busy'});return {models:[]};},reset(){},async withRemoval(action){if(paused||active)throw Object.assign(Error(),{code:'proxy-admin-busy'});paused=true;try{return await action();}finally{paused=false;}}};
|
||||
attachOwnerIPC(process,owner,()=>{});`);
|
||||
const children=[];
|
||||
const forkProcess=(_file,_args,options)=>{const child=fork(file,[],options);children.push(child);return child;};
|
||||
t.after(async()=>{for(const child of children){if(child.connected)child.disconnect();if(child.exitCode===null)await once(child,'exit');}});
|
||||
return {root,marker,children,forkProcess};
|
||||
}
|
||||
test('a real IPC fork finishes a write after its transport times out and blocks another write until it settles',async t=>{
|
||||
const f=fixture(t),owner=createOwnerProxy({configDir:f.root,dataRoot:f.root,forkProcess:f.forkProcess,timeoutMs:80});
|
||||
await assert.rejects(owner.call('slow',{}),code('outcome-unknown'));
|
||||
await assert.rejects(owner.call('another',{}),code('proxy-admin-busy'));
|
||||
for(let i=0;i<100&&!fs.existsSync(f.marker);i++)await new Promise(r=>setTimeout(r,10));
|
||||
assert.equal(fs.readFileSync(f.marker,'utf8'),'finished');
|
||||
let result; for(let i=0;i<100;i++){try{result=await owner.call('read',{});break;}catch(error){if(error.code!=='proxy-admin-busy')throw error;await new Promise(r=>setTimeout(r,10));}}
|
||||
assert.deepEqual(result,{done:true});owner.close();
|
||||
});
|
||||
test('a real IPC fork drains a write on disconnect instead of terminating it',async t=>{
|
||||
const f=fixture(t),child=f.forkProcess(null,null,{stdio:['ignore','ignore','pipe','ipc'],execArgv:[]});
|
||||
const exit=once(child,'exit');let errors='';child.stderr.on('data',d=>errors+=d);
|
||||
child.send({id:1,type:'call',verb:'slow',args:{}});
|
||||
await new Promise(r=>setTimeout(r,100));child.disconnect();await exit;
|
||||
assert.equal(fs.existsSync(f.marker),true,errors);
|
||||
});
|
||||
test('a non-Console process cannot drive the production IPC child without agent markers',async()=>{
|
||||
const child=fork(ownerPath,['--owner-ipc','/unread','/unread'],{stdio:['ignore','ignore','ignore','ipc'],execArgv:[],env:{PATH:process.env.PATH,HOME:process.env.HOME,MOSAIC_BUS_CLI_NONCE:'b'.repeat(64)}});
|
||||
const exit=once(child,'exit');
|
||||
child.send({id:1,type:'call',verb:'proxy.init',args:{generate:true},principal:{provider:'fake',iss:'fake',sub:'fake'}});
|
||||
const [reply]=await once(child,'message');assert.equal(reply.error,'human-required');child.disconnect();await exit;
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
// proxy-ride first slice (Jason 2026-11-21): the real config loader with two scratch instances of
|
||||
// one made-up HOME. The owner is named instance "owner" with its own proxy.json; the rider is the
|
||||
// default instance (or a second named one) with proxy-ride.json. Nothing reads a real config.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, realpathSync, rmSync, symlinkSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { installPaths, RIDE_LINES } from '../src/settings.mjs';
|
||||
|
||||
const repo = fileURLToPath(new URL('../../../', import.meta.url));
|
||||
const MANAGE = 'ride-config-management-key';
|
||||
function instance(home, name, dataRoot) {
|
||||
const configDir = join(home, '.config', `mosaic-${name}`), file = join(configDir, 'config.json');
|
||||
mkdirSync(configDir, { recursive: true, mode: 0o700 }); mkdirSync(dataRoot, { recursive: true });
|
||||
writeFileSync(file, JSON.stringify({ configVersion: 1, environment: 'development', dataRoot, execution: { backend: 'docker', provider: 'fixture', model: 'fixture' } }));
|
||||
if (name !== 'dev') writeFileSync(join(dataRoot, 'instance.json'), JSON.stringify({ instanceVersion: 1, name }));
|
||||
return { name, configDir, file, dataRoot };
|
||||
}
|
||||
function proxy(i, port = 18432) {
|
||||
const v = { port, binary: installPaths(i.dataRoot).binary };
|
||||
writeFileSync(join(i.configDir, 'proxy.json'), JSON.stringify(v));
|
||||
mkdirSync(join(i.configDir, 'secrets'), { mode: 0o700 });
|
||||
writeFileSync(join(i.configDir, 'secrets', 'proxy-management.key'), MANAGE, { mode: 0o600 });
|
||||
return v;
|
||||
}
|
||||
const ride = (i, name) => writeFileSync(join(i.configDir, 'proxy-ride.json'), JSON.stringify({ version: 1, instance: name }) + '\n', { mode: 0o600 });
|
||||
function fixture() {
|
||||
const home = realpathSync(mkdtempSync(join(tmpdir(), 'rc-')));
|
||||
const owner = instance(home, 'owner', join(home, 'od'));
|
||||
const rider = instance(home, 'dev', join(home, 'rd'));
|
||||
return { home, owner, rider, value: proxy(owner) };
|
||||
}
|
||||
function run(f, script, args = [], config = null) {
|
||||
const env = { PATH: process.env.PATH, HOME: f.home, ...(config ? { MOSAIC_CONFIG: config } : {}) };
|
||||
return spawnSync(script.endsWith('.mjs') ? process.execPath : 'bash', [join(repo, script), ...args], { env, encoding: 'utf8', timeout: 10000 });
|
||||
}
|
||||
const validate = (f, args = []) => run(f, 'scripts/mosaic-config.mjs', ['validate', ...args]);
|
||||
function refuses(f, r, code) {
|
||||
assert.equal(r.status, 2, r.stderr);
|
||||
assert.equal(r.stderr.trim().split('\n').at(-1), `mosaic-config: ${code}: ${RIDE_LINES[code]}`);
|
||||
assert.equal(r.stderr.includes(f.home), false, 'no path in the refusal');
|
||||
assert.equal(r.stdout, '');
|
||||
}
|
||||
|
||||
test('a rider resolves the owner proxy plus owner; its own data root and unit flag are unchanged', () => {
|
||||
const f = fixture(); ride(f.rider, 'owner');
|
||||
const before = readFileSync(f.rider.file);
|
||||
let r = validate(f);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
const out = JSON.parse(r.stdout);
|
||||
assert.equal(out.dataRoot, f.rider.dataRoot);
|
||||
assert.deepEqual(out.proxy, { ...f.value, owner: { instance: 'owner', configDir: f.owner.configDir, dataRoot: f.owner.dataRoot } });
|
||||
assert.equal(r.stdout.includes(MANAGE), false, 'the management key never enters the output');
|
||||
assert.deepEqual(readFileSync(f.rider.file), before);
|
||||
r = run(f, 'scripts/mosaic-config.mjs', ['instance']);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.doesNotMatch(r.stdout, /MOSAIC_INSTANCE_PROXY_CONFIGURED/);
|
||||
r = run(f, 'scripts/mosaic-config.mjs', ['instance', '--instance', 'owner']);
|
||||
assert.match(r.stdout, /MOSAIC_INSTANCE_PROXY_CONFIGURED=1/, 'the owner keeps its flag');
|
||||
r = run(f, 'scripts/bus-service.sh', ['render']);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.doesNotMatch(r.stdout, /Wants=mosaic-proxy/, "the rider's bus unit does not wait for a proxy unit");
|
||||
for (const [script, args] of [['scripts/proxy-service.sh', ['render']], ['packages/model-proxy/src/run.mjs', []]]) {
|
||||
r = run(f, script, args);
|
||||
assert.equal(r.status, 3, `${script}: ${r.stderr}`);
|
||||
assert.match(r.stderr, /proxy-not-configured/, 'a rider runs no proxy of its own');
|
||||
}
|
||||
});
|
||||
|
||||
test('a named instance rides the same way, selected with --instance', () => {
|
||||
const f = fixture(); const second = instance(f.home, 'second', join(f.home, 'sd')); ride(second, 'owner');
|
||||
const r = validate(f, ['--instance', 'second']);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.equal(JSON.parse(r.stdout).proxy.owner.instance, 'owner');
|
||||
});
|
||||
|
||||
test('proxy-ride-invalid: a ride file naming its own instance, by name or by its config directory', () => {
|
||||
let f = fixture(); ride(f.rider, 'dev'); refuses(f, validate(f), 'proxy-ride-invalid');
|
||||
f = fixture(); ride(f.owner, 'owner'); rmSync(join(f.owner.configDir, 'proxy.json'));
|
||||
refuses(f, validate(f, ['--instance', 'owner']), 'proxy-ride-invalid');
|
||||
// MOSAIC_CONFIG names the owner's file by another path: the same directory still refuses.
|
||||
f = fixture(); const alias = join(f.home, 'alias'); symlinkSync(f.rider.configDir, alias); ride(f.rider, 'dev');
|
||||
refuses(f, run(f, 'scripts/mosaic-config.mjs', ['validate'], join(alias, 'config.json')), 'proxy-ride-invalid');
|
||||
});
|
||||
|
||||
test('proxy-ride-invalid: an owner whose data root is the rider\'s', () => {
|
||||
const f = fixture(); const twin = instance(f.home, 'twin', f.rider.dataRoot); proxy(twin, 18433);
|
||||
ride(f.rider, 'twin');
|
||||
// validate checks no claim of the rider's own, so the shared root is what refuses.
|
||||
refuses(f, validate(f), 'proxy-ride-invalid');
|
||||
});
|
||||
|
||||
test('proxy-ride-invalid: a malformed ride file, or one naming a path', () => {
|
||||
for (const text of ['{', '{"version":1,"instance":"../mosaic-owner"}', '{"version":1,"instance":"owner","configDir":"/x"}']) {
|
||||
const f = fixture(); writeFileSync(join(f.rider.configDir, 'proxy-ride.json'), text, { mode: 0o600 });
|
||||
refuses(f, validate(f), 'proxy-ride-invalid');
|
||||
}
|
||||
});
|
||||
|
||||
test('proxy-ride-conflict: an instance with its own proxy.json and a ride file', () => {
|
||||
const f = fixture(); proxy(f.rider, 18440); ride(f.rider, 'owner');
|
||||
refuses(f, validate(f), 'proxy-ride-conflict');
|
||||
refuses(f, run(f, 'scripts/mosaic-config.mjs', ['instance']), 'proxy-ride-conflict');
|
||||
});
|
||||
|
||||
test('proxy-ride-owner-missing: no such instance, no proxy, a broken proxy, an unclaimed root, or a rider of a rider', () => {
|
||||
const cases = {
|
||||
absent: (f) => ride(f.rider, 'nobody'),
|
||||
noProxy: (f) => { rmSync(join(f.owner.configDir, 'proxy.json')); ride(f.rider, 'owner'); },
|
||||
badProxy: (f) => { writeFileSync(join(f.owner.configDir, 'proxy.json'), '{'); ride(f.rider, 'owner'); },
|
||||
badConfig: (f) => { writeFileSync(f.owner.file, '{'); ride(f.rider, 'owner'); },
|
||||
unclaimed: (f) => { rmSync(join(f.owner.dataRoot, 'instance.json')); ride(f.rider, 'owner'); },
|
||||
riderOfRider: (f) => {
|
||||
const middle = instance(f.home, 'middle', join(f.home, 'md')); ride(middle, 'owner'); ride(f.rider, 'middle');
|
||||
assert.equal(validate(f, ['--instance', 'middle']).status, 0, 'the middle instance itself rides');
|
||||
},
|
||||
};
|
||||
for (const [label, prep] of Object.entries(cases)) {
|
||||
const f = fixture(); prep(f);
|
||||
const r = validate(f);
|
||||
assert.equal(r.status, 2, `${label}: ${r.stderr}`);
|
||||
refuses(f, r, 'proxy-ride-owner-missing');
|
||||
}
|
||||
});
|
||||
|
||||
test('neither file still has no proxy; an instance with its own proxy.json is exactly as before', () => {
|
||||
const f = fixture();
|
||||
let r = validate(f);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.equal(Object.hasOwn(JSON.parse(r.stdout), 'proxy'), false);
|
||||
r = run(f, 'packages/model-proxy/src/run.mjs');
|
||||
assert.equal(r.status, 3); assert.match(r.stderr, /proxy-not-configured/);
|
||||
r = validate(f, ['--instance', 'owner']);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.deepEqual(JSON.parse(r.stdout).proxy, f.value);
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
// proxy-ride first slice (Jason 2026-11-21): <configDir>/proxy-ride.json, its strict reader, the
|
||||
// verb's exclusive write and --off removal, and proxy init refusing beside a ride file. Scratch
|
||||
// directories only.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, lstatSync, symlinkSync, chmodSync, existsSync, renameSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { RIDE_FILE, RIDE_LINES, readRide, createRide, removeRide, initializeProxy, installPaths } from '../src/settings.mjs';
|
||||
import { REFUSALS } from '../../bus/src/refusals.mjs';
|
||||
|
||||
const digest = (x) => createHash('sha256').update(x).digest('hex');
|
||||
const pin = { version: '8.0.42', binary: { sha256: digest('fake binary') }, panel: { sha256: digest('fake panel') } };
|
||||
const code = (c) => (e) => e.code === c;
|
||||
function dir() { const root = mkdtempSync(join(tmpdir(), 'rf-')); const configDir = join(root, 'config'), dataRoot = join(root, 'data'); mkdirSync(configDir, { mode: 0o700 }); mkdirSync(dataRoot); return { root, configDir, dataRoot, file: join(configDir, RIDE_FILE) }; }
|
||||
const put = (f, text, mode = 0o600) => { writeFileSync(f.file, text, { mode }); chmodSync(f.file, mode); };
|
||||
|
||||
test('readRide: absent is undefined; a strict file names its instance', () => {
|
||||
const f = dir();
|
||||
assert.equal(readRide(f.configDir), undefined);
|
||||
put(f, '{"version":1,"instance":"uiorg"}\n');
|
||||
assert.deepEqual(readRide(f.configDir), { instance: 'uiorg' });
|
||||
});
|
||||
|
||||
for (const [label, text] of Object.entries({
|
||||
malformed: '{', array: '[]', null: 'null', extra: '{"version":1,"instance":"uiorg","path":"/x"}',
|
||||
missing: '{"version":1}', version: '{"version":2,"instance":"uiorg"}', stringVersion: '{"version":"1","instance":"uiorg"}',
|
||||
path: '{"version":1,"instance":"../mosaic-uiorg"}', absolute: '{"version":1,"instance":"/home/x/.config/mosaic-uiorg"}',
|
||||
upper: '{"version":1,"instance":"UIorg"}', short: '{"version":1,"instance":"u"}', long: `{"version":1,"instance":"${'a'.repeat(17)}"}`,
|
||||
number: '{"version":1,"instance":7}', big: `{"version":1,"instance":"uiorg","pad":"${'x'.repeat(5000)}"}`,
|
||||
})) test(`proxy-ride-invalid: ${label}`, () => { const f = dir(); put(f, text); assert.throws(() => readRide(f.configDir), code('proxy-ride-invalid')); });
|
||||
|
||||
test('proxy-ride-invalid: wrong mode, symlink, directory', () => {
|
||||
let f = dir(); put(f, '{"version":1,"instance":"uiorg"}', 0o644);
|
||||
assert.throws(() => readRide(f.configDir), code('proxy-ride-invalid'));
|
||||
f = dir(); const real = join(f.root, 'real.json'); writeFileSync(real, '{"version":1,"instance":"uiorg"}', { mode: 0o600 }); symlinkSync(real, f.file);
|
||||
assert.throws(() => readRide(f.configDir), code('proxy-ride-invalid'));
|
||||
f = dir(); mkdirSync(f.file);
|
||||
assert.throws(() => readRide(f.configDir), code('proxy-ride-invalid'));
|
||||
});
|
||||
|
||||
test('proxy-ride-conflict: a ride file beside proxy.json refuses before the ride file is read', () => {
|
||||
const f = dir(); put(f, 'not json at all', 0o644); writeFileSync(join(f.configDir, 'proxy.json'), '{}');
|
||||
assert.throws(() => readRide(f.configDir), code('proxy-ride-conflict'));
|
||||
});
|
||||
|
||||
test('createRide writes 0600 exclusively, never rewrites, and its undo removes only its own file', () => {
|
||||
const f = dir();
|
||||
const undo = createRide(f.configDir, 'uiorg');
|
||||
assert.equal(readFileSync(f.file, 'utf8'), '{"version":1,"instance":"uiorg"}\n');
|
||||
assert.equal(lstatSync(f.file).mode & 0o777, 0o600);
|
||||
assert.deepEqual(readRide(f.configDir), { instance: 'uiorg' });
|
||||
assert.throws(() => createRide(f.configDir, 'other'), code('proxy-ride-invalid'));
|
||||
assert.equal(readFileSync(f.file, 'utf8'), '{"version":1,"instance":"uiorg"}\n');
|
||||
undo();
|
||||
assert.equal(existsSync(f.file), false);
|
||||
const again = createRide(f.configDir, 'uiorg');
|
||||
// Moved aside, not unlinked, so the new file cannot reuse its inode number.
|
||||
renameSync(f.file, join(f.root, 'aside.json')); put(f, '{"version":1,"instance":"later"}\n');
|
||||
again();
|
||||
assert.equal(readFileSync(f.file, 'utf8'), '{"version":1,"instance":"later"}\n', 'undo leaves a file it did not create');
|
||||
for (const name of ['../x', 'UI', '', 'a', 'a/b']) assert.throws(() => createRide(dir().configDir, name), code('proxy-ride-invalid'));
|
||||
});
|
||||
|
||||
test('removeRide removes the file, never a link target, and says when there was none', () => {
|
||||
let f = dir();
|
||||
assert.equal(removeRide(f.configDir), false);
|
||||
createRide(f.configDir, 'uiorg');
|
||||
assert.equal(removeRide(f.configDir), true);
|
||||
assert.equal(existsSync(f.file), false);
|
||||
f = dir(); const target = join(f.root, 'target.json'); writeFileSync(target, 'keep'); symlinkSync(target, f.file);
|
||||
assert.equal(removeRide(f.configDir), true);
|
||||
assert.equal(readFileSync(target, 'utf8'), 'keep');
|
||||
f = dir(); mkdirSync(f.file);
|
||||
assert.throws(() => removeRide(f.configDir), code('proxy-ride-invalid'));
|
||||
});
|
||||
|
||||
test('proxy-ride-conflict: proxy init refuses beside a ride file and writes nothing', async () => {
|
||||
const f = dir(); const p = installPaths(f.dataRoot, pin);
|
||||
mkdirSync(join(p.dir, 'static'), { recursive: true }); writeFileSync(p.binary, 'fake binary', { mode: 0o755 }); writeFileSync(p.panel, 'fake panel');
|
||||
createRide(f.configDir, 'uiorg');
|
||||
await assert.rejects(initializeProxy({ configDir: f.configDir, dataRoot: f.dataRoot, pin, key: 'ride-management' }), code('proxy-ride-conflict'));
|
||||
for (const name of ['proxy.json', 'secrets', '.proxy-init.lock']) assert.equal(existsSync(join(f.configDir, name)), false);
|
||||
assert.equal(existsSync(join(f.dataRoot, 'proxy')), false);
|
||||
});
|
||||
|
||||
test('each ride code has one plain owner line, and the bus refusal table carries the same line', () => {
|
||||
assert.deepEqual(Object.keys(RIDE_LINES), ['proxy-ride-invalid', 'proxy-ride-owner-missing', 'proxy-ride-conflict']);
|
||||
for (const [c, line] of Object.entries(RIDE_LINES)) {
|
||||
assert.equal(line.includes('\n'), false);
|
||||
assert.match(line, /mosaic proxy ride/);
|
||||
assert.doesNotMatch(line, /\//, 'no path in the owner line');
|
||||
assert.equal(REFUSALS[c]?.nextStep, line, c);
|
||||
}
|
||||
});
|
||||
@@ -544,3 +544,60 @@ test('the owner models come only from riding buses that answer a ready catalogue
|
||||
assert.deepEqual((await ownerModelsFrom({ proxy: true, riders: [rider('s', true, ready([stale])), rider('a', true, ready([row()]))] })).models, [row()]);
|
||||
assert.deepEqual((await ownerModelsFrom({ proxy: true, riders: [rider('a', true, ready([row()])), rider('s', true, ready([stale]))] })).models, [row()]);
|
||||
});
|
||||
|
||||
test('the owner catalogue answers before the first rider and stays authoritative over stale buses', async () => {
|
||||
let busReads = 0;
|
||||
const ownerCatalogue = async () => ({ status: 'ready', models: [glm] });
|
||||
const first = await ownerModelsFrom({ proxy: true, riders: [], ownerCatalogue });
|
||||
assert.equal(first.catalogue, 'ready');
|
||||
assert.deepEqual(first.models, [glm]);
|
||||
const both = await ownerModelsFrom({ proxy: true, ownerCatalogue, riders: [{ cliproxy: true, call: async () => { busReads++; return { catalogue: { status: 'ready', models: [row()] } }; } }] });
|
||||
assert.deepEqual(both.models, [glm]); assert.equal(busReads, 0);
|
||||
const empty = await ownerModelsFrom({ proxy: true, ownerCatalogue: async () => ({ status: 'ready', models: [] }) });
|
||||
assert.equal(empty.catalogue, 'ready'); assert.deepEqual(empty.models, []);
|
||||
});
|
||||
test('owner catalogue failure and timeout never fall back to a stale riding bus', { timeout: 3000 }, async t => {
|
||||
let release;
|
||||
const stalled = new Promise(resolve => { release = resolve; });
|
||||
// Even a broken deadline must release the synthetic read when the test times out.
|
||||
t.after(() => release({ status: 'unavailable' }));
|
||||
for (const read of [async () => { throw Error('/private token=secret'); }, () => stalled, async () => ({ status: 'unavailable' })]) {
|
||||
const start = Date.now();
|
||||
let busReads = 0;
|
||||
const owner = await ownerModelsFrom({ proxy: true, riders: [{ cliproxy: true, call: async () => { busReads++; return { catalogue: { status: 'ready', models: [row()] } }; } }], ownerCatalogue: read, timeoutMs: 20 });
|
||||
assert.equal(busReads, 0);
|
||||
assert.equal(owner.catalogue, 'unavailable'); assert.deepEqual(owner.models, []);
|
||||
assert.ok(Date.now() - start < 1000); assert.doesNotMatch(JSON.stringify(owner), /private|secret/);
|
||||
}
|
||||
});
|
||||
test('a first stopped fixture moves using the owner catalogue without a riding bus', async t => {
|
||||
const ownerModels = () => ownerModelsFrom({ proxy: true, riders: [], ownerCatalogue: async () => ({ status: 'ready', models: [row()] }) });
|
||||
let moved = 0;
|
||||
const f = admin(t, { riders: async () => [{ id: 'first', fixture: true, cliproxy: false, changes: '', status: async () => ({ pid: null }) }], ownerModels,
|
||||
move: async (_id, models) => { assert.deepEqual(models, [row()]); moved++; return { moved: true, model: row().key }; } });
|
||||
assert.equal((await f.admin.rideMove({ org: 'first' })).moved, true); assert.equal(moved, 1);
|
||||
});
|
||||
|
||||
|
||||
test('owner models reader without organizations never calls the owner catalogue', async () => {
|
||||
const { ownerModelsReader } = await import('../src/ride.mjs');
|
||||
let calls = 0, busReads = 0;
|
||||
const read = ownerModelsReader({ proxy: () => true, ownerProxy: { catalogue: async () => { calls++; return { status: 'ready', models: [glm] }; } },
|
||||
rideRiders: async () => [{ cliproxy: true, call: async () => { busReads++; return { catalogue: { status: 'ready', models: [row()] } }; } }] });
|
||||
const result = await read();
|
||||
assert.equal(calls, 0); assert.equal(busReads, 1);
|
||||
assert.deepEqual(result, { proxy: true, riding: true, models: [row()] });
|
||||
});
|
||||
|
||||
test('owner catalogue default bound stops waiting at exactly 5000 ms', { timeout: 3000 }, async t => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
let done = false;
|
||||
const pending = ownerModelsFrom({ proxy: true, ownerCatalogue: () => new Promise(() => {}) }).then(value => { done = true; return value; });
|
||||
t.mock.timers.tick(4999);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert.equal(done, false);
|
||||
t.mock.timers.tick(1);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert.equal(done, true, 'the default wait ends at 5000 ms');
|
||||
assert.deepEqual(await pending, { proxy: true, riding: false, catalogue: 'unavailable', models: [] });
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setupState } from '../src/setup-state.mjs';
|
||||
const [service, accounts] = setupState;
|
||||
const ready = { release: { verified: true }, init: { initialized: true }, unit: { active: 'active', healthy: true, listening: true }, fence: { set: false } };
|
||||
test('model service and account checks do not apply to organizations using other model routes', async () => {
|
||||
for (const providers of [[], ['fixture']]) {
|
||||
const ctx = { members: [{ id: 'local', doc: { plugins: { 'model-provider': providers } } }],
|
||||
service: () => { throw Error('must not inspect service'); }, read: () => { throw Error('must not read accounts'); } };
|
||||
for (const row of setupState) assert.deepEqual(await row.check(ctx), { state: 'not-applicable', reason: 'Your organization answers without the model service.' });
|
||||
ctx.members.push({ ...ctx.members[0], id: 'second' });
|
||||
for (const row of setupState) assert.deepEqual(await row.check(ctx), { state: 'not-applicable', reason: 'Your organizations answer without the model service.' });
|
||||
}
|
||||
});
|
||||
for (const withProxy of [false, true]) test(`an invalid member${withProxy ? ' beside a proxy organization' : ''} cannot silently skip the model checks`, async () => {
|
||||
const ctx = { members: [{ id: 'broken', invalid: true }, ...(withProxy ? [{ id: 'proxy', doc: { plugins: { 'model-provider': ['cliproxy'] } } }] : [])],
|
||||
service: async () => ready, read: async () => { throw Error('must not hide invalid membership'); } };
|
||||
for (const row of setupState) await assert.rejects(row.check(ctx), /organization unavailable/);
|
||||
});
|
||||
test('a mixed instance still checks its model service and proxy accounts', async () => {
|
||||
const ctx = { members: [{ id: 'local', doc: { plugins: {} } }, { id: 'proxy', doc: { plugins: { 'model-provider': ['cliproxy'] } } }],
|
||||
service: async () => ready, read: async (org, name) => {
|
||||
assert.equal(org.id, 'proxy');
|
||||
return name === 'accounts' ? { accounts: [{ provider: 'claude', status: 'active' }] } : { catalogue: { status: 'ready', models: [{ upstream: 'claude', available: true }] } };
|
||||
} };
|
||||
for (const row of setupState) assert.equal((await row.check(ctx)).state, 'done');
|
||||
});
|
||||
test('service needs a verified install, active unit and answering port', async () => {
|
||||
assert.equal((await service.check({ service: async () => ready })).state, 'done');
|
||||
for (const unit of [{ active: 'inactive' }, { active: 'failed' }, { active: 'active', healthy: false }]) assert.equal((await service.check({ service: async () => ({ ...ready, unit }) })).state, 'failed');
|
||||
assert.equal((await service.check({ service: async () => ({ release: {}, init: {}, unit: {} }) })).state, 'next');
|
||||
assert.equal((await service.check({ service: async () => ({ release: {}, init: {}, unit: {}, fence: { set: true } }) })).state, 'failed');
|
||||
await assert.rejects(service.check({ service: async () => ({ release: { problem: 'proxy-install-invalid' }, init: {}, unit: {} }) }));
|
||||
await assert.rejects(service.check({ service: async () => { throw Error(); } }));
|
||||
});
|
||||
test('account completion uses existing account metadata and a usable model, with no new health probe', async () => {
|
||||
const org = { id: 'team' };
|
||||
const ctx = (a, models) => ({ members: [org], read: async (_, name) => name === 'accounts' ? { accounts: a } : { catalogue: { status: 'ready', models } } });
|
||||
assert.equal((await accounts.check(ctx([{ provider: 'claude', status: 'active' }], [{ module: 'cliproxy', upstream: 'claude', available: true }]))).state, 'done');
|
||||
assert.equal((await accounts.check(ctx([], []))).state, 'next');
|
||||
assert.equal((await accounts.check(ctx([{ status: 'error' }], []))).state, 'failed');
|
||||
assert.equal((await accounts.check(ctx([{ provider: 'claude', status: 'active' }], []))).state, 'next');
|
||||
assert.equal((await accounts.check({ members: [], read: async () => { throw Error(); } })).state, 'next');
|
||||
await assert.rejects(accounts.check({ members: [org], read: async () => { throw Error(); } }));
|
||||
});
|
||||
test('the account reader can answer without an organization and uses the catalogue provider identity', async () => {
|
||||
const result = await accounts.check({ members: [], accounts: async () => ({ accounts: [{ provider: 'claude', status: 'active' }], catalogue: { status: 'ready', models: [{ module: 'another-provider', upstream: 'claude', available: true }] } }) });
|
||||
assert.equal(result.state, 'done');
|
||||
});
|
||||
for (const status of ['unavailable', 'disabled']) test(`a ${status} catalogue gives a plain next step`, async () => {
|
||||
for (const entries of [[], [{ provider: 'claude', status: 'active' }]]) {
|
||||
const result = await accounts.check({ members: [], accounts: async () => ({ accounts: entries, catalogue: { status } }) });
|
||||
assert.equal(result.state, 'next'); assert.doesNotMatch(result.reason, /Couldn't check/);
|
||||
}
|
||||
});
|
||||
test('one account reader failing does not hide a usable account', async () => {
|
||||
assert.equal((await accounts.check({ members: [{ id: 'bad' }, { id: 'good' }], read: async (org, name) => {
|
||||
if (org.id === 'bad') throw Error();
|
||||
return name === 'accounts' ? { accounts: [{ provider: 'claude', status: 'active' }] } : { catalogue: { status: 'ready', models: [{ upstream: 'claude', available: true }] } };
|
||||
} })).state, 'done');
|
||||
});
|
||||
import { readService } from '../src/setup-state.mjs';
|
||||
import { defaultRun } from '../src/admin.mjs';
|
||||
import { mkdtemp, mkdir, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
test('service inspection makes one systemctl read and forwards cancellation', async t => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'setup-service-'));
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const configDir = join(root, 'config'), dataRoot = join(root, 'data');
|
||||
await mkdir(configDir); await mkdir(join(dataRoot, 'proxy'), { recursive: true });
|
||||
let calls = 0;
|
||||
const signal = new AbortController().signal;
|
||||
await readService({ configDir, dataRoot, instance: 'test', signal, run: async (command, _args, options) => {
|
||||
calls++; assert.equal(command, 'systemctl'); assert.equal(options.signal, signal); assert.equal(options.timeout, 1000);
|
||||
return { code: 0, stdout: 'LoadState=loaded\nActiveState=inactive\n' };
|
||||
} });
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
test('the process reader stops promptly when its request is cancelled', async () => {
|
||||
const controller = new AbortController(), start = Date.now();
|
||||
const pending = defaultRun(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { timeout: 5000, signal: controller.signal });
|
||||
setTimeout(() => controller.abort(), 30);
|
||||
assert.notEqual((await pending).code, 0); assert.ok(Date.now() - start < 1500);
|
||||
});
|
||||
test('an unrelated available model does not stand in for an active account offering one', async () => {
|
||||
assert.equal((await accounts.check({ members: [], accounts: async () => ({ accounts: [{ provider: 'claude', status: 'active' }], catalogue: { status: 'ready', models: [{ upstream: 'unrelated', available: true }] } }) })).state, 'next');
|
||||
});
|
||||
import { PROVIDERS, providerUpstream } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
test('account matching uses the plugin mapping when its provider and upstream names differ', async () => {
|
||||
const provider = PROVIDERS.find(p => p.signIn === 'apikey');
|
||||
const result = await accounts.check({ members: [], accounts: async () => ({ accounts: [{ provider: provider.id, status: 'active' }], catalogue: { status: 'ready', models: [{ upstream: providerUpstream(provider.id), available: true }] } }) });
|
||||
assert.equal(result.state, 'done');
|
||||
});
|
||||
for (const status of ['unavailable', 'disabled']) test(`a ${status} organization catalogue does not depend on an account reader answering`, async () => {
|
||||
let accountsRead = 0;
|
||||
const result = await accounts.check({ members: [{ id: 'team' }], read: async (_, name) => {
|
||||
if (name === 'accounts') { accountsRead++; throw Error('no proxy configured'); }
|
||||
return { catalogue: { status, models: [] } };
|
||||
} });
|
||||
assert.equal(result.state, 'next'); assert.doesNotMatch(result.reason, /Couldn't check/); assert.equal(accountsRead, 0);
|
||||
});
|
||||
@@ -60,7 +60,7 @@ function normalizeDoc(ctx, id, input, existing) {
|
||||
}
|
||||
// Presets are supplied by installed modules; reject malformed or duplicate names
|
||||
// rather than silently choosing a different module's configuration.
|
||||
async function discoverPresets() {
|
||||
async function discoverPresets(context) {
|
||||
const presets = new Map();
|
||||
for (const kind of ['harness', 'model-provider']) {
|
||||
const { modules, refused } = await loadInstalled(kind);
|
||||
@@ -68,7 +68,7 @@ async function discoverPresets() {
|
||||
for (const { module } of modules) {
|
||||
if (module.orgPresets === undefined) continue;
|
||||
if (typeof module.orgPresets !== 'function') fail('org-invalid', 'invalid preset provider');
|
||||
const list = await module.orgPresets();
|
||||
const list = await module.orgPresets(context);
|
||||
if (!Array.isArray(list)) fail('org-invalid', 'invalid preset provider');
|
||||
for (const p of list) {
|
||||
if (!p || typeof p.name !== 'string' || !/^[a-z][a-z0-9-]*$/.test(p.name) || presets.has(p.name) ||
|
||||
@@ -85,10 +85,11 @@ async function discoverPresets() {
|
||||
}
|
||||
// `owner` (#1873 ride-default) is what the Console read from the owner's model proxy:
|
||||
// {proxy, riding, models}. A preset that does not use it ignores it.
|
||||
export async function orgPresets({ env = process.env, owner } = {}) {
|
||||
const presets = await discoverPresets();
|
||||
// `fixture` (first-run-fixes-1 B2) is what the Console read of the instance's dev fixture: {ready}.
|
||||
export async function orgPresets({ env = process.env, owner, fixture } = {}) {
|
||||
const presets = await discoverPresets({ env, owner, fixture });
|
||||
return Promise.all([...presets.values()].map(async p => {
|
||||
const availability = await p.available({ env, owner });
|
||||
const availability = await p.available({ env, owner, fixture });
|
||||
if (!availability || typeof availability.ok !== 'boolean' || (!availability.ok && (typeof availability.reason !== 'string' || !availability.reason))) fail('org-invalid', 'invalid preset availability');
|
||||
return { name: p.name, label: p.label, description: p.description, thinking: structuredClone(p.thinking), available: availability.ok ? { ok: true } : { ok: false, reason: availability.reason } };
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// Uses the host's recorded harness fit result, not a thinking-level list or a new preflight.
|
||||
export const setupState = Object.freeze([
|
||||
{
|
||||
id: 'agents.routed', title: 'Choose models for your agents',
|
||||
purpose: 'The model your assistant and your chief use. Filled in for you when the default fits.',
|
||||
fix: { page: '#/settings/routing', label: 'Choose models' },
|
||||
order: { after: ['organization.ready'] }, required: true,
|
||||
async check(ctx) {
|
||||
if (!ctx.members.length) return { state: 'next', reason: 'Create an organization first, then choose the models your agents use.' };
|
||||
const answers = await Promise.allSettled(ctx.members.map(async org => {
|
||||
const inOrg = ctx.members.length > 1 ? ` in ${org.id}` : '';
|
||||
const answer = (state, reason, fix) => ({ state, reason: inOrg ? reason.replace(/\.$/, `${inOrg}.`) : reason, ...(fix ? { fix } : {}) });
|
||||
const fix = { page: '#/settings/routing', label: 'Choose models' };
|
||||
const r = await ctx.read(org, 'routes');
|
||||
if (!r?.instances || !Array.isArray(r.harnesses) || !Array.isArray(r.models)) throw Error('routes unavailable');
|
||||
const names = ['assistant', 'chief'].map(name => Object.entries(org.doc?.roles ?? {}).find(([, role]) => role.definition === (name === 'chief' ? 'chief-of-staff' : name))?.[0] ?? name);
|
||||
const chosen = names.map(name => r.instances[name]);
|
||||
const missing = chosen.map((c, i) => !c?.harness || !c.model || !r.harnesses.includes(c.harness) || !r.models.includes(c.model) ? ['assistant', 'chief'][i] : null).filter(Boolean);
|
||||
if (missing.length) return answer('next', `Choose a model for ${missing.length === 2 ? 'both your assistant and your chief' : `your ${missing[0]}`}.`, fix);
|
||||
const p = await ctx.read(org, 'plugins');
|
||||
if (!Array.isArray(p?.harnessWatch)) throw Error('fit unavailable');
|
||||
const fits = chosen.map(c => p.harnessWatch.find(h => h.name === c.harness));
|
||||
if (fits.some(h => ['red', 'missing'].includes(h?.state))) return answer('failed', 'A chosen program did not pass its check. Choose models to check the program.', fix);
|
||||
if (fits.some(h => h?.state === 'unknown')) return answer('failed', 'The program check did not finish. Choose models to try again.', fix);
|
||||
if (fits.some(h => !['fit', 'changed'].includes(h?.state) || !h?.checkedAt)) return answer('checking', 'The chosen programs have not passed their check yet. Choose models to check them.', fix);
|
||||
return answer('done', 'Your assistant and chief have models, and their programs passed the recorded check.');
|
||||
}));
|
||||
const found = answers.filter(a => a.status === 'fulfilled').map(a => a.value);
|
||||
const missed = answers.length - found.length;
|
||||
const result = found.find(a => a.state === 'failed') ?? found.find(a => a.state === 'next') ?? found.find(a => a.state === 'checking') ?? found[0];
|
||||
if (!result) return { state: 'next', reason: "Your organizations couldn't be checked. Choose models to check their settings." };
|
||||
if (ctx.members.length > 1 && !missed && result.state === 'done') return { state: 'done', reason: 'Your assistant and chief have models, and their programs passed the recorded check in every organization.' };
|
||||
return { ...result, reason: result.reason + (missed ? " Some organizations couldn't be checked. Choose models to check their settings." : '') };
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -0,0 +1,22 @@
|
||||
export const setupState = Object.freeze([
|
||||
{
|
||||
id: 'organization.ready', title: 'Create your organization',
|
||||
purpose: 'One organization is one team of agents with its own projects and tasks.',
|
||||
fix: { page: '#/settings/organizations?new=1', label: 'Create organization' },
|
||||
order: { after: ['model-account.connected'] }, required: true,
|
||||
async check(ctx) {
|
||||
if (!ctx.members.length) return { state: 'next', reason: 'Give your team a name. Mosaic sets up its first project and agents.' };
|
||||
const answers = await Promise.allSettled(ctx.members.map(async org => ctx.read(org, 'status')));
|
||||
const states = answers.filter(a => a.status === 'fulfilled').map(a => a.value);
|
||||
const missed = answers.length - states.length;
|
||||
const unhealthy = states.some(s => s?.healthy !== true);
|
||||
const fix = { page: '#/settings/organizations', label: 'Open Organizations' };
|
||||
if (!states.length) return { state: 'next', reason: "Your organizations couldn't be checked. Open Organizations to check them.", fix };
|
||||
if (!states.some(s => s?.healthy === true)) return { state: 'failed', reason: 'An organization is not answering. Open Organizations to check it and start it again.' + (missed ? " Some organizations couldn't be checked." : ''), fix };
|
||||
return { state: 'done', reason: 'An organization is created and answering.' +
|
||||
(unhealthy ? ' Some organizations are not answering. Open Organizations to check them.' : '') +
|
||||
(missed ? " Some organizations couldn't be checked. Open Organizations to check them." : ''),
|
||||
...(unhealthy || missed ? { fix } : {}) };
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -9,10 +9,20 @@ test('installed modules supply presets and report availability without credentia
|
||||
const claude = presets.find(p => p.name === 'claude-code');
|
||||
assert.equal(fixture.available.ok, true);
|
||||
assert.equal(claude.available.ok, false);
|
||||
assert.ok(claude.available.reason);
|
||||
assert.equal(claude.available.reason, 'Claude sign-in is not available on this Console.');
|
||||
assert.deepEqual(claude.thinking.levels, ['low', 'medium', 'high', 'xhigh', 'max']);
|
||||
});
|
||||
|
||||
// first-run-fixes-1 (B2): the Console passes what it knows of the instance's dev fixture.
|
||||
test('the Test model preset is hidden when the Console says the fixture is not ready', async () => {
|
||||
const fixtureOf = async fixture => (await service.orgPresets({ env: { PATH: '/usr/bin:/bin' }, fixture })).find(p => p.name === 'fixture');
|
||||
assert.equal(await fixtureOf({ ready: false }), undefined);
|
||||
assert.deepEqual((await fixtureOf({ ready: true })).available, { ok: true });
|
||||
assert.deepEqual((await fixtureOf(undefined)).available, { ok: true }, 'no word from the Console keeps it offered');
|
||||
const others = async fixture => (await service.orgPresets({ env: { PATH: '/usr/bin:/bin' }, fixture })).filter(p => p.name !== 'fixture').map(p => [p.name, p.available]);
|
||||
assert.deepEqual(await others({ ready: false }), await others(undefined), 'no other preset reads the fixture');
|
||||
});
|
||||
|
||||
test('preset overlays produce valid documents and the legacy alias remains identical', async () => {
|
||||
const doc = await templateRender('alpha', { preset: 'fixture' });
|
||||
assert.deepEqual(doc, await templateRender('alpha', { fixture: 'local' }));
|
||||
@@ -44,7 +54,11 @@ test('the cliproxy preset is discovered and names each reason it is unavailable'
|
||||
assert.match((await cliproxyOf({ proxy: true, riding: false, models: [row()] })).available.reason, /No organization uses the model proxy yet/);
|
||||
assert.match((await cliproxyOf({ proxy: true, riding: true, models: [] })).available.reason, /lists no model you can use/);
|
||||
for (const bad of [row({ available: false }), row({ reason: 'unverified' }), row({ module: 'fixture' }), row({ harnesses: [] })])
|
||||
assert.match((await cliproxyOf({ proxy: true, riding: true, models: [bad] })).available.reason, /lists no model you can use/);
|
||||
assert.equal((await cliproxyOf({ proxy: true, riding: true, models: [bad] })).available.reason, 'Switch a model on in Model setup.');
|
||||
// first-run-fixes-1 (F5): each reason names the page as the Settings nav does.
|
||||
assert.equal(none.available.reason, 'Set up the model proxy first, on the Model setup page.');
|
||||
assert.equal((await cliproxyOf({ proxy: true, riding: false, models: [row()] })).available.reason, 'No organization uses the model proxy yet, or none answered. Open Model setup to check it.');
|
||||
assert.equal((await cliproxyOf({ proxy: true, riding: true, models: [] })).available.reason, 'The model proxy lists no model you can use. Sign in to an account on the Model setup page.');
|
||||
const ok = await cliproxyOf({ proxy: true, riding: true, models: [row()] });
|
||||
assert.deepEqual(ok.available, { ok: true });
|
||||
assert.deepEqual(ok.thinking, { levels: ['low', 'medium', 'high', 'xhigh', 'max'], default: 'low' });
|
||||
@@ -72,3 +86,18 @@ test('existing presets ignore the new model and owner inputs', async () => {
|
||||
assert.equal(presets.find(p => p.name === 'fixture').available.ok, true);
|
||||
assert.equal(presets.find(p => p.name === 'claude-code').available.ok, false);
|
||||
});
|
||||
|
||||
|
||||
test('the first organization uses the owner catalogue and one plain reason for empty or failed reads', async () => {
|
||||
const owner = { proxy: true, riding: false, catalogue: 'ready', models: [row()] };
|
||||
assert.deepEqual((await cliproxyOf(owner)).available, { ok: true });
|
||||
const reason = (await cliproxyOf({ ...owner, models: [] })).available.reason;
|
||||
assert.match(reason, /account on the Model setup page/); assert.doesNotMatch(reason, /organization|Ride all/);
|
||||
const unavailable = (await cliproxyOf({ ...owner, catalogue: 'unavailable', models: [] })).available;
|
||||
assert.equal(unavailable.ok, false); assert.equal(unavailable.reason, 'Your models could not be checked. Open Model setup to try again.');
|
||||
});
|
||||
|
||||
test('a catalogue with only switched-off models names the model switch', async () => {
|
||||
assert.deepEqual((await cliproxyOf({ proxy: true, riding: false, catalogue: 'ready', models: [row({ available: false, reason: 'model-off' })] })).available,
|
||||
{ ok: false, reason: 'Switch a model on in Model setup.' });
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setupState } from '../src/setup/setup-state.mjs';
|
||||
import { setupState as routes } from '../src/setup/setup-routing.mjs';
|
||||
const org = { id: 'team', doc: { roles: { assistant: { definition: 'assistant' }, chief: { definition: 'chief' } } } };
|
||||
test('routing identifies the missing agent and names the organization only when there are several', async () => {
|
||||
const selected = { harness: 'example', model: 'model' };
|
||||
for (const missing of ['assistant', 'chief', 'both']) for (const multiple of [false, true]) {
|
||||
const members = multiple ? [{ ...org, id: 'ready' }, { ...org, id: 'fxco' }] : [org];
|
||||
const result = await routes[0].check({ members, read: async (member, name) => name === 'plugins'
|
||||
? { harnessWatch: [{ name: 'example', state: 'fit', checkedAt: 'now' }] }
|
||||
: { harnesses: ['example'], models: ['model'], instances: member.id === 'ready' ? { assistant: selected, chief: selected }
|
||||
: Object.fromEntries(['assistant', 'chief'].filter(n => n !== missing && missing !== 'both').map(n => [n, selected])) } });
|
||||
const who = missing === 'both' ? 'both your assistant and your chief' : `your ${missing}`;
|
||||
assert.equal(result.reason, `Choose a model for ${who}${multiple ? ' in fxco' : ''}.`);
|
||||
}
|
||||
});
|
||||
test('organization readiness requires an owner organization and its bus answering', async () => {
|
||||
assert.equal((await setupState[0].check({ members: [], read: async () => {} })).state, 'next');
|
||||
for (const healthy of [true, false]) assert.equal((await setupState[0].check({ members: [org], read: async () => ({ healthy }) })).state, healthy ? 'done' : 'failed');
|
||||
const unavailable = await setupState[0].check({ members: [org], read: async () => { throw Error('private'); } });
|
||||
assert.equal(unavailable.state, 'next'); assert.match(unavailable.reason, /couldn't be checked/); assert.doesNotMatch(unavailable.reason, /private/);
|
||||
});
|
||||
test('routing confirms every organization when all their agents have models and recorded fit', async () => {
|
||||
const selected = { harness: 'example', model: 'model' };
|
||||
const result = await routes[0].check({ members: [{ ...org, id: 'alpha' }, { ...org, id: 'beta' }], read: async (_, name) => name === 'plugins'
|
||||
? { harnessWatch: [{ name: 'example', state: 'fit', checkedAt: 'now' }] }
|
||||
: { harnesses: ['example'], models: ['model'], instances: { assistant: selected, chief: selected } } });
|
||||
assert.equal(result.state, 'done');
|
||||
assert.equal(result.reason, 'Your assistant and chief have models, and their programs passed the recorded check in every organization.');
|
||||
});
|
||||
test('one answering organization completes setup while another cannot be checked', async () => {
|
||||
const result = await setupState[0].check({ members: [{ id: 'broken', invalid: true }, org], read: async member => {
|
||||
if (member.invalid) throw Error('private');
|
||||
return { healthy: true };
|
||||
} });
|
||||
assert.equal(result.state, 'done'); assert.match(result.reason, /Some organizations couldn't be checked/); assert.doesNotMatch(result.reason, /private/);
|
||||
});
|
||||
test('one answering organization is enough even when another reports an unhealthy bus', async () => {
|
||||
const result = await setupState[0].check({ members: [{ id: 'stopped' }, org], read: async member => ({ healthy: member.id === org.id }) });
|
||||
assert.equal(result.state, 'done'); assert.match(result.reason, /Some organizations are not answering/);
|
||||
});
|
||||
test('routing requires both agent routes and recorded fit, never levels alone', async () => {
|
||||
const route = { harnesses: ['example'], models: ['model'], instances: { assistant: { harness: 'example', model: 'model' }, chief: { harness: 'example', model: 'model' } } };
|
||||
const run = (r = route, state = 'fit') => routes[0].check({ members: [org], read: async (_, name) => name === 'routes' ? r : { harnessWatch: [{ name: 'example', state, checkedAt: '2026-11-21T01:00:00Z' }] } });
|
||||
assert.equal((await run()).state, 'done');
|
||||
assert.equal((await run(route, 'changed')).state, 'done');
|
||||
assert.equal((await run(route, 'red')).state, 'failed');
|
||||
assert.equal((await run(route, 'unchecked')).state, 'checking');
|
||||
assert.equal((await run({ ...route, instances: { assistant: route.instances.assistant } })).state, 'next');
|
||||
assert.equal((await routes[0].check({ members: [] })).state, 'next');
|
||||
assert.match((await routes[0].check({ members: [org], read: async () => { throw Error(); } })).reason, /couldn't be checked/);
|
||||
});
|
||||
test('routing follows a renamed chief before another role with the conventional id', async () => {
|
||||
const member = { id: 'team', doc: { roles: { assistant: { definition: 'assistant' }, chief: { definition: 'coder' }, lead: { definition: 'chief-of-staff' } } } };
|
||||
const r = { harnesses: ['example'], models: ['model'], instances: { assistant: { harness: 'example', model: 'model' }, chief: { harness: 'example', model: 'model' } } };
|
||||
const check = () => routes[0].check({ members: [member], read: async (_, name) => name === 'routes' ? r : { harnessWatch: [{ name: 'example', state: 'fit', checkedAt: '2026-11-21T01:00:00Z' }] } });
|
||||
assert.equal((await check()).state, 'next');
|
||||
r.instances.lead = r.instances.chief;
|
||||
assert.equal((await check()).state, 'done');
|
||||
});
|
||||
test('routing keeps answering organizations and uses the worst answered state', async () => {
|
||||
const route = { harnesses: ['example'], models: ['model'], instances: { assistant: { harness: 'example', model: 'model' }, chief: { harness: 'example', model: 'model' } } };
|
||||
for (const state of ['fit', 'red', 'unknown']) {
|
||||
const result = await routes[0].check({ members: [{ id: 'bad' }, org], read: async (member, name) => {
|
||||
if (member.id === 'bad') throw Error('private');
|
||||
return name === 'routes' ? route : { harnessWatch: [{ name: 'example', state, checkedAt: 'now' }] };
|
||||
} });
|
||||
assert.equal(result.state, state === 'fit' ? 'done' : 'failed'); assert.match(result.reason, /Some organizations couldn't be checked/); assert.doesNotMatch(result.reason, /private/);
|
||||
}
|
||||
const result = await routes[0].check({ members: [org, { ...org, id: 'empty' }], read: async (member, name) => name === 'routes' ? member.id === 'empty' ? { ...route, instances: {} } : route : { harnessWatch: [{ name: 'example', state: 'fit', checkedAt: 'now' }] } });
|
||||
assert.equal(result.state, 'next');
|
||||
});
|
||||
@@ -50,6 +50,19 @@ unknown or ambiguous legacy mapping and validates transport data before use.
|
||||
|
||||
### Organization presets
|
||||
|
||||
“Your models through the model proxy” reads the instance owner's catalogue for the signed-in
|
||||
root owner in an organization-mode Console. It can create the first organization after an
|
||||
account is connected and a usable model is offered. Availability, model choices and template
|
||||
selection use that same read; a failed read offers nothing. With models switched off, the
|
||||
preset points to the model switches in Model setup; with no model rows, it asks to sign in.
|
||||
The owner catalogue takes precedence
|
||||
over riding buses, so an old bus catalogue cannot restore an unavailable or switched-off model.
|
||||
Other Console modes keep the riding-bus reader. Quick Setup starts the normal organization bus,
|
||||
which registers with the shared model service and issues model keys on launch preflight.
|
||||
Quick Setup gives the chief the routing values the preset assistant defines (harness, model
|
||||
and thinking), without adding the chief to the launch list. Advanced Setup keeps the preset template unchanged. The routing
|
||||
checklist still requires the selected program's existing recorded check to pass.
|
||||
|
||||
A `harness` or `model-provider` module may export `orgPresets()`, returning an
|
||||
array of preset descriptions. Each has a globally unique stable `name`, a
|
||||
`label`, a one-line `description`, `thinking: { levels, default }`, an
|
||||
|
||||
@@ -92,7 +92,7 @@ export function orgPresets() {
|
||||
thinking: { levels: [...LEVELS], default: 'low' },
|
||||
available: ({ env }) => {
|
||||
const problem = preflight({ env });
|
||||
return problem ? { ok: false, reason: problem.code === 'no-session-credential' ? 'No session credential is available to the Console.' : 'Claude Code is not available to the Console.' } : { ok: true };
|
||||
return problem ? { ok: false, reason: problem.code === 'no-session-credential' ? 'Claude sign-in is not available on this Console.' : 'Claude Code is not available on this Console.' } : { ok: true };
|
||||
},
|
||||
overlay: ({ thinking }) => ({ plugins: { channel: ['cli', 'webui'], harness: ['claude-code'] },
|
||||
launch: { by: 'chief', instances: ['assistant'], models: { opus: { provider: 'anthropic', model: 'claude-opus-5-5' } } },
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
// Provider configuration and transport declarations owned by the proxy module.
|
||||
export const interfaceVersion = 1;
|
||||
// Whether an admitted organization needs this model service for its model routes.
|
||||
export const usesModelService = doc => (doc.plugins?.['model-provider'] ?? []).includes('cliproxy');
|
||||
export const ZAI_URL = 'https://api.z.ai/api/anthropic';
|
||||
// #1873 settings-backend-a3: the one list of providers an account can be added for. The bus proxy
|
||||
// page, the management client and the Console's provider select all read it; a provider not here
|
||||
@@ -94,7 +96,7 @@ export async function catalogue({ listAccounts, listModels, listGroups, now, off
|
||||
if (group.disabled === true || !group.keys.some(key => key && key.disabled !== true)) continue;
|
||||
const upstream = family(group['base-url']);
|
||||
if (group.models === undefined || (Array.isArray(group.models) && !group.models.length)) {
|
||||
if (upstream === 'zai') notices.push('z.ai account has no models configured. Add them on Model proxy.');
|
||||
if (upstream === 'zai') notices.push('z.ai account has no models configured. Add them on Model setup.');
|
||||
continue;
|
||||
}
|
||||
if (!Array.isArray(group.models) || group.models.length > MAX_MODELS) throw Error();
|
||||
@@ -143,23 +145,26 @@ export function route({ selection, harness }) {
|
||||
}
|
||||
|
||||
// #1873 ride-default slice 1: a new organization that uses the owner's models through the
|
||||
// instance's model proxy. The Console reads the owner's catalogue from a riding bus and passes
|
||||
// instance's model proxy. The Console reads the instance owner catalogue, or riding buses, and passes
|
||||
// it as `owner`; this module never reaches the proxy itself.
|
||||
const THINKING = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max']);
|
||||
export const usableModel = m => !!m && m.module === 'cliproxy' && m.available === true && m.reason === null
|
||||
&& typeof m.key === 'string' && /^[a-z][a-z0-9-]{0,63}$/.test(m.key) && typeof m.upstream === 'string' && Object.hasOwn(ROUTES, m.upstream)
|
||||
&& typeof m.provider === 'string' && typeof m.model === 'string' && MODEL.test(m.model)
|
||||
&& Array.isArray(m.harnesses) && (m.harnesses.includes('claude-code') || m.harnesses.includes('pi'));
|
||||
export function ownerModelsAvailable(owner) {
|
||||
if (!owner || owner.proxy !== true) return { ok: false, reason: 'Set up the model proxy first, on the Model setup page.' };
|
||||
if (owner.catalogue === 'unavailable') return { ok: false, reason: 'Your models could not be checked. Open Model setup to try again.' };
|
||||
if (owner.catalogue !== 'ready' && owner.riding !== true) return { ok: false, reason: 'No organization uses the model proxy yet, or none answered. Open Model setup to check it.' };
|
||||
if (Array.isArray(owner.models) && owner.models.length && !owner.models.some(usableModel)) return { ok: false, reason: 'Switch a model on in Model setup.' };
|
||||
if (!Array.isArray(owner.models) || !owner.models.some(usableModel)) return { ok: false, reason: 'The model proxy lists no model you can use. Sign in to an account on the Model setup page.' };
|
||||
return { ok: true };
|
||||
}
|
||||
export function orgPresets() {
|
||||
return [{ name: 'cliproxy', label: 'Your models through the model proxy',
|
||||
description: 'Uses a model your model proxy lists. Each reply spends your own account.',
|
||||
thinking: { levels: [...THINKING], default: 'low' },
|
||||
available: ({ owner } = {}) => {
|
||||
if (!owner || owner.proxy !== true) return { ok: false, reason: 'Set up the model proxy first, on the Model proxy page.' };
|
||||
if (owner.riding !== true) return { ok: false, reason: 'No organization uses the model proxy yet, or none answered. Use Ride all on the Model proxy page.' };
|
||||
if (!Array.isArray(owner.models) || !owner.models.some(usableModel)) return { ok: false, reason: 'The model proxy lists no model you can use. Sign in to an account on the Model proxy page.' };
|
||||
return { ok: true };
|
||||
},
|
||||
available: ({ owner } = {}) => ownerModelsAvailable(owner),
|
||||
overlay: ({ thinking, model }) => {
|
||||
if (!usableModel(model)) throw Object.assign(Error('the model proxy lists no such model'), { code: 'org-invalid' });
|
||||
const harness = model.harnesses.includes('claude-code') ? 'claude-code' : 'pi';
|
||||
|
||||
@@ -17,9 +17,17 @@ export const FIXTURE_TEMPLATE = Object.freeze({
|
||||
vars: { 'bus.tester': true },
|
||||
});
|
||||
// Organization setup is supplied by this module, alongside its model route.
|
||||
export function orgPresets() {
|
||||
// first-run-fixes-1 (B2): `fixture` is what the Console knows of the instance's dev fixture
|
||||
// ({ ready }). A chat on this preset has no endpoint to answer it until `mosaic dev fixture init`
|
||||
// runs, so the preset is hidden when the Console says it is not ready. With no word from
|
||||
// the Console (a caller that does not read the fixture) it stays offered.
|
||||
// first-run-fixes-1 follow-up: the Console never tells an owner to run a command, so the reason is a plain line.
|
||||
export const FIXTURE_NOT_READY = 'Developer test fixture is not running.';
|
||||
export function orgPresets({ fixture } = {}) {
|
||||
if (fixture?.ready === false) return [];
|
||||
return [{ name: 'fixture', label: 'Test model', description: 'Canned replies, no cost.',
|
||||
thinking: { levels: ['off'], default: 'off' }, available: () => ({ ok: true }),
|
||||
thinking: { levels: ['off'], default: 'off' },
|
||||
available: ({ fixture } = {}) => (fixture?.ready === false ? { ok: false, reason: FIXTURE_NOT_READY } : { ok: true }),
|
||||
overlay: ({ thinking }) => ({ ...structuredClone(FIXTURE_TEMPLATE), assistantVars: { ...FIXTURE_TEMPLATE.assistantVars, thinking } }) }];
|
||||
}
|
||||
const HARNESSES = Object.freeze(['pi']);
|
||||
|
||||
@@ -158,3 +158,15 @@ export function checkPlugins(value, where, { kinds = KINDS, fail = raise } = {})
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// Instance readiness contributions, independent of an organization's plugin switches. Each part
|
||||
// owns its row definitions and read checks. The host loads these paths relative to packages/.
|
||||
// No new kind, module interface, organization setting or capability is introduced here.
|
||||
export const setupState = Object.freeze([
|
||||
'model-proxy/src/setup-state.mjs',
|
||||
'organization/src/setup/setup-state.mjs',
|
||||
'organization/src/setup/setup-routing.mjs',
|
||||
'bus/src/setup-reply.mjs',
|
||||
'tasks/src/setup-state.mjs',
|
||||
'processing-control/src/setup-state.mjs',
|
||||
]);
|
||||
@@ -36,7 +36,7 @@ test('an empty group offers no models; unknown groups offer claude-code and pi a
|
||||
const c = await catalogue(d);
|
||||
assert.equal(c.models.length, 1);
|
||||
assert.deepEqual([c.models[0].upstream, c.models[0].harnesses, c.models[0].reason], ['other', ['claude-code', 'pi'], 'unverified']);
|
||||
assert.ok(c.notices.includes('z.ai account has no models configured. Add them on Model proxy.'));
|
||||
assert.ok(c.notices.includes('z.ai account has no models configured. Add them on Model setup.'));
|
||||
});
|
||||
|
||||
test('a failed catalogue never authorizes a saved route', async () => {
|
||||
|
||||
@@ -7,18 +7,24 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { constants } from 'node:os';
|
||||
import { loadSystem } from '../../cli/src/config.mjs';
|
||||
import { CliError } from '../../cli/src/errors.mjs';
|
||||
import { RIDE_LINES } from '../../model-proxy/src/settings.mjs';
|
||||
import { configDir } from '../../organization/src/organization-config.mjs';
|
||||
import { launchWorker, redactSecrets, WorkerLaunchError } from './worker-proxy.mjs';
|
||||
import { unregisterRuntime } from './runtimes.mjs';
|
||||
import { initializeControl, assertProcessing } from './state.mjs';
|
||||
|
||||
function refusal(e) {
|
||||
// proxy-ride: the config refusal keeps its code and fixed owner line. Other config problems read
|
||||
// as they did.
|
||||
const ride = e instanceof CliError ? /(?:^|: )(proxy-ride-(?:invalid|owner-missing|conflict)): /.exec(e.message) : null;
|
||||
if (ride) return { line: `processing: ${ride[1]}: ${RIDE_LINES[ride[1]]}`, exitCode: 3 };
|
||||
if (e instanceof WorkerLaunchError) return { line: e.code ? `processing: ${e.code}: ${e.line}` : e.line, exitCode: e.exitCode };
|
||||
return { line: `processing: ${e?.code?.startsWith?.('processing-') ? e.code : 'container-launch-failed'}`, exitCode: 3 };
|
||||
}
|
||||
|
||||
try {
|
||||
const system = loadSystem();
|
||||
const system = loadSystem({ ride: true });
|
||||
initializeControl(system.dataRoot);
|
||||
assertProcessing(system.dataRoot);
|
||||
const args = process.argv.slice(2), tty = args[0] === '--tty';
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { defaultRun } from '../../model-proxy/src/admin.mjs';
|
||||
import { listRunIds, isRunId, readRunDocument } from '../../runs/src/runs.mjs';
|
||||
import { accountState, setupState as modelSetupState } from '../../model-proxy/src/setup-state.mjs';
|
||||
|
||||
// Stop at the first result instead of parsing the whole run history.
|
||||
export function hasRunResult(dataRoot, { ids = listRunIds, read = readRunDocument } = {}) {
|
||||
if (!dataRoot) return false;
|
||||
return ids(dataRoot).reverse().some(id => isRunId(id) && !!read(dataRoot, id, 'result.json'));
|
||||
}
|
||||
export async function dockerAnswers({ run = defaultRun, signal } = {}) {
|
||||
try { return (await run('docker', ['info', '--format', '{{.ServerVersion}}'], { timeout: 800, env: process.env, signal })).code === 0; }
|
||||
catch { return false; }
|
||||
}
|
||||
export const setupState = Object.freeze([
|
||||
{
|
||||
id: 'worker.ready', title: 'Run work in sealed containers',
|
||||
purpose: 'Lets agents run code in a container on this computer. Not needed to start. Needs Docker.',
|
||||
fix: null, order: { after: [] }, required: false,
|
||||
async check(ctx) {
|
||||
// Workers need the instance model service even when organizations answer another way.
|
||||
const instance = { ...ctx, members: [] };
|
||||
const [service, account, docker] = await Promise.allSettled([modelSetupState[0].check(instance), accountState(ctx.accounts ? instance : ctx), (ctx.docker ?? (() => dockerAnswers({ signal: ctx.signal })))()]);
|
||||
const ready = service.status === 'fulfilled' && service.value?.state === 'done';
|
||||
const connected = account.status === 'fulfilled' ? account.value.state === 'done' ? 'connected' : 'not ready' : 'not checked';
|
||||
const model = typeof ctx.system?.execution?.model === 'string' && !!ctx.system.execution.model.trim();
|
||||
const answers = docker.status === 'fulfilled' && docker.value === true;
|
||||
const ran = ctx.runs ? (await ctx.runs()).some(r => r?.result && typeof r.result === 'object') : hasRunResult(ctx.dataRoot);
|
||||
return { state: ran && answers ? 'done' : 'optional',
|
||||
reason: `A worker needs Docker, a model service, an account and a worker model. Model service: ${ready ? 'ready' : 'not ready'}; Account: ${connected}; Worker model: ${model ? 'chosen' : 'not chosen'}; Docker: ${answers ? 'answering' : 'not answering'}. ${ran ? 'A worker run is recorded.' : 'No worker run is recorded.'} Worker runs start outside the Console.` };
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -122,7 +122,9 @@ export async function checkModel({ system, configDir, uid = process.getuid(), cl
|
||||
if (typeof harness !== 'string' || harness === '') throw new WorkerLaunchError('processing-worker-launch-invalid', 'The config names no worker adapter.');
|
||||
let mgmt = client;
|
||||
if (!mgmt) {
|
||||
try { mgmt = await loadManagementClient({ configDir, proxy: system.proxy }); }
|
||||
// proxy-ride: a riding instance reads the owner instance's management key (same OS user, same
|
||||
// 0600 check) and the owner's model list. Its own worker key stays its own.
|
||||
try { mgmt = await loadManagementClient({ configDir: system.proxy.owner?.configDir ?? configDir, proxy: system.proxy }); }
|
||||
catch (e) { throw passThrough({ code: e?.code ?? 'proxy-management-key-invalid', name: 'TriageKeyError', message: 'the proxy management key file is missing or unsafe' }); }
|
||||
}
|
||||
// The catalogue swallows each client error into "unavailable"; keep the first code to tell a
|
||||
@@ -133,7 +135,7 @@ export async function checkModel({ system, configDir, uid = process.getuid(), cl
|
||||
catch (e) { seen ??= typeof e?.code === 'string' ? e.code : 'proxy-client-response'; throw e; }
|
||||
};
|
||||
const view = { getCredentials: wrap('getCredentials'), getCredentialModels: wrap('getCredentialModels'), getUpstreamGroups: wrap('getUpstreamGroups') };
|
||||
const catalogue = await createModelCatalogue({ client: () => view, settings: () => ({ 'model-provider': ['cliproxy'] }), pluginDataRoot: system.dataRoot }).read('worker', { fresh: true });
|
||||
const catalogue = await createModelCatalogue({ client: () => view, settings: () => ({ 'model-provider': ['cliproxy'] }), pluginDataRoot: system.proxy.owner?.dataRoot ?? system.dataRoot }).read('worker', { fresh: true });
|
||||
if (catalogue.status !== 'ready') throw seen === 'proxy-client-down' ? refuse('proxy-down') : refuse('model-catalogue-unavailable');
|
||||
const entry = catalogue.models.find(m => m.provider === provider && m.model === model) ?? null;
|
||||
const usable = () => {
|
||||
|
||||
@@ -13,7 +13,10 @@ export async function prepareWorker() {
|
||||
}
|
||||
export async function launchWorker({ system, record }) {
|
||||
const managed = registerRuntime(system.dataRoot, record);
|
||||
const proc = mode === 'signal'
|
||||
// 'proxy' (proxy-ride-cli.test.mjs): the answer names the proxy the launch step was given.
|
||||
const proc = mode === 'proxy'
|
||||
? { status: 0, signal: null, stdout: `${system.proxy?.owner?.instance ?? 'no-owner'}:${system.proxy?.port ?? 'no-proxy'}`, stderr: '' }
|
||||
: mode === 'signal'
|
||||
? { status: 0, signal: null, stdout: 'done', stderr: '' }
|
||||
: { status: 1, signal: null, stdout: `answer ${FAKE_KEY}`, stderr: `starting\nerror: the proxy rejected ${FAKE_KEY}\n` };
|
||||
return { proc, managed, haltGeneration: null, modelKeyId: 'a1b2c3d4e5f6', secrets: [FAKE_KEY], signal: mode === 'signal' ? 'SIGTERM' : null };
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// proxy-ride first slice (Jason 2026-11-21): a riding instance's worker model check. The rider's
|
||||
// system.proxy carries `owner`, as scripts/mosaic-config.mjs gives it. The rider holds no
|
||||
// management key of its own; it reads the owner's, and the owner's model on/off list. A stand-in
|
||||
// proxy on 127.0.0.1 port 0 in this process. Nothing here reads a real config, proxy or secret.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import http from 'node:http';
|
||||
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { initializeControl } from '../src/state.mjs';
|
||||
import { WORKER_UID, WorkerLaunchError, checkModel } from '../src/worker-proxy.mjs';
|
||||
import { writeOffered } from '../../model-proxy/src/models-offered.mjs';
|
||||
|
||||
const MANAGE = 'fxride-worker-manage';
|
||||
const UPSTREAM = [{ 'base-url': 'https://api.z.ai/api/anthropic', keys: [{}], models: [{ name: 'fixture-id' }, { name: 'fixture-two' }] }];
|
||||
|
||||
async function fixture(t) {
|
||||
const root = realpathSync(mkdtempSync(join(tmpdir(), 'rw-')));
|
||||
const owner = { configDir: join(root, 'oc'), dataRoot: join(root, 'od') };
|
||||
const rider = { configDir: join(root, 'rc'), dataRoot: join(root, 'rd') };
|
||||
for (const d of [owner.configDir, join(owner.configDir, 'secrets'), owner.dataRoot, rider.configDir, rider.dataRoot]) mkdirSync(d, { recursive: true, mode: 0o700 });
|
||||
writeFileSync(join(owner.configDir, 'secrets', 'proxy-management.key'), MANAGE, { mode: 0o600 });
|
||||
initializeControl(rider.dataRoot);
|
||||
const seen = [];
|
||||
const server = http.createServer((req, res) => {
|
||||
seen.push(req.url);
|
||||
if (req.headers.authorization !== `Bearer ${MANAGE}`) { res.writeHead(401); res.end('{}'); return; }
|
||||
const body = req.url === '/v8/management/config/api-keys/claude' ? UPSTREAM
|
||||
: req.url === '/v8/management/credentials' ? { files: [] } : { models: [] };
|
||||
res.end(JSON.stringify(body));
|
||||
});
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
const port = server.address().port;
|
||||
t.after(async () => { server.closeAllConnections(); await new Promise(r => server.close(r)); rmSync(root, { recursive: true, force: true }); });
|
||||
const execution = { backend: 'docker', provider: 'zai', model: 'fixture-id', adapter: 'pi' };
|
||||
rider.system = { dataRoot: rider.dataRoot, execution, proxy: { port, binary: '/fixture-unused', owner: { instance: 'owner', configDir: owner.configDir, dataRoot: owner.dataRoot } } };
|
||||
return { root, owner, rider, seen };
|
||||
}
|
||||
const check = f => checkModel({ system: f.rider.system, configDir: f.rider.configDir, uid: WORKER_UID });
|
||||
|
||||
test("a rider's model check reads the owner's management key and passes with no key of its own", async t => {
|
||||
const f = await fixture(t);
|
||||
const out = await check(f);
|
||||
assert.equal(out.entry.provider, 'zai'); assert.equal(out.entry.model, 'fixture-id');
|
||||
assert.ok(f.seen.length > 0, 'the check asked the stand-in proxy');
|
||||
});
|
||||
|
||||
test("the owner switching a model off refuses it for the rider; the rider's own data root has no say", async t => {
|
||||
const f = await fixture(t);
|
||||
writeOffered(f.owner.dataRoot, { version: 1, providers: { 'z.ai': { on: ['fixture-two'], seen: ['fixture-id', 'fixture-two'] } } });
|
||||
// The rider's own list would switch it on: only the owner's counts.
|
||||
writeOffered(f.rider.dataRoot, { version: 1, providers: { 'z.ai': { on: ['fixture-id', 'fixture-two'], seen: ['fixture-id', 'fixture-two'] } } });
|
||||
await assert.rejects(check(f), e => {
|
||||
assert.ok(e instanceof WorkerLaunchError, String(e));
|
||||
assert.equal(e.code, 'model-provider-unavailable');
|
||||
assert.equal(e.line, 'zai/fixture-id is switched off. Switch it on in Settings > Model setup.');
|
||||
assert.equal(String(e.message).includes(MANAGE), false);
|
||||
return true;
|
||||
});
|
||||
// The owner switches it back on: the rider passes again.
|
||||
writeOffered(f.owner.dataRoot, { version: 1, providers: { 'z.ai': { on: ['fixture-id', 'fixture-two'], seen: ['fixture-id', 'fixture-two'] } } });
|
||||
assert.equal((await check(f)).entry.model, 'fixture-id');
|
||||
});
|
||||
|
||||
test("a rider whose owner has no management key refuses with the key's code and no request", async t => {
|
||||
const f = await fixture(t);
|
||||
rmSync(join(f.owner.configDir, 'secrets', 'proxy-management.key'));
|
||||
// A key in the rider's own directory is not the one a rider uses.
|
||||
mkdirSync(join(f.rider.configDir, 'secrets'), { mode: 0o700 });
|
||||
writeFileSync(join(f.rider.configDir, 'secrets', 'proxy-management.key'), MANAGE, { mode: 0o600 });
|
||||
await assert.rejects(check(f), e => e instanceof WorkerLaunchError && e.code === 'proxy-management-key-invalid');
|
||||
assert.deepEqual(f.seen, []);
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setupState, dockerAnswers } from '../src/setup-state.mjs';
|
||||
test('workers still inspect the instance service and account when organizations answer without them', async () => {
|
||||
for (const providers of [[], ['fixture']]) {
|
||||
let accountReads = 0;
|
||||
const ctx = { members: [{ id: 'local', doc: { plugins: { 'model-provider': providers } } }],
|
||||
service: async () => ({ release: { verified: true }, init: { initialized: true }, unit: { active: 'active', healthy: true, listening: true } }),
|
||||
accounts: async () => { accountReads++; return { accounts: [{ provider: 'claude', status: 'active' }], catalogue: { status: 'ready', models: [{ upstream: 'claude', available: true }] } }; },
|
||||
read: () => { throw Error('must use the instance account read'); }, docker: async () => false, runs: () => [] };
|
||||
const row = await setupState[0].check(ctx);
|
||||
assert.match(row.reason, /Model service: ready; Account: connected/);
|
||||
assert.equal(accountReads, 1);
|
||||
const missing = await setupState[0].check({ ...ctx, accounts: async () => ({ accounts: [], catalogue: { status: 'ready', models: [] } }) });
|
||||
assert.match(missing.reason, /Model service: ready; Account: not ready/);
|
||||
}
|
||||
});
|
||||
test('worker readiness is optional and names the requirements actually ready', async () => {
|
||||
const ctx = { system: { execution: { model: 'chosen' } }, members: [], dataRoot: '/unused', service: async () => ({ release: { verified: true }, init: { initialized: true }, unit: { active: 'active', healthy: true, listening: true } }), docker: async () => false, runs: () => [] };
|
||||
const row = await setupState[0].check(ctx);
|
||||
assert.equal(setupState[0].required, false); assert.equal(row.state, 'optional');
|
||||
assert.match(row.reason, /Model service: ready/); assert.match(row.reason, /Account: not ready/); assert.match(row.reason, /Worker model: chosen/); assert.match(row.reason, /Docker: not answering/);
|
||||
const done = await setupState[0].check({ ...ctx, docker: async () => true, runs: () => [{ result: { status: 'succeeded' } }] });
|
||||
assert.equal(done.state, 'done');
|
||||
const fenced = await setupState[0].check({ ...ctx, service: async () => ({ ...(await ctx.service()), fence: { set: true } }) });
|
||||
assert.match(fenced.reason, /Model service: not ready/);
|
||||
await assert.rejects(setupState[0].check({ ...ctx, runs: () => { throw Error(); } }));
|
||||
});
|
||||
test('Docker read is short, never starts a container and returns false on failure', async () => {
|
||||
assert.equal(await dockerAnswers({ run: async (command, args, options) => { assert.equal(command, 'docker'); assert.deepEqual(args, ['info', '--format', '{{.ServerVersion}}']); assert.ok(options.timeout <= 1000); return { code: 0 }; } }), true);
|
||||
assert.equal(await dockerAnswers({ run: async () => { throw Error(); } }), false);
|
||||
});
|
||||
import { hasRunResult } from '../src/setup-state.mjs';
|
||||
test('worker evidence stops reading run results after the first recorded result', () => {
|
||||
const reads = [];
|
||||
assert.equal(hasRunResult('/unused', { ids: () => ['r-1', 'r-2', 'r-3'], read: (_, id) => { reads.push(id); return id === 'r-2' ? {} : null; } }), true);
|
||||
assert.deepEqual(reads, ['r-3', 'r-2']);
|
||||
assert.equal(hasRunResult('/unused', { ids: () => [], read: () => { throw Error(); } }), false);
|
||||
});
|
||||
test('Docker receives the request cancellation signal', async () => {
|
||||
const signal = new AbortController().signal;
|
||||
assert.equal(await dockerAnswers({ signal, run: async (_command, _args, options) => { assert.equal(options.signal, signal); return { code: 0 }; } }), true);
|
||||
});
|
||||
@@ -166,7 +166,10 @@ decides authority or capacity; `packages/cli/README.md` ("Sessions") has the
|
||||
launch flow and the on-disk layout.
|
||||
|
||||
- `newRun` picks a run id (`r` and 12 hex digits) and makes its 0700
|
||||
directory, refusing a data root too deep for the run's socket path.
|
||||
directory. The run's tool socket is not at the run directory's host
|
||||
path: the sandbox binds the run's `sock/` at `/run/mosaic`
|
||||
(`TOOL_SOCKET` in `src/sandbox.mjs`), so a deep data root or a long org
|
||||
id can't push it past the 107-byte socket path limit.
|
||||
- `sessionEnv` builds the session's environment from an allowlist
|
||||
(`ENV_ALLOW`), the repository's `node_modules/.bin` on `PATH`, and
|
||||
`MOSAIC_RUN_ID`. Founder credential variables never pass.
|
||||
|
||||
@@ -77,6 +77,15 @@ export const RUNNER_FILES = Object.freeze([
|
||||
"packages/tasks/src/requirements.mjs",
|
||||
].map((p) => join(REPO, p)));
|
||||
|
||||
// The run's tool socket (first-run-fixes-1, B4). A Unix socket path stops at 107 bytes, and the
|
||||
// run directory's host path grows with the data root and twice with the org id
|
||||
// (<dataRoot>/org-runtime/<org>/launches/<org>/r<12 hex>), so a normal org id could fail every
|
||||
// launch. The socket lives in the run directory's sock/ (0700, made with home/ and tmp/), which
|
||||
// binds() mounts at this short fixed path inside the sandbox. Only the runner and the harness it
|
||||
// starts use the socket, and both run inside the sandbox, so the path is the same for every run.
|
||||
export const TOOL_SOCKET_DIR = "/run/mosaic";
|
||||
export const TOOL_SOCKET = `${TOOL_SOCKET_DIR}/tools.sock`;
|
||||
|
||||
const SYSTEM_LINKS = ["/bin", "/lib", "/lib64", "/sbin"];
|
||||
const NAMESPACES = ["--unshare-user", "--unshare-pid", "--unshare-ipc", "--as-pid-1"];
|
||||
|
||||
@@ -138,9 +147,10 @@ export function binds({ runDir, workspace, workspaceDest = null, hidden = [], ad
|
||||
if (!real) throw new Error(`hidden path ${h} is not a directory`);
|
||||
return { kind: "tmpfs", dest: join(workspaceDest ?? workspace, inside), why: "a project checkout this launch may not see, covered by an empty tmpfs" };
|
||||
}),
|
||||
{ kind: "rw", src: runDir, why: "the run directory: turns/, session/, tools.sock, turn.done, home/, tmp/" },
|
||||
{ kind: "rw", src: runDir, why: "the run directory: turns/, session/, sock/, turn.done, home/, tmp/" },
|
||||
{ kind: "ro", src: join(runDir, "bundle"), why: "the run's bundle stays as the host wrote it" },
|
||||
{ kind: "ro", src: join(runDir, "session.json"), why: "the session file stays as the host wrote it" },
|
||||
{ kind: "rw", src: join(runDir, "sock"), dest: TOOL_SOCKET_DIR, why: "the run's sock/ at a short path, so tools.sock fits a socket path whatever the data root and org id" },
|
||||
{ kind: "rw", src: join(runDir, "tmp"), dest: "/tmp", why: "a private /tmp, on disk in the run directory" },
|
||||
);
|
||||
// Row 121: only this thread's store, and only its two directories.
|
||||
@@ -166,10 +176,10 @@ function argsOf(list) {
|
||||
return args;
|
||||
}
|
||||
|
||||
// The run's home/ and tmp/, made before the spawn: binds need their sources.
|
||||
// The run's home/, sock/ and tmp/, made before the spawn: binds need their sources.
|
||||
// A thread run also needs the mount point for its transcripts.
|
||||
export function prepareRun(runDir, { threadStore = null } = {}) {
|
||||
for (const d of ["home", "tmp"]) mkdirSync(join(runDir, d), { recursive: true, mode: 0o700 });
|
||||
for (const d of ["home", "sock", "tmp"]) mkdirSync(join(runDir, d), { recursive: true, mode: 0o700 });
|
||||
if (threadStore) mkdirSync(join(runDir, "home", ".claude", "projects"), { recursive: true, mode: 0o700 });
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
// On disk, under the data root:
|
||||
// launches/<business>/<run>/ the run directory (0700): session.json,
|
||||
// bundle/, session/, turns/, runner.log,
|
||||
// tools.sock, turn.done
|
||||
// sock/tools.sock, turn.done
|
||||
// launches/<business>.jsonl the launch log (0600, append-only):
|
||||
// every launch, refusal and end
|
||||
// workspaces/<business>/<instance>/ the instance's workspace (0700), kept
|
||||
@@ -276,8 +276,9 @@ export function sessionEnv(env, run, proxy = null) {
|
||||
return out;
|
||||
}
|
||||
|
||||
// A new run id and its directory. Ids are short because the run directory
|
||||
// holds a Unix socket (tools.sock), and socket paths stop at 107 bytes.
|
||||
// A new run id and its directory. The run's tool socket no longer sits at
|
||||
// the run directory's host path (sandbox.mjs TOOL_SOCKET), so neither the
|
||||
// data root nor the org id can make a launch fail on the 107-byte limit.
|
||||
export function newRun(dataRoot, business) {
|
||||
const root = runsDir(dataRoot, business);
|
||||
mkdirSync(root, { recursive: true, mode: 0o700 });
|
||||
@@ -290,7 +291,6 @@ export function newRun(dataRoot, business) {
|
||||
if (e.code === "EEXIST") continue;
|
||||
throw e;
|
||||
}
|
||||
if (Buffer.byteLength(join(runDir, "tools.sock")) > 107) throw new SeatError(`data root path too long for a socket: run ${run}`, 2);
|
||||
return { run, runDir };
|
||||
}
|
||||
throw new SeatError("could not pick a free run id", 1);
|
||||
|
||||
@@ -108,13 +108,11 @@ test('a busy session workspace lock names the session, never the lock path', t =
|
||||
assert.throws(() => lockSessionWorkspace(ws, {}), coded('session workspace s1 is busy: its lock is unreadable', root, 'session-workspace-busy'));
|
||||
});
|
||||
|
||||
test('a data root too long for a socket names the run, never its directory', t => {
|
||||
const { root, dir } = scratch(t);
|
||||
assert.throws(() => newRun(join(dir, 'a'.repeat(70)), 'acme'), error => {
|
||||
assert.ok(error instanceof SeatError, error.stack);
|
||||
assert.equal(error.exitCode, 2);
|
||||
assert.match(error.message, /^data root path too long for a socket: run r[0-9a-f]{12}$/);
|
||||
assert.ok(!error.message.includes(root), error.message);
|
||||
return true;
|
||||
});
|
||||
// first-run-fixes-1 (B4): newRun no longer refuses a deep data root (the tool socket sits at a
|
||||
// short path inside the sandbox), so the refusal whose message this test checked is gone.
|
||||
test('a data root too deep for the old socket path gets a run, and no refusal can quote its directory', t => {
|
||||
const { dir } = scratch(t);
|
||||
const { run, runDir } = newRun(join(dir, 'a'.repeat(70)), 'acme');
|
||||
assert.match(run, /^r[0-9a-f]{12}$/);
|
||||
assert.ok(Buffer.byteLength(join(runDir, 'tools.sock')) > 107);
|
||||
});
|
||||
@@ -20,7 +20,7 @@ import { SOURCES } from "../../harness/src/bundle.mjs";
|
||||
import { createLoader } from "../../plugins/src/loader.mjs";
|
||||
import { startTimeOf } from "../src/proc.mjs";
|
||||
import { newRun, RUNNER, runnerOf, sessionEnv, spawnSession, writeSessionFile } from "../src/session.mjs";
|
||||
import { binds, gitIdentity, prepareRun, REPO, RUNNER_FILES, sandboxArgv, sandboxProblem } from "../src/sandbox.mjs";
|
||||
import { binds, gitIdentity, prepareRun, REPO, RUNNER_FILES, sandboxArgv, sandboxProblem, TOOL_SOCKET, TOOL_SOCKET_DIR } from "../src/sandbox.mjs";
|
||||
|
||||
const FAKE = new URL("../../harness/tests/fixtures/fake-adapter.mjs", import.meta.url).pathname;
|
||||
|
||||
@@ -87,6 +87,10 @@ test("every bind says why; the bundle and session file stay read-only over the r
|
||||
assert.ok(at(join(runDir, f)) > at(runDir), `${f} is mounted over the run directory`);
|
||||
}
|
||||
assert.deepEqual(list.at(-1), { kind: "rw", src: join(runDir, "tmp"), dest: "/tmp", why: list.at(-1).why });
|
||||
// first-run-fixes-1 (B4): the run's sock/ at the short fixed path its tool socket uses.
|
||||
assert.equal(TOOL_SOCKET, "/run/mosaic/tools.sock");
|
||||
assert.deepEqual(list[at(join(runDir, "sock"))], { kind: "rw", src: join(runDir, "sock"), dest: TOOL_SOCKET_DIR, why: list[at(join(runDir, "sock"))].why });
|
||||
assert.ok(at(join(runDir, "sock")) > at(runDir));
|
||||
assert.equal(at(join(root, "launch.sock")), -1, "no launch socket for a role that may not launch");
|
||||
assert.equal(at(join(root, "git.sock")), -1, "no git socket for a role that neither pushes nor reviews");
|
||||
assert.ok(!list.some((b) => b.src === realpathSync(join(REPO, "node_modules"))), "no harness mounts unless the module names them");
|
||||
@@ -162,6 +166,7 @@ test("REQ-THREAD-2 a thread store binds its session directory and Claude transcr
|
||||
|
||||
prepareRun(runDir);
|
||||
assert.equal(existsSync(join(runDir, "home", ".claude")), false);
|
||||
assert.equal(statSync(join(runDir, "sock")).mode & 0o777, 0o700, "sock/ is made with home/ and tmp/");
|
||||
prepareRun(runDir, { threadStore: store });
|
||||
assert.equal(statSync(join(runDir, "home", ".claude", "projects")).mode & 0o777, 0o700);
|
||||
});
|
||||
|
||||
@@ -33,7 +33,7 @@ import {
|
||||
threadStore,
|
||||
writeSessionFile,
|
||||
} from "../src/session.mjs";
|
||||
import { BWRAP, sandboxProblem } from "../src/sandbox.mjs";
|
||||
import { BWRAP, sandboxProblem, TOOL_SOCKET } from "../src/sandbox.mjs";
|
||||
|
||||
const FAKE = new URL("../../harness/tests/fixtures/fake-adapter.mjs", import.meta.url).pathname;
|
||||
const skip = sandboxProblem() ?? false;
|
||||
@@ -92,7 +92,7 @@ test("sessionExit gives a runner's signal death back as the signal; a session cr
|
||||
for (const k of SESSION_CREDENTIALS.flat()) assert.ok(ENV_ALLOW.includes(k), k);
|
||||
});
|
||||
|
||||
test("newRun: short ids, 0700 directories, and a refusal when the socket path won't fit", (t) => {
|
||||
test("newRun: short ids, 0700 directories, and no socket refusal for a deep data root or a 64-character org id", (t) => {
|
||||
const root = scratch(t);
|
||||
const a = newRun(join(root, "data"), "acme");
|
||||
const b = newRun(join(root, "data"), "acme");
|
||||
@@ -100,8 +100,12 @@ test("newRun: short ids, 0700 directories, and a refusal when the socket path wo
|
||||
assert.notEqual(a.run, b.run);
|
||||
assert.equal(mode(a.runDir), 0o700);
|
||||
assert.equal(mode(join(root, "data", "launches", "acme")), 0o700);
|
||||
const deep = join(root, "x".repeat(100));
|
||||
assert.throws(() => newRun(deep, "acme"), (e) => e instanceof SeatError && /too long for a socket/.test(e.message));
|
||||
// first-run-fixes-1 (B4): the tool socket is TOOL_SOCKET inside the sandbox, not in the run
|
||||
// directory, so the run directory's host path may pass 107 bytes.
|
||||
const org = "o".repeat(64);
|
||||
const deep = newRun(join(root, "x".repeat(100), "org-runtime", org), org);
|
||||
assert.ok(Buffer.byteLength(join(deep.runDir, "tools.sock")) > 107);
|
||||
assert.equal(mode(deep.runDir), 0o700);
|
||||
});
|
||||
|
||||
test("session file and launch log: 0600, the session file written once", (t) => {
|
||||
@@ -305,3 +309,87 @@ test("a session runs in its sandbox as pid 1 of its namespace, claims, answers,
|
||||
assert.equal(existsSync(join(runDir, "tools.sock")), false);
|
||||
assert.equal(mode(join(runDir, "runner.log")), 0o600);
|
||||
});
|
||||
|
||||
// first-run-fixes-1 (B4): the greenfield walk's org "walkco" failed every chat because the run's
|
||||
// tools.sock passed 107 bytes. The org id appears twice in a launch's run directory
|
||||
// (<dataRoot>/org-runtime/<org>/launches/<org>/r<12 hex>), so here it is the longest id the product
|
||||
// accepts (64 characters) under a long data root. The runner binds its tool socket at TOOL_SOCKET
|
||||
// inside the sandbox, which is the run's sock/ on the host, and answers.
|
||||
test("B4: a 64-character org id under a long data root launches, and its tool socket lives in the run's sock/", { skip }, async (t) => {
|
||||
const root = scratch(t);
|
||||
const org = `o${"x".repeat(62)}9`;
|
||||
assert.equal(org.length, 64);
|
||||
const store = new Store(root);
|
||||
const broker = new Broker({
|
||||
store,
|
||||
businesses: {
|
||||
[org]: {
|
||||
id: org,
|
||||
human: "jason",
|
||||
arbiters: { technical: "pm", delivery: "pm" },
|
||||
roles: {
|
||||
pm: { authority: { withinRole: ["message.send"], crossRole: [] } },
|
||||
coder: { authority: { withinRole: ["message.send"], crossRole: [] } },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const brokerSocket = join(root, "bus.sock");
|
||||
const server = await serve({ broker, path: brokerSocket });
|
||||
t.after(async () => {
|
||||
await server.close().catch(() => {});
|
||||
store.close();
|
||||
});
|
||||
|
||||
const dataRoot = join(root, "home-of-a-user-with-a-long-name", ".mosaic-instance", "org-runtime", org);
|
||||
const { run, runDir } = newRun(dataRoot, org);
|
||||
assert.ok(Buffer.byteLength(join(runDir, "tools.sock")) > 107, "the old socket path would not fit");
|
||||
assert.ok(Buffer.byteLength(TOOL_SOCKET) <= 107);
|
||||
const bundle = join(runDir, "bundle");
|
||||
const ws = join(root, "ws");
|
||||
mkdirSync(bundle, { mode: 0o700 });
|
||||
mkdirSync(ws);
|
||||
writeFileSync(join(bundle, "prompt.md"), "# test\n");
|
||||
writeFileSync(join(bundle, "policy.json"), JSON.stringify({ harness: "pi", workspace: ws, tools: [], typed: [], network: "none", needs: [], credentials: [] }));
|
||||
writeFileSync(join(bundle, "tools.json"), "[]");
|
||||
const adapter = join(root, "adapter.sh");
|
||||
writeFileSync(adapter, `exec '${process.execPath}' '${FAKE}'\n`, { mode: 0o644 });
|
||||
writeSessionFile(runDir, {
|
||||
business: org, instance: "coder", run, launchedBy: "pm", harness: "pi", provider: "fake", model: "fake-model",
|
||||
brokerSocket, launchSocket: join(root, "launch.sock"), workspace: ws, sessionDir: join(runDir, "session"), adapter,
|
||||
bundle: { prompt: join(bundle, "prompt.md"), policy: join(bundle, "policy.json"), tools: join(bundle, "tools.json") },
|
||||
toolSocket: TOOL_SOCKET, turnMarker: join(runDir, "turn.done"), turnEnd: "marker", harnessEnv: {}, pollInterval: 50,
|
||||
});
|
||||
|
||||
const child = spawnSession({ runDir, env: sessionEnv({ HOME: process.env.HOME, PATH: process.env.PATH }, run), paths: { workspace: ws, adapter, brokerSocket, readOnly: [FAKE] }, business: org, role: "coder" });
|
||||
t.after(() => {
|
||||
try {
|
||||
process.kill(child.pid, "SIGKILL");
|
||||
} catch {}
|
||||
});
|
||||
const exited = new Promise((r) => child.once("close", (code, signal) => r({ code, signal })));
|
||||
const runner = await runnerOf(child);
|
||||
const cap = broker.bindLaunch({ business: org, role: "coder", run, harness: "pi", pid: child.pid, startTime: startTimeOf(child.pid) });
|
||||
const pm = broker.bindLaunch({ business: org, role: "pm", run: "pm-run", harness: "pi" });
|
||||
broker.request(pm, { verb: "role.claim" });
|
||||
child.stdin.end(`${JSON.stringify({ cap })}\n`);
|
||||
const sent = broker.request(pm, { verb: "message.send", args: { to: "coder", body: "hello", class: "REQUEST" } });
|
||||
let reply;
|
||||
const end = Date.now() + 15000;
|
||||
while (!reply && Date.now() < end) {
|
||||
reply = broker.request(pm, { verb: "message.receive" }).find((m) => m.in_reply_to === sent.id);
|
||||
if (!reply) await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
assert.ok(reply, "the session answered");
|
||||
assert.equal(mode(join(runDir, "sock")), 0o700);
|
||||
const socket = lstatSync(join(runDir, "sock", "tools.sock"));
|
||||
assert.ok(socket.isSocket(), "the runner's tool socket is in the run's sock/ on the host");
|
||||
assert.equal(socket.mode & 0o777, 0o600);
|
||||
assert.equal(existsSync(join(runDir, "tools.sock")), false, "nothing at the old path");
|
||||
|
||||
const registry = new Registry(dataRoot);
|
||||
registry.add({ business: org, instance: "coder", run, pid: child.pid, startTime: startTimeOf(child.pid), runnerPid: runner.pid, runnerStartTime: runner.startTime });
|
||||
assert.deepEqual(await stopSession(dataRoot, run, { timeoutMs: 10000 }), { stopped: true, business: org, instance: "coder", run });
|
||||
assert.deepEqual(await exited, { code: 0, signal: null });
|
||||
assert.equal(existsSync(join(runDir, "sock", "tools.sock")), false, "the runner removes its socket on exit");
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
export const setupState = Object.freeze([
|
||||
{
|
||||
id: 'tasks.created', title: 'Give your team a first task',
|
||||
purpose: 'Write down one piece of work so your chief has something to plan.',
|
||||
fix: { page: '#/tasks', label: 'New task' },
|
||||
order: { after: ['assistant.replied'] }, required: true,
|
||||
async check(ctx) {
|
||||
const answers = await Promise.allSettled(ctx.members.map(org => ctx.read(org, 'tasks')));
|
||||
const tasks = answers.filter(a => a.status === 'fulfilled' && Array.isArray(a.value));
|
||||
const missed = answers.length - tasks.length;
|
||||
if (tasks.some(a => a.value.length)) return { state: 'done', reason: 'Your team has a task recorded.' + (missed ? " Some organizations couldn't be checked. Open Tasks to check them." : '') };
|
||||
if (missed) return { state: 'next', reason: "Some organizations couldn't be checked. Open Tasks to check them or create your team's first task." };
|
||||
return { state: 'next', reason: 'Create a task with one piece of work for your team.' };
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -0,0 +1,14 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setupState } from '../src/setup-state.mjs';
|
||||
test('first task is evidence of work recorded, not work running', async () => {
|
||||
const check = tasks => setupState[0].check({ members: [{ id: 'team' }], read: async () => tasks });
|
||||
assert.equal((await check([])).state, 'next');
|
||||
assert.equal((await check([{ id: 1, state: 'todo' }])).state, 'done');
|
||||
assert.equal((await setupState[0].check({ members: [] })).state, 'next');
|
||||
assert.match((await check(null)).reason, /couldn't be checked/);
|
||||
assert.match((await setupState[0].check({ members: [{}], read: async () => { throw Error(); } })).reason, /couldn't be checked/);
|
||||
});
|
||||
test('a task in an answering organization counts when another cannot answer', async () => {
|
||||
assert.equal((await setupState[0].check({ members: [{ id: 'bad' }, { id: 'good' }], read: async org => { if (org.id === 'bad') throw Error(); return [{}]; } })).state, 'done');
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
import { setupRoutes } from './setup-http.mjs';
|
||||
import { assertBuildStart, assertDevInstance, assertDeployed } from '../../cli/src/deployment.mjs';
|
||||
// MOSAIC_TESTER_SOCKET_V1: private tester ingress, no tester TCP.
|
||||
import { createChat } from './chat.mjs';
|
||||
@@ -21,7 +22,7 @@ import { listOrgs, resolveOrg } from '../../organization/src/org-registry.mjs';
|
||||
import { showOrg } from '../../organization/src/org-service.mjs';
|
||||
import * as orgService from '../../organization/src/org-service.mjs';
|
||||
import { orgUsesFixture } from '../../cli/src/dev-fixture.mjs';
|
||||
import { moveFixtureOrg, ownerModelsFrom, readRider } from '../../model-proxy/src/ride.mjs';
|
||||
import { moveFixtureOrg, ownerModelsReader, readRider } from '../../model-proxy/src/ride.mjs';
|
||||
import { ownedText } from '../../model-proxy/src/admin.mjs';
|
||||
import { configDir } from '../../organization/src/organization-config.mjs';
|
||||
import { loadRootAgents } from '../../organization/src/agent-levels.mjs';
|
||||
@@ -37,6 +38,7 @@ import { fileURLToPath } from 'node:url';
|
||||
import { isAbsolute, join } from 'node:path';
|
||||
import { actionTrail } from './action-trail.mjs';
|
||||
import { reviveBuses } from './bus-revive.mjs';
|
||||
import { createOwnerProxy } from '../../model-proxy/src/owner-call.mjs';
|
||||
import { createProxyAdmin, orgCatalogue } from './proxy-admin.mjs';
|
||||
import { createTriageHost } from './triage-host.mjs';
|
||||
import { createTriageRoute, triageTokenPattern } from './triage-route.mjs';
|
||||
@@ -117,7 +119,7 @@ try {
|
||||
if (devBind !== null) throw new Error('--dev-insecure-bind takes one address');
|
||||
devBind = value;
|
||||
} else if (flag === '--dev-allow-host') devNames.push(value);
|
||||
// #1873: where the Proxy page installs the proxy user unit; proxy-service.sh's default otherwise.
|
||||
// #1873: where the Model setup page installs the proxy user unit; proxy-service.sh's default otherwise.
|
||||
else if (flag === '--proxy-unit-dir') {
|
||||
if (!isAbsolute(value)) throw new Error('--proxy-unit-dir must be an absolute path');
|
||||
options.proxyUnitDir = value;
|
||||
@@ -246,12 +248,12 @@ try {
|
||||
}
|
||||
return out;
|
||||
};
|
||||
// The owner's models (ride.mjs ownerModelsFrom): the proxy is set up when proxy.json names a port.
|
||||
const ownerModels = system && (devOwner || ssoOn) ? async () => {
|
||||
let proxy = false;
|
||||
try { proxy = Number.isInteger(loadProxy(configDir(), system.dataRoot)?.port); } catch {}
|
||||
return ownerModelsFrom({ proxy, riders: proxy ? await rideRiders() : [] });
|
||||
} : null;
|
||||
const ownerProxy = system && (devOwner || ssoOn) ? createOwnerProxy({ dataRoot: system.dataRoot, configDir: configDir() }) : null;
|
||||
// The proxy is set up when proxy.json names a port; organization mode uses the owner catalogue.
|
||||
const ownerModels = system && (devOwner || ssoOn) ? ownerModelsReader({
|
||||
proxy: () => Number.isInteger(loadProxy(configDir(), system.dataRoot)?.port),
|
||||
organizations, ownerProxy, rideRiders,
|
||||
}) : null;
|
||||
// Each active organization's bus `routes` catalogue, every one asked at once, so a hung bus costs
|
||||
// one timeout, not one each. A bus that does not answer gives a catalogue that is not ready, so it
|
||||
// confirms nothing. Triage's route checks and the Worker model card read the same list.
|
||||
@@ -265,6 +267,7 @@ try {
|
||||
}));
|
||||
};
|
||||
const proxyAdmin = system && (devOwner || ssoOn) ? createProxyAdmin({
|
||||
ownerProxy,
|
||||
dataRoot: system.dataRoot, configDir: configDir(), instance, unitDir: options.proxyUnitDir ?? null,
|
||||
buses: () => busesStopped({ dataRoot: system.dataRoot, configDir: configDir() }),
|
||||
orgs: async () => {
|
||||
@@ -360,7 +363,7 @@ try {
|
||||
catalogues: routeCatalogues,
|
||||
})] : [];
|
||||
try {
|
||||
server = await startServer({ restart, trail, ...(lan ? { host: lan.bind, devAllowHosts: lan.allowHosts } : {}), board: options.board, port: options.port, bus, reads, preview: options.preview, sso, proof, send, settingsWrite, projectFiles, projectFile, libraryFile, libraryStatus, librarySync, libraryRevert, librarySave, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, proxyAdmin, triage, processing, decisionWrite, requestRead, requestWrite, userOptions, federation: system?.federation ?? null, organizations, agentLevels, ownerModels, rideRemoved: proxyAdmin ? id => proxyAdmin.rideRemoved(id) : null, routes: [...agentLevelRoutes, ...triageRoutes], preselect: options.business ?? null });
|
||||
server = await startServer({ restart, trail, ...(lan ? { host: lan.bind, devAllowHosts: lan.allowHosts } : {}), board: options.board, port: options.port, bus, reads, preview: options.preview, sso, proof, send, settingsWrite, projectFiles, projectFile, libraryFile, libraryStatus, librarySync, libraryRevert, librarySave, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, proxyAdmin, triage, processing, decisionWrite, requestRead, requestWrite, userOptions, federation: system?.federation ?? null, organizations, agentLevels, ownerModels, rideRemoved: proxyAdmin ? id => proxyAdmin.rideRemoved(id) : null, routes: [setupRoutes({ organizations, proxyAdmin, system, dataRoot: system?.dataRoot, configDir: configDir(), instance, unitDir: options.proxyUnitDir ?? null }), ...agentLevelRoutes, ...triageRoutes], preselect: options.business ?? null });
|
||||
} catch (err) { sso?.close(); throw err; }
|
||||
if (testerSocket) {
|
||||
const call = busCaller({ dataRoot: system.dataRoot, socket: socketPath(system.dataRoot), business: options.business ?? null, cli: TESTER_CLI });
|
||||
|
||||
@@ -64,9 +64,9 @@ const HIRE_START_REFUSALS = {
|
||||
'model-catalogue-unavailable': [503, 'The model catalogue could not be read, so this model could not be checked. Check Settings > Model setup, then try again.' + NONE],
|
||||
'model-harness-incompatible': [409, 'This model does not run on the chosen harness. Pick another model or harness.' + NONE],
|
||||
'thinking-unsupported': [409, 'The chosen harness does not apply this thinking level. Clear Thinking or pick a level it applies.' + NONE],
|
||||
'unknown-model': [409, 'This model is not one of the organization\'s models. Pick a model listed under Settings > Routing.' + NONE],
|
||||
'harness-off': [409, 'This harness is not switched on for the organization. Pick a harness listed under Settings > Routing, or ask the owner to switch it on.' + NONE],
|
||||
'harness-refused': [409, 'The harness refused this route. Clear Thinking, or pick another model or harness under Settings > Routing.' + NONE],
|
||||
'unknown-model': [409, 'This model is not one of the organization\'s models. Pick a model listed under Settings > Models.' + NONE],
|
||||
'harness-off': [409, 'This harness is not switched on for the organization. Pick a harness listed under Settings > Models, or ask the owner to switch it on.' + NONE],
|
||||
'harness-refused': [409, 'The harness refused this route. Clear Thinking, or pick another model or harness under Settings > Models.' + NONE],
|
||||
'template-system-only': [409, 'This role template is for the system, not for an organization. Pick another template.' + NONE],
|
||||
'definition-not-hireable': [409, 'This organization does not hire agents from this role template. Pick another template.' + NONE],
|
||||
'definition-shared': [409, 'Another agent uses the same role definition, so this change cannot replace it.' + NONE],
|
||||
@@ -100,7 +100,7 @@ const HIRE_START_REFUSALS = {
|
||||
'credential-scope-exceeded': [409, 'The requested credential scope is wider than the role allows.' + CHECK],
|
||||
// The fields passed the shape check below, so a malformed answer here is a value the organization
|
||||
// checks refused: most often a model that is not a launch.models key.
|
||||
'invalid-request': [400, 'The bus refused a value in this proposal. Pick a model listed under Settings > Routing and a role the organization checks accept.' + EITHER],
|
||||
'invalid-request': [400, 'The bus refused a value in this proposal. Pick a model listed under Settings > Models and a role the organization checks accept.' + EITHER],
|
||||
};
|
||||
// A reply the endpoint cannot read as a definite answer: no answer, or the bus server's request
|
||||
// codes. Anything else that reads as a code is a definite refusal.
|
||||
|
||||
@@ -27,8 +27,8 @@
|
||||
// handler returns false for them.
|
||||
|
||||
import { open } from 'node:fs/promises';
|
||||
import { pickModel, usableModel } from '../../model-proxy/src/ride.mjs';
|
||||
import { lstatSync } from 'node:fs';
|
||||
import { pickModel, usableModel, ownerModelsAvailable } from '../../model-proxy/src/ride.mjs';
|
||||
import { lstatSync, readFileSync } from 'node:fs';
|
||||
import { checkProject, initProject, projectRepo, recordContext } from '../../project/src/index.mjs';
|
||||
import { refuseInsideAgent } from '../../cli/src/transport.mjs';
|
||||
import { join } from 'node:path';
|
||||
@@ -286,7 +286,7 @@ function refusal(res, error, { step, id, unknownOk = false }) {
|
||||
// Default service wiring: the real C1/C2/C3 modules, loaded on first use.
|
||||
// A missing module (a branch without S1 yet) answers not-configured.
|
||||
async function load(spec) { try { return await import(spec); } catch (e) { if (e?.code === 'ERR_MODULE_NOT_FOUND') return null; throw e; } }
|
||||
export function defaultOrgAdmin(env = process.env, { ownerModels = null, rideRemoved = null } = {}) {
|
||||
export function defaultOrgAdmin(env = process.env, { ownerModels = null, rideRemoved = null, devFixture = null } = {}) {
|
||||
let system = null;
|
||||
// The same context `mosaic org` builds (packages/cli/src/org.mjs): the named
|
||||
// instance from MOSAIC_CONFIG, its data root and its config directory.
|
||||
@@ -301,7 +301,7 @@ export function defaultOrgAdmin(env = process.env, { ownerModels = null, rideRem
|
||||
return system;
|
||||
};
|
||||
return createOrgAdmin({
|
||||
ownerModels, rideRemoved: rideRemoved ?? removalRecorder(context),
|
||||
ownerModels, rideRemoved: rideRemoved ?? removalRecorder(context), devFixture: devFixture ?? fixtureState(context),
|
||||
service: () => load('../../organization/src/org-service.mjs'),
|
||||
registry: () => load('../../organization/src/org-registry.mjs'),
|
||||
bus: () => load('../../cli/src/org-bus.mjs'),
|
||||
@@ -320,19 +320,43 @@ export function removalRecorder(context) {
|
||||
};
|
||||
}
|
||||
|
||||
// first-run-fixes-1 (B2): whether the instance's dev fixture can answer a chat, read from the
|
||||
// record `mosaic dev fixture init` writes (cli dev-fixture.mjs readFixture): ready when the record
|
||||
// names this instance and its endpoint process still runs. No record, a record the launcher would
|
||||
// refuse, or an endpoint that has exited reads not ready. With no context it says nothing.
|
||||
// Review P3-2: the endpoint is matched by the tail of its script path, so a fixture started from
|
||||
// another checkout than the Console's own copy still reads ready. `mosaic dev fixture stop` keeps
|
||||
// the exact match (dev-fixture.mjs isEndpoint), since it signals the process; this only reads.
|
||||
// The default instance has no context here and keeps the old offer (devOwnerInstance refuses it).
|
||||
const FIXTURE_TAIL = '/plugins/model-provider/fixture/endpoint.mjs';
|
||||
const runsFixture = pid => { try { const script = readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0')[1]; return typeof script === 'string' && script.endsWith(FIXTURE_TAIL); } catch { return false; } };
|
||||
export function fixtureState(context) {
|
||||
return async () => {
|
||||
const ctx = await context(), dev = await load('../../cli/src/dev-fixture.mjs');
|
||||
if (!ctx?.dataRoot || !dev) return undefined;
|
||||
let record; try { record = dev.readFixture(ctx.dataRoot); } catch { return { ready: false }; }
|
||||
return { ready: !!record && record.instance === ctx.instance && runsFixture(record.pid) };
|
||||
};
|
||||
}
|
||||
|
||||
// `service`, `registry` and `bus` are module objects or functions returning
|
||||
// them (or null when absent). `context()` gives { configDir, dataRoot, instance }.
|
||||
// `ownerModels()` (#1873 ride-default) answers {proxy, riding, models} from the owner's model
|
||||
// proxy, read through the riding buses; without it the cliproxy preset reads unavailable.
|
||||
// proxy: the root owner in organization mode reads the owner catalogue; other callers read
|
||||
// riding buses. An optional `catalogue` names owner read readiness. No read writes setup state.
|
||||
// `rideRemoved(id)` records in the proxy's receipts that a save took cliproxy off the organization,
|
||||
// so Ride all leaves it off; without it such a save is refused.
|
||||
export function createOrgAdmin({ service, registry = null, bus = null, context, ownerModels = null, rideRemoved = null }) {
|
||||
// `devFixture()` (first-run-fixes-1 B2) answers {ready} for the instance's dev fixture; without it
|
||||
// the Test model preset is offered as before. A failing read is not ready.
|
||||
export function createOrgAdmin({ service, registry = null, bus = null, context, ownerModels = null, rideRemoved = null, devFixture = null }) {
|
||||
const get = async x => (typeof x === 'function' ? x() : x);
|
||||
const owner = async () => { if (typeof ownerModels !== 'function') return { proxy: false, riding: false, models: [] }; try { return await ownerModels(); } catch { return { proxy: false, riding: false, models: [] }; } };
|
||||
return { service: () => get(service), registry: () => get(registry), bus: () => get(bus), context: () => get(context), ownerModels: owner, rideRemoved };
|
||||
const fixture = async () => { if (typeof devFixture !== 'function') return undefined; try { return await devFixture(); } catch { return { ready: false }; } };
|
||||
return { service: () => get(service), registry: () => get(registry), bus: () => get(bus), context: () => get(context), ownerModels: owner, rideRemoved, devFixture: fixture };
|
||||
}
|
||||
const providersOf = doc => (Array.isArray(doc?.plugins?.['model-provider']) ? doc.plugins['model-provider'] : []);
|
||||
const ownerOf = admin => (typeof admin.ownerModels === 'function' ? admin.ownerModels() : { proxy: false, riding: false, models: [] });
|
||||
const fixtureOf = admin => (typeof admin.devFixture === 'function' ? admin.devFixture() : undefined);
|
||||
|
||||
// The handler. Returns true when it answered. `owner` is the signed-in owner
|
||||
// session (provider, iss, sub) or null; `send` says --send is on; `origin` is
|
||||
@@ -434,7 +458,16 @@ async function route(req, res, { path, search, org, admin, principal, write, log
|
||||
if (path === '/api/org-presets' && !write) {
|
||||
if (new URLSearchParams(search).size) return json(res, 422, { error: 'invalid', message: 'unexpected query parameter' });
|
||||
const service = await need(admin, 'service', res, 'presets'); if (!service) return;
|
||||
try { return json(res, 200, { presets: await service.orgPresets({ owner: await ownerOf(admin) }) }); }
|
||||
try {
|
||||
const owner = await ownerOf(admin);
|
||||
const presets = await service.orgPresets({ owner, fixture: await fixtureOf(admin) });
|
||||
// One read supplies availability and the choices. Put the existing default first.
|
||||
const models = ownerModelsAvailable(owner).ok ? owner.models.filter(usableModel) : [];
|
||||
const chosen = pickModel(models);
|
||||
return json(res, 200, { presets: presets.map(p => p.name === 'cliproxy' && chosen ? { ...p,
|
||||
models: [chosen, ...models.filter(m => m.key !== chosen.key)].map(m => ({ key: m.key, label: m.label || m.model })),
|
||||
} : p) });
|
||||
}
|
||||
catch (e) { return refusal(res, e, { step: 'presets' }); }
|
||||
}
|
||||
if (path === '/api/org-template' && !write) {
|
||||
@@ -449,7 +482,7 @@ async function route(req, res, { path, search, org, admin, principal, write, log
|
||||
let model;
|
||||
if (params.get('preset') === 'cliproxy') {
|
||||
const owner = await ownerOf(admin), models = Array.isArray(owner?.models) ? owner.models : [];
|
||||
model = params.has('model') ? models.find(m => usableModel(m) && m.key === params.get('model')) : (owner?.proxy === true && owner?.riding === true ? pickModel(models) : null);
|
||||
model = !ownerModelsAvailable(owner).ok ? null : params.has('model') ? models.find(m => usableModel(m) && m.key === params.get('model')) : pickModel(models);
|
||||
if (!model) return json(res, 422, { error: 'invalid', step: 'template', errors: [{ path: '$.model', field: 'model', message: params.has('model') ? 'the model proxy lists no such model' : 'the model proxy lists no model you can use' }] });
|
||||
}
|
||||
let doc;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// #1873 model proxy setup from the Console: the owner-only HTTP routes. Same checks as
|
||||
// proxy-http.mjs. The controller (packages/model-proxy/src/admin-control.mjs) runs host
|
||||
// actions; init and the fence clear go to the bus, which decides them. No key, token, path or
|
||||
// upstream text reaches a response, receipt or log line.
|
||||
// actions; init and the fence clear use the instance owner transport or selected bus. No key,
|
||||
// token or upstream text reaches a response, receipt or log line. Unit refusals may name a file.
|
||||
import { isIP } from 'node:net';
|
||||
import { validManagementKey, proxyTiming } from '../../model-proxy/src/common.mjs';
|
||||
import { createProxyAdmin, proxyCode } from '../../model-proxy/src/admin-control.mjs';
|
||||
@@ -47,6 +47,7 @@ const ROUTES = Object.freeze({
|
||||
// organization's proxy client key health. The program list itself is in status.
|
||||
'/api/proxy/admin/programs/off': ['POST', ['name']],
|
||||
'/api/proxy/admin/access': ['GET', []],
|
||||
'/api/proxy/admin/undo': ['POST', []],
|
||||
// #1873 account-remove (Jason 2026-11-20): what removing one account takes away, then the remove.
|
||||
'/api/proxy/admin/accounts/impact': ['GET', ['account']],
|
||||
'/api/proxy/admin/accounts/remove': ['POST', ['accountId']],
|
||||
@@ -135,6 +136,7 @@ export async function proxyAdminHTTP(req, res, { path, admin, call, named, teste
|
||||
}
|
||||
try {
|
||||
switch (path) {
|
||||
case '/api/proxy/admin/undo': return done(200, await admin.undo());
|
||||
case '/api/proxy/admin/status': return done(200, await admin.status());
|
||||
case '/api/proxy/admin/unit/render': return done(200, await admin.render());
|
||||
case '/api/proxy/admin/fetch': return done(202, admin.fetchStart());
|
||||
@@ -190,7 +192,7 @@ export async function proxyAdminHTTP(req, res, { path, admin, call, named, teste
|
||||
}
|
||||
} catch (error) {
|
||||
const code = ['human-required', 'not-configured', 'invalid-request'].includes(error?.code) ? error.code : proxyCode(error, 'outcome-unknown');
|
||||
return refuse(code);
|
||||
return done(STATUS[code] ?? 400, { error: code, ...(['proxy-unit-exists', 'proxy-unit-missing'].includes(code) && typeof error.ownerMessage === 'string' ? { message: error.ownerMessage } : {}) });
|
||||
}
|
||||
return done(404, { error: 'not found' });
|
||||
}
|
||||
@@ -13,6 +13,8 @@ const routes = Object.freeze({
|
||||
'/api/proxy/priority/set': ['POST', 'proxy.priority.set', ['accountId', 'priority']],
|
||||
'/api/proxy/group/models/set': ['POST', 'proxy.group.models.set', ['accountId', 'models']],
|
||||
});
|
||||
// Only these instance account routes belong to Model setup. Routing stays on its bus.
|
||||
export const OWNER_PROXY_PATHS = Object.freeze(Object.entries(routes).filter(([, route]) => route[1].startsWith('proxy.')).map(([path]) => path));
|
||||
const codes = ['not-configured', 'human-required', 'provider-not-allowed', 'login-state-unknown',
|
||||
'callback-url-invalid', 'apikey-invalid', 'priority-invalid', 'priority-unconfirmed', 'priority-write-refused', 'models-invalid', 'models-ambiguous', 'models-write-refused', 'models-unconfirmed', 'proxy-down', 'invalid-request'];
|
||||
const json = (res, status, value) => {
|
||||
|
||||
@@ -41,11 +41,11 @@
|
||||
const running=Array.isArray(e.running)?e.running:[], alive=Array.isArray(e.alive)?e.alive:[];
|
||||
const menu=open?`<button type="button" class="agent-more" aria-haspopup="menu" aria-expanded="false" aria-label="More actions for ${esc(name)}"${off}>⋯</button><div class="agent-menu" role="menu" hidden>${!c.isTester&&!e.protected?`<button type="button" role="menuitem" data-agent-edit="${esc(name)}">Edit</button>`:''}<button type="button" role="menuitem" data-agent-dialog="end" data-agent-name="${esc(name)}">Terminate…</button>${!c.isTester?`<button type="button" role="menuitem" data-agent-dialog="regenerate" data-agent-name="${esc(name)}">Regenerate…</button>${button(e.kept?'unkeep':'keep',name,e.kept?'Unkeep':'Keep')}${!e.endProtected?`<hr><button type="button" role="menuitem" class="agent-danger" data-agent-dialog="delete" data-agent-name="${esc(name)}">Delete…</button>`:''}`:''}</div>`:'';
|
||||
const d=c.instanceDrafts.change?.instance===name?c.instanceDrafts.change:{};
|
||||
const editor=editing===name?`<tr class="agent-editor"><td colspan="6"><form id="instance-change-form" class="instance-form" data-op="change"><input type="hidden" data-instance-field="instance" value="${esc(name)}"><label>Definition <select data-instance-field="definition"${changeOff}>${option(name,d.definition,'Keep the definition')}</select></label>${v.launch?`<label>Launch <select data-instance-field="launch"${changeOff}><option value="">Keep</option><option value="yes"${d.launch==='yes'?' selected':''}>Launch it</option><option value="no"${d.launch==='no'?' selected':''}>Don't launch it</option></select></label>`:''}<details id="instance-change-vars"><summary>Vars as JSON</summary><p>Harness, model and thinking are set in Routing.</p><label><span class="sr-only">Vars as JSON</span><textarea data-instance-field="vars" rows="3"${changeOff}>${esc(d.vars??'')}</textarea></label></details><div class="settings-actions${c.instanceDrafts.change?' has-draft':''}">${instanceStatus('change')}<button type="submit"${changeOff}>${c.instanceBusyOps.includes('change')?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Save agent'}</button><button type="button" data-instance-discard${c.instanceDrafts.change?'':' hidden'}${changeOff}>Discard draft</button></div></form></td></tr>`:'';
|
||||
const editor=editing===name?`<tr class="agent-editor"><td colspan="6"><form id="instance-change-form" class="instance-form" data-op="change"><input type="hidden" data-instance-field="instance" value="${esc(name)}"><label>Definition <select data-instance-field="definition"${changeOff}>${option(name,d.definition,'Keep the definition')}</select></label>${v.launch?`<label>Launch <select data-instance-field="launch"${changeOff}><option value="">Keep</option><option value="yes"${d.launch==='yes'?' selected':''}>Launch it</option><option value="no"${d.launch==='no'?' selected':''}>Don't launch it</option></select></label>`:''}<details id="instance-change-vars"><summary>Vars as JSON</summary><p>Harness, model and thinking are set in ${window.MosaicOrg?'Models':'Routing'}.</p><label><span class="sr-only">Vars as JSON</span><textarea data-instance-field="vars" rows="3"${changeOff}>${esc(d.vars??'')}</textarea></label></details><div class="settings-actions${c.instanceDrafts.change?' has-draft':''}">${instanceStatus('change')}<button type="submit"${changeOff}>${c.instanceBusyOps.includes('change')?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Save agent'}</button><button type="button" data-instance-discard${c.instanceDrafts.change?'':' hidden'}${changeOff}>Discard draft</button></div></form></td></tr>`:'';
|
||||
return `<tr><th scope="row">${txt(name)}</th><td headers="agent-col-definition"><span class="agent-mobile-label" aria-hidden="true">Definition: </span>${txt(e.definition)}</td><td headers="agent-col-launch"><span class="agent-mobile-label" aria-hidden="true">Launch: </span>${e.launcher?'Launcher':e.launched?'Yes':'No'}</td><td headers="agent-col-kept"><span class="agent-mobile-label" aria-hidden="true">Kept: </span>${e.kept?'Yes':'No'}</td><td headers="agent-col-running"><span class="agent-mobile-label" aria-hidden="true">Running: </span>${running.length?running.map(r=>`<code>${txt(r)}</code>`).join(' '):'<span class="muted">None</span>'}${alive.map(r=>` <strong class="agent-alive">still running after fire: <code>${txt(r)}</code></strong>`).join('')}</td><td class="agent-actions">${threadDefinitions.has(e.definition)?'<span class="agent-start-hint">Starts when you message it</span>':open?button('launch',name,'Launch'):''}${menu}</td></tr>${editor}`;
|
||||
}).join('');
|
||||
const d=c.instanceDrafts.add||{}, bound=defs.filter(n=>Array.isArray(v.definitions[n].services)&&v.definitions[n].services.length).map(n=>`${txt(n)} (${v.definitions[n].services.map(txt).join(', ')})`);
|
||||
const add=!c.isTester&&open?`<section class="panel"><h3>Add an agent</h3><form id="instance-add-form" class="instance-form" data-op="add"><div class="filters"><label>Name <input data-instance-field="instance" value="${esc(d.instance??'')}" maxlength="64"${addOff}></label><label>Definition <select data-instance-field="definition"${addOff}>${option('',d.definition,'Choose a definition')}</select></label>${v.launch?`<label><input type="checkbox" data-instance-field="launch"${d.launch?' checked':''}${addOff}> Launch it</label>`:''}</div><details id="instance-add-vars"><summary>Vars as JSON</summary><p>Harness, model and thinking are set in Routing.</p><label><span class="sr-only">Vars as JSON</span><textarea data-instance-field="vars" rows="3"${addOff}>${esc(d.vars??'')}</textarea></label></details><div class="settings-actions${c.instanceDrafts.add?' has-draft':''}">${instanceStatus('add')}<button type="submit"${addOff}>${c.instanceBusyOps.includes('add')?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Add agent'}</button><button type="button" data-instance-discard${c.instanceDrafts.add?'':' hidden'}${addOff}>Discard draft</button></div></form>${bound.length?`<p>Definitions that declare credentials are a hand edit: ${bound.join(', ')}.</p>`:''}</section>`:'';
|
||||
const add=!c.isTester&&open?`<section class="panel"><h3>Add an agent</h3><form id="instance-add-form" class="instance-form" data-op="add"><div class="filters"><label>Name <input data-instance-field="instance" value="${esc(d.instance??'')}" maxlength="64"${addOff}></label><label>Definition <select data-instance-field="definition"${addOff}>${option('',d.definition,'Choose a definition')}</select></label>${v.launch?`<label><input type="checkbox" data-instance-field="launch"${d.launch?' checked':''}${addOff}> Launch it</label>`:''}</div><details id="instance-add-vars"><summary>Vars as JSON</summary><p>Harness, model and thinking are set in ${window.MosaicOrg?'Models':'Routing'}.</p><label><span class="sr-only">Vars as JSON</span><textarea data-instance-field="vars" rows="3"${addOff}>${esc(d.vars??'')}</textarea></label></details><div class="settings-actions${c.instanceDrafts.add?' has-draft':''}">${instanceStatus('add')}<button type="submit"${addOff}>${c.instanceBusyOps.includes('add')?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Add agent'}</button><button type="button" data-instance-discard${c.instanceDrafts.add?'':' hidden'}${addOff}>Discard draft</button></div></form>${bound.length?`<p>Definitions that declare credentials are a hand edit: ${bound.join(', ')}.</p>`:''}</section>`:'';
|
||||
const noHire=Array.isArray(v.noHire)?v.noHire:[], retired=Array.isArray(v.retired)?v.retired:[];
|
||||
const hiring=!c.isTester?`<section class="panel"><h3>Hiring</h3><p>Turn hiring off to stop new agents of a definition.</p><div class="hiring-grid">${defs.map(n=>`<div>${open?`<button type="button" role="switch" aria-label="Hiring allowed for ${esc(n)}" aria-checked="${!noHire.includes(n)}" data-agent-action="${noHire.includes(n)?'hire':'nohire'}" data-agent-name="${esc(n)}"${off}><span class="switch-track"></span></button>`:`<span>${noHire.includes(n)?'Off':'On'}</span>`}<span class="hiring-name">${txt(n)}</span></div>`).join('')}</div>${retired.length?`<p>Retired names, never reused: ${retired.map(txt).join(', ')}.</p>`:''}</section>`:'';
|
||||
const state=pending?`<p id="agents-pending">Request <code>${txt(pending.request)}</code> to ${txt(pending.action)} ${txt(pending.instance)}: ${txt(pending.state)}.</p>`:'';
|
||||
|
||||
@@ -165,6 +165,8 @@
|
||||
document.dispatchEvent(new CustomEvent('mosaic-theme-change', {detail: {palette: current.theme, mode: current.mode, stored: true, warning: null, picked: current.theme}}));
|
||||
// The open organization's saved appearance, read again when another organization opens (#1873 SP1).
|
||||
const readBusiness = async () => {
|
||||
await window.MosaicOrg?.ready;
|
||||
if (document.documentElement.hasAttribute('data-organizations') && !window.MosaicOrg?.id) return;
|
||||
try {
|
||||
const { ok, body } = await getJSON('/api/business');
|
||||
if (ok && orgId(body?.business?.id)) return window.MosaicAppearance.organization(body.business.id, body.business.appearance, body.business.id);
|
||||
@@ -505,6 +507,8 @@
|
||||
// good load, from the status `mosaic bus start` left. textContent only. Nothing here retries.
|
||||
async function busDown() {
|
||||
const box = $('bus-down');
|
||||
await window.MosaicOrg?.ready;
|
||||
if (document.documentElement.hasAttribute('data-organizations') && !window.MosaicOrg?.id) { box.hidden = true; return; }
|
||||
// E2E5 review P2: the organization list is read first and on its own, so a failed bus-status read
|
||||
// (likely when the bus is down) still refreshes the list, its banner and the Settings Start control.
|
||||
// #1873 SP1: the dashboard lists every organization's bus on its own rows; this banner is an organization page's.
|
||||
@@ -664,5 +668,5 @@
|
||||
setTimeout(() => { const a = document.activeElement; if (!a || a === document.body || a.disabled || !a.getClientRects().length) line.focus(); });
|
||||
});
|
||||
// Sign out (sage-1347, F7): a plain same-origin form POST to /auth/logout, shown only under --sso.
|
||||
api('/api/config').then(config => { board = config.board || 'unknown'; $('board-url').textContent = config.board ? `Board: ${board}` : 'No board'; window.MosaicFederation?.render(config.federation, $('federation')); if (config.sso === true) { sso = true; $('sign-out').hidden = out(); $('local-sign-out').hidden = true; $('avatar-name').textContent = 'Operator'; $('avatar-button').querySelector('.avatar-initial').textContent = 'O'; } }).catch(err => { if (machine) error(err); }).finally(refresh);
|
||||
api('/api/config').then(config => { board = config.board || 'unknown'; $('board-url').hidden = document.documentElement.hasAttribute('data-organizations'); $('board-url').textContent = $('board-url').hidden ? '' : config.board ? `Board: ${board}` : 'No board'; window.MosaicFederation?.render(config.federation, $('federation')); if (config.sso === true) { sso = true; $('sign-out').hidden = out(); $('local-sign-out').hidden = true; $('avatar-name').textContent = 'Operator'; $('avatar-button').querySelector('.avatar-initial').textContent = 'O'; } }).catch(err => { if (machine) error(err); }).finally(refresh);
|
||||
})();
|
||||
@@ -1193,7 +1193,7 @@
|
||||
const name=Object.hasOwn(nameDrafts,instance)?nameDrafts[instance]:named?.[instance]??'';
|
||||
const busy=kind=>assistantFormsBusy.has(assistantKey(instance,kind)), disabledFor=kind=>!canSend||out()||busy(kind)?' disabled':'', disabled=disabledFor('settings'), nameDisabled=disabledFor('name'), stopDisabled=disabledFor('stop');
|
||||
const status=kind=>{const text=assistantCardReceipts[assistantKey(instance,kind)]||'', current=(assistantReceiptKinds[instance]||'settings')===kind;return `<p role="status" data-assistant-kind="${kind}"${current?` data-assistant-receipt="${k}"`:''} class="${text.startsWith('Outcome unknown')?'banner ref':text.includes('Draft kept')?'banner err':text.includes('saved')||text.startsWith('Seat name set')||text.startsWith('Stopped')?'settings-success':''}">${txt(text)}</p>`;};
|
||||
return `<form class="assistant-form" data-instance="${k}"><section class="panel"><h3>Seat name</h3><p>The name people see for this seat.</p><div class="filters"><label>Seat name <input data-assistant-field="name" value="${esc(name)}" maxlength="64" placeholder="No name set"${nameDisabled}></label><button type="button" data-assistant-name="${k}"${nameDisabled}>${busy('name')?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Save name'}</button>${named?'':' <span class="small muted">The current name could not be read.</span>'}</div>${status('name')}</section><section class="panel"><h3>Settings</h3><label>Definition <input data-assistant-field="definition" value="${esc(val('definition'))}" maxlength="64"${disabled}></label><label>Vars as JSON <textarea data-assistant-field="vars" rows="4"${disabled}>${esc(val('vars'))}</textarea></label><p>Harness, model and thinking are set in Routing.</p><label>Tracker as JSON <textarea data-assistant-field="tracker" rows="4"${disabled}>${esc(val('tracker'))}</textarea></label><p>Leave empty to remove the tracker.</p><div class="settings-actions${assistantDrafts[instance]||Object.hasOwn(nameDrafts,instance)?' has-draft':''}"><button type="submit"${disabled}>${busy('settings')?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Save assistant settings'}</button><button type="button" data-assistant-discard="${k}"${assistantDrafts[instance]||Object.hasOwn(nameDrafts,instance)?'':' hidden'}${busy('settings')?' disabled':''}>Discard draft</button>${status('settings')}</div></section><section class="panel"><h3>Runs</h3><p>Stop ends the runs of your threads. The assistant starts again when you next write to it.</p><button type="button" class="agent-danger" data-assistant-stop="${k}"${stopDisabled}>${busy('stop')?'<span class="settings-spinner" aria-hidden="true"></span> Stopping…':'Stop its runs'}</button>${status('stop')}</section></form>`;
|
||||
return `<form class="assistant-form" data-instance="${k}"><section class="panel"><h3>Seat name</h3><p>The name people see for this seat.</p><div class="filters"><label>Seat name <input data-assistant-field="name" value="${esc(name)}" maxlength="64" placeholder="No name set"${nameDisabled}></label><button type="button" data-assistant-name="${k}"${nameDisabled}>${busy('name')?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Save name'}</button>${named?'':' <span class="small muted">The current name could not be read.</span>'}</div>${status('name')}</section><section class="panel"><h3>Settings</h3><label>Definition <input data-assistant-field="definition" value="${esc(val('definition'))}" maxlength="64"${disabled}></label><label>Vars as JSON <textarea data-assistant-field="vars" rows="4"${disabled}>${esc(val('vars'))}</textarea></label><p>Harness, model and thinking are set in ${routingLabel()}.</p><label>Tracker as JSON <textarea data-assistant-field="tracker" rows="4"${disabled}>${esc(val('tracker'))}</textarea></label><p>Leave empty to remove the tracker.</p><div class="settings-actions${assistantDrafts[instance]||Object.hasOwn(nameDrafts,instance)?' has-draft':''}"><button type="submit"${disabled}>${busy('settings')?'<span class="settings-spinner" aria-hidden="true"></span> Saving…':'Save assistant settings'}</button><button type="button" data-assistant-discard="${k}"${assistantDrafts[instance]||Object.hasOwn(nameDrafts,instance)?'':' hidden'}${busy('settings')?' disabled':''}>Discard draft</button>${status('settings')}</div></section><section class="panel"><h3>Runs</h3><p>Stop ends the runs of your threads. The assistant starts again when you next write to it.</p><button type="button" class="agent-danger" data-assistant-stop="${k}"${stopDisabled}>${busy('stop')?'<span class="settings-spinner" aria-hidden="true"></span> Stopping…':'Stop its runs'}</button>${status('stop')}</section></form>`;
|
||||
}).join('');
|
||||
return `<div aria-labelledby="settings-page-title">${forms}</div>`;
|
||||
}
|
||||
@@ -1565,6 +1565,8 @@
|
||||
// #1873 settings slice 4 (DESIGN.md section 2): four groups. You; Your models; All organizations;
|
||||
// This organization, whose heading holds the organization picker. An organization's own pages carry
|
||||
// ?org=<id> so the address base never changes with the organization. Testers keep their short list.
|
||||
// first-run-fixes-1 (F10): the routing page's name in the nav, for text that points to it.
|
||||
const routingLabel = () => (window.MosaicOrg && !isTester ? 'Models' : 'Routing');
|
||||
const ORG_SETTINGS = ['routing','agents','limits','tokens','assistant','business','names'];
|
||||
function settingsShell(page, body, helper='') {
|
||||
const org = window.MosaicOrg, orgId = org?.id ?? null, orgName = orgId ? (org.label || orgId) : null;
|
||||
@@ -1580,7 +1582,7 @@
|
||||
const picker = org && rows.length ? `<div class="settings-group org-pick"><label for="org-pick">This organization</label><select id="org-pick">${rows.map(r => `<option value="${txt(r.id)}"${r.id === orgId ? ' selected' : ''}>${txt(r.label)}</option>`).join('')}</select></div>` : `<div class="settings-group">${org ? 'This organization' : 'This business'}</div>`;
|
||||
const links = isTester ? group('Settings', ['appearance','business','routing','agents','names'])
|
||||
: group('You', ['appearance']) + group('Your models', ['model-setup', ...(triageOwner ? ['triage'] : [])]) + group(org ? 'All organizations' : 'This instance', ['organizations','console','about'])
|
||||
+ picker + ['routing','agents','limits','tokens','assistant','business'].map(a).join('');
|
||||
+ (document.documentElement.hasAttribute('data-organizations') && !orgId ? '' : picker + ['routing','agents','limits','tokens','assistant','business'].map(a).join(''));
|
||||
const where = orgName && scoped(page) ? `${txt(orgName)} · ` : '';
|
||||
const title = org && page === 'routing' && orgName ? `${txt(orgName)}'s models` : label;
|
||||
return `${head('Settings','Your models, your organizations and this browser.')}<div class="settings-layout"><div><button type="button" id="settings-disclosure" aria-expanded="false" aria-controls="settings-nav"><small>Section</small><strong>${where}${label}${isDirty(page)?dot:''}</strong><span aria-hidden="true">⌄</span></button><nav id="settings-nav" aria-label="Settings sections">${links}</nav></div><div class="settings-content settings-${page}${readonlyPage(page)?' readonly':''}"><h2 id="settings-page-title" tabindex="-1">${title}</h2><p class="settings-helper">${helper}</p>${readonlyPage(page)?'<p class="settings-readonly">Read only. Saving requires signed-in send mode.</p>':''}${body}</div></div>`;
|
||||
@@ -1588,7 +1590,7 @@
|
||||
async function settingsView(get, page='appearance') {
|
||||
if (page==='business') return businessView(get);
|
||||
if (page==='appearance') return settingsShell(page,appearance(),'These choices apply in this browser only.');
|
||||
if (page==='organizations') { await configRead; return settingsShell(page,window.MosaicOrgCreate.markup,'Create an organization from the template, edit it, and finish its setup. Each step names the command it equals.'); }
|
||||
if (page==='organizations') { await configRead; return settingsShell(page,window.MosaicOrgCreate.markup,'Choose who answers, then create your organization and finish setting it up.'); }
|
||||
if (page==='model-setup') { await configRead; return settingsShell(page,window.MosaicProxy.markup,'Your model service, your accounts and the models they offer. Every organization uses them, including organizations you add later, unless it sets up its own.'); }
|
||||
// #1873 triage-settings: Settings > Triage (triage-settings.js), the instance owner's only; anyone else gets no page.
|
||||
if (page==='triage') { await configRead; if (!triageOwner || !window.MosaicTriageRoute) return notFound(); return settingsShell(page,await window.MosaicTriageRoute.section(),'The model Triage uses, what runs it, and its daily token limit. Only the instance owner sees this page.'); }
|
||||
@@ -1606,7 +1608,7 @@
|
||||
if (page==='tokens' && s.launch && !s.launch.refused) takeSnapshot(s.launch);
|
||||
const notify = typeof n.binding==='string' ? `<code>${txt(n.binding)}</code>` : n.refused ? `Could not be read: <code>${txt(n.refused)}</code>` : '<span class="muted">None set</span>';
|
||||
const contents={limits:()=>launchForm(s.launch),routing:()=>routesSection(routes,instances),agents:()=>agentsSection(instances)+agentLevels,assistant:()=>assistantSection(s.launch,names),tokens:()=>tokenLimits(limitRows,limitsRefused)+tokenUsage(usage),names:()=>testerNames(names,instances),about:()=>`<section class="panel"><dl class="kv"><dt>Address</dt><dd><code>${txt(s.address)||'unknown'}</code></dd><dt>Release</dt><dd>${txt(s.release)||'unknown'}</dd><dt>Business</dt><dd>${txt(s.business)||none}</dd><dt>Board</dt><dd><code>${txt(s.board)||'unknown'}</code></dd><dt>Notifier binding</dt><dd>${notify}</dd></dl></section>`};
|
||||
const helpers={limits:'Leave a limit blank for no limit. Zero stops new launches. Running sessions keep running when limits or models change.',routing:"Each agent’s harness, model and thinking, and the fallback a launch takes when the primary harness fails its preflight. A fallback sets all three or none. Running sessions keep their route. The next launch reads the change. A harness is the program that runs the model. Preflight is the check a launch makes before it starts.",agents:'Each agent with its definition, launch membership and runs. A launch refuses until the agent has a route in Routing.',assistant:'The definition stays an assistant one. Holder and credentials stay hand edits.',tokens:'Token limits the bus checks, and token use read from session transcripts.'};
|
||||
const helpers={limits:'Leave a limit blank for no limit. Zero stops new launches. Running sessions keep running when limits or models change.',routing:"Each agent’s harness, model and thinking, and the fallback a launch takes when the primary harness fails its preflight. A fallback sets all three or none. Running sessions keep their route. The next launch reads the change. A harness is the program that runs the model. Preflight is the check a launch makes before it starts.",agents:'Each agent with its definition, launch membership and runs. A launch refuses until the agent has a route in '+routingLabel()+'.',assistant:'The definition stays an assistant one. Holder and credentials stay hand edits.',tokens:'Token limits the bus checks, and token use read from session transcripts.'};
|
||||
// settings-s5 review P2-2: the header says where the models come from only from the plugins read.
|
||||
const riding=harnessSettings?(harnessSettings.plugins?.['model-provider']??[]).includes('cliproxy'):null;
|
||||
if(window.MosaicOrg&&!isTester)helpers.routing=`The models ${modelsWhose()} agents use.${riding===true?' They come from your accounts in Model setup.':riding===false?' They come from its own organization file.':''} ${helpers.routing}`;
|
||||
|
||||
@@ -366,6 +366,8 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date(
|
||||
// `#/orgs/<id>/...` is a route inside the same page, not a mode: opening another organization
|
||||
// changes the scope of later /api reads and fires `mosaic-org-switch`. Nothing reloads.
|
||||
// Requests already sent keep the organization they were sent with.
|
||||
// Model setup belongs to the instance owner, before any organization exists.
|
||||
const modelSetupFetch = (input, init) => window.fetch(new URL(input, location.href).href, init);
|
||||
(() => {
|
||||
const nativeFetch = window.fetch.bind(window);
|
||||
// SP13: the organization segment stops at `/` or `?`, so `#/orgs/<id>?agent=…` names <id>.
|
||||
@@ -595,6 +597,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
+ '<p id="proxy-setup-message" role="status" aria-live="polite"></p>'
|
||||
// settings-s5b: the lines come from GET /api/proxy/admin/log, read when the box opens (readLog in the controller).
|
||||
+ '<details id="proxy-setup-lines" class="proxy-setup-lines" hidden><summary>The service\'s last lines</summary><div class="inside" data-log></div></details>'
|
||||
+ '<button type="button" id="proxy-setup-undo" class="btn" hidden>Remove unfinished setup</button>'
|
||||
+ '<div id="proxy-setup-fixtures" class="banner mk-note" hidden></div>';
|
||||
const accounts = '<p id="proxy-message" role="status" aria-live="polite">Reading accounts…</p>'
|
||||
+ '<p class="small muted">Model setup has not checked whether a model answers.</p>'
|
||||
@@ -688,7 +691,8 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
const root = $('proxy-setup');
|
||||
let canWrite = false, login = null, poll = null, accountList = null, accountsDown = null;
|
||||
const busy = new Set(), priorityReceipts = new Map(), opened = new Set();
|
||||
const wanted = new URLSearchParams(location.hash.split('?')[1] ?? '').get('step');
|
||||
const wantedParam = new URLSearchParams(location.hash.split('?')[1] ?? '').get('step');
|
||||
const wanted = ({ 1: 'service', 2: 'accounts' })[wantedParam] ?? wantedParam;
|
||||
if (STEP_KEYS.includes(wanted)) opened.add(wanted);
|
||||
let scrolled = false;
|
||||
const message = (text, loginOnly = false) => { $(loginOnly ? 'proxy-login-message' : 'proxy-message').textContent = text; };
|
||||
@@ -729,7 +733,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
scrolled = true; box.scrollIntoView({ block: 'start' });
|
||||
}
|
||||
async function call(path, args) {
|
||||
const response = await fetch('/api/proxy/' + path, { cache: 'no-store', credentials: 'same-origin',
|
||||
const response = await (proxyAdmin ? modelSetupFetch : fetch)('/api/proxy/' + path, { cache: 'no-store', credentials: 'same-origin',
|
||||
method: args === undefined ? 'GET' : 'POST',
|
||||
...(args === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(args) }),
|
||||
});
|
||||
@@ -778,7 +782,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
'human-required': 'Only the instance owner removes an account.',
|
||||
};
|
||||
async function adminCall(path, args) {
|
||||
const response = await fetch('/api/proxy/admin/' + path, { cache: 'no-store', credentials: 'same-origin', redirect: 'manual',
|
||||
const response = await modelSetupFetch('/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 new Error('Sign in to the Console again.');
|
||||
let value = null; try { value = await response.json(); } catch { /* refused below */ }
|
||||
@@ -933,7 +937,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
// 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',
|
||||
const response = await modelSetupFetch('/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 */ }
|
||||
@@ -1168,7 +1172,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
// until the chain starts, which clears them before any request is answered.
|
||||
const setup = (() => {
|
||||
const form = $('proxy-setup-init');
|
||||
let state = null, timer = null, enabled = false, sendOk = false, seenFetch = null, loading = false;
|
||||
let state = null, timer = null, enabled = false, sendOk = false, organizationMode = false, seenFetch = null, loading = false;
|
||||
// #1873 settings slice 1 (D1): the steps after "accounts" come from what this page reads itself:
|
||||
// the account count (refresh), the organizations in the status, and the Triage route.
|
||||
let accountCount = null, triageSet = null;
|
||||
@@ -1197,21 +1201,24 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
'proxy-restart-unconfirmed': 'The restart could not be confirmed on the host. Restart again.',
|
||||
'proxy-init-lock-held': 'The init lock cannot be cleared yet.',
|
||||
'proxy-init-lock-absent': 'There is no init lock.',
|
||||
'proxy-unit-exists': 'A different proxy unit file is installed. Check it with mosaic proxy unit render.',
|
||||
'proxy-unit-exists': 'This service file does not match a file Mosaic wrote for this instance. Nothing was replaced. Ask the person who installed it to move it aside, then try again.',
|
||||
'proxy-unit-dropin': 'A service override exists beside this unit file. Nothing was changed. Ask the instance administrator to check it and any system-wide or user service overrides.',
|
||||
'proxy-unit-missing': 'The model service is not installed.',
|
||||
'proxy-unit-unhealthy': 'The model service started but does not answer on its port.',
|
||||
'proxy-unit-failed': 'systemd refused the action.',
|
||||
'proxy-unit-failed': 'The user service manager refused the action. Try again, or remove this unfinished setup and start clean.',
|
||||
'proxy-setup-in-use': 'This model service has finished setup, is running, has connected accounts or client keys, or is used by an organization or another instance. It cannot be removed as unfinished setup.',
|
||||
'proxy-setup-remove-refused': 'Mosaic could not prove this setup is unused and safe to remove. Nothing more was removed. Ask the instance administrator to check it.',
|
||||
'not-configured': 'Model service setup is not available on this Console.',
|
||||
'outcome-unknown': 'The outcome is unknown. Check the status before retrying.',
|
||||
};
|
||||
const explain = code => `${Object.hasOwn(REASONS, code) ? REASONS[code] : 'The action was refused.'} (${code})`;
|
||||
const explain = code => Object.hasOwn(REASONS, code) ? REASONS[code] : 'The action was refused. Check the service details, then try again.';
|
||||
async function admin(path, args) {
|
||||
const response = await fetch('/api/proxy/admin/' + path, { cache: 'no-store', credentials: 'same-origin', redirect: 'manual',
|
||||
const response = await modelSetupFetch('/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 new Error('Sign in to the Console again.');
|
||||
let value = null; try { value = await response.json(); } catch { /* refused below */ }
|
||||
if (!response.ok) { const code = typeof value?.error === 'string' && /^[a-z -]+$/.test(value.error) ? value.error : 'outcome-unknown'; const error = new Error(explain(code)); error.code = code; throw error; }
|
||||
if (!response.ok) { const code = typeof value?.error === 'string' && /^[a-z -]+$/.test(value.error) ? value.error : 'outcome-unknown'; const error = new Error(typeof value?.message === 'string' ? value.message : explain(code)); error.code = code; throw error; }
|
||||
return value;
|
||||
}
|
||||
const say = (text, kind) => receipt('proxy-setup-message', text, kind);
|
||||
@@ -1314,7 +1321,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
'account.proxy.group.models.set': n(entry.models, 'model') ? `Models chosen for an account, ${n(entry.models, 'model')}` : 'Models chosen for an account',
|
||||
'account.remove': provider ? `${provider} account removed` : 'Account removed',
|
||||
fetch: 'Release downloaded and checked', init: 'Set up', 'init-lock.clear': 'Stale setup lock cleared', 'fence.clear': 'Key writes resumed',
|
||||
'unit.install': 'Service installed', 'unit.start': 'Started', 'unit.stop': 'Stopped', 'unit.restart': 'Restarted',
|
||||
'setup.undo': 'Unfinished setup removed', 'unit.install': 'Service file 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',
|
||||
@@ -1381,7 +1388,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
row(dl, 'Release', !release.fetched ? `Not fetched (pinned ${release.version}, panel ${release.panelVersion})` : release.verified ? `Fetched ${release.version}, panel ${release.panelVersion}, hashes verified` : `Fetched ${release.version}, hashes not verified (${release.problem})`);
|
||||
const files = init.files.filter(f => f.present).map(f => f.label).join(', ') || 'none';
|
||||
row(dl, 'Initialized', init.initialized ? `Yes, port ${init.settings?.port ?? '—'}${timeouts(init.settings)}` : init.partial ? `Partly (${init.problem ?? 'incomplete'}). Present: ${files}` : init.problem ? `No (${init.problem})` : 'No');
|
||||
row(dl, 'Service', `${unit.unit}: ${unit.installed ? 'installed' : 'not installed'}, ${unit.active}${unit.pid ? `, pid ${unit.pid}` : ''}${unit.port ? `, port ${unit.port} ${unit.listening ? 'answering' : 'not answering'}` : ''}${unit.error ? ` (${unit.error})` : ''}`);
|
||||
row(dl, 'Service', `${unit.unit}: ${unit.installed ? 'service file installed' : 'not installed'}, ${unit.active}${unit.pid ? `, pid ${unit.pid}` : ''}${unit.port ? `, port ${unit.port} ${unit.listening ? 'answering' : 'not answering'}` : ''}${unit.problem ? `. ${unit.problem}` : ''}${unit.error ? ` (${unit.error})` : ''}`);
|
||||
row(dl, 'Fence', !fence.set ? 'Clear' : fence.invalid ? 'Set (unreadable fence file)' : `Set after ${fence.op ?? 'a key write'}${fence.org ? ` for ${fence.org}` : ''}${fence.time ? ` at ${window.MosaicLocalTime(fence.time)}` : ''}`);
|
||||
row(dl, 'Init lock', !initLock.present ? 'None' : initLock.clearable ? 'Stale: the bus is stopped and no model service files exist' : `Held: ${initLock.blockers.join('; ')}`);
|
||||
if (state.restart?.confirmed) row(dl, 'Last restart', `Confirmed at ${window.MosaicLocalTime(state.restart.observedAt)}, new pid ${state.restart.pid}`);
|
||||
@@ -1425,6 +1432,9 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
// Card 1, Model service.
|
||||
function paintService() {
|
||||
const next = state.next?.[0], box = $('proxy-setup-next'), lines = $('proxy-setup-lines');
|
||||
const undo = $('proxy-setup-undo');
|
||||
undo.hidden = next === 'accounts' || !(state.init?.initialized || state.init?.partial || state.initLock?.present || state.unit?.installed);
|
||||
undo.disabled = !sendOk || Boolean(state.busy) || Boolean(chain?.running);
|
||||
const ok = progressDone(), some = Object.values(ok).some(Boolean), fetching = state.fetch?.state === 'running';
|
||||
paintFixtures(next !== 'accounts');
|
||||
if (next === 'accounts') { setCard('service', 'done', state.unit.port ? `Running. Service reachable on this machine, port ${state.unit.port}.` : 'Running. Service reachable on this machine.'); box.replaceChildren(); paintProgress(false); lines.hidden = true; return; }
|
||||
@@ -1432,10 +1442,10 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
setCard('service', 'work', chain?.running ? 'Setting up. Keep this page open; if you leave, Continue setup picks up from here.' : 'Downloading the release. Keep this page open.');
|
||||
box.replaceChildren(goButton('Working…', next, true, () => {})); paintProgress(true); lines.hidden = true; return;
|
||||
}
|
||||
let failed = chain?.failed ?? null;
|
||||
let failed = chain?.failed ?? (state.stoppedSetup ? { at: state.stoppedSetup.at, reason: state.stoppedSetup.reason ?? explain(state.stoppedSetup.code) } : null);
|
||||
if (!failed && next === 'fetch' && state.fetch?.state === 'failed') failed = { at: 'fetch', reason: `The download failed. ${explain(state.fetch.error)}` };
|
||||
if (failed && (CHAIN.includes(next) || next === 'unit-restart')) {
|
||||
setCard('service', 'bad', `${failed.reason} The steps that finished are kept. No organization was touched.`, { badge: ['badge-danger', 'Setup stopped'] });
|
||||
setCard('service', 'bad', `Setup stopped while ${{ fetch: 'downloading and checking the program', init: 'configuring the service', 'unit-install': 'installing the service file', 'unit-start': 'starting the service', 'unit-restart': 'restarting the service', answer: 'checking the service' }[failed.at] ?? 'setting up the service'}. ${failed.reason} The steps that finished are kept. No organization was touched.`, { badge: ['badge-danger', 'Setup stopped'] });
|
||||
box.replaceChildren(el('p', 'Try again starts from the step that failed.', 'small muted'), goButton('Try again', next, !sendOk || Boolean(state.busy), runChain));
|
||||
paintProgress(true);
|
||||
if (lines.hidden) { lines.hidden = false; lines.open = true; readLog(); }
|
||||
@@ -1444,7 +1454,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
lines.hidden = true;
|
||||
if (CHAIN.includes(next)) {
|
||||
const fresh = next === 'fetch' && !some;
|
||||
setCard('service', 'next', fresh ? 'Lets your agents use the accounts you sign in to. It runs on this machine and takes about a minute to set up.' : 'Setup is partly done. Continue setup picks up from the step that is not done yet.');
|
||||
setCard('service', 'next', fresh ? 'Downloads the pinned program and installs a user service on this computer. Nothing leaves this machine until you connect an account. It takes about a minute to set up.' : 'Setup is partly done. Continue setup picks up from the step that is not done yet.');
|
||||
box.replaceChildren(goButton(state.busy ? 'Working…' : fresh ? 'Set up model service' : 'Continue setup', next, !sendOk || Boolean(state.busy), runChain));
|
||||
paintProgress(!fresh); return;
|
||||
}
|
||||
@@ -1584,7 +1594,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
// Why the list is not known: no organization to ask, the model service off in each one, or
|
||||
// a list that could not be read (a bus or the proxy down).
|
||||
const unread = v.catalogue === 'none' ? 'No organization is active' : v.catalogue === 'disabled' ? 'No organization has the model service on' : 'No organization\'s model list could be read';
|
||||
how.textContent = v.canSave === true ? '' : 'Choosing the worker model on this page is not built yet. To change it, edit execution.provider and execution.model in the config.';
|
||||
how.textContent = v.canSave === true ? '' : 'Choosing the model for background work on this page is not available yet. Ask the person who manages this installation to change it.';
|
||||
list.replaceChildren(...(Array.isArray(v.models) && v.models.length
|
||||
? v.models.map(m => { const li = el('li'); li.append(el('strong', id(m.provider, m.model))); if (m.label && m.label !== id(m.provider, m.model)) li.append(' ', el('span', m.label, 'small muted')); return li; })
|
||||
: [el('li', !v.takesModel ? 'None. This adapter takes no model.' : v.catalogue === 'ready' ? `None. No account serves a model for ${harness} that is switched on and is not a Claude model.` : `Not known. ${unread}.`, 'muted')]));
|
||||
@@ -1593,30 +1603,30 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
setCard('worker', 'done', 'Worker runs use the mock adapter, which takes no model.'); return;
|
||||
}
|
||||
if (!v.using) {
|
||||
using.textContent = 'No worker model is set.'; standing.textContent = 'Worker runs refuse to start until execution.provider and execution.model are set in the config.';
|
||||
setCard('worker', 'bad', 'No worker model is set. Set execution.provider and execution.model in the config.'); return;
|
||||
using.textContent = 'No worker model is set.'; standing.textContent = 'Background work cannot start until the person who manages this installation chooses a model.';
|
||||
setCard('worker', 'bad', 'No model is set for background work. Ask the person who manages this installation to choose one.'); return;
|
||||
}
|
||||
const name = id(v.using.provider, v.using.model);
|
||||
using.replaceChildren(...(v.using.from === 'config'
|
||||
? ['Worker runs use ', el('strong', name), '. The config names it (execution.provider and execution.model), and the config always wins.']
|
||||
: ['Worker runs use ', el('strong', name), ', the choice saved for Model setup, because the config names no worker model.']));
|
||||
? ['Worker runs use ', el('strong', name), '. It is set for this installation and takes priority over a choice saved here.']
|
||||
: ['Worker runs use ', el('strong', name), ', the choice saved here. No model is set for background work in this installation.']));
|
||||
// [card kind, the card's one line after the name, the line in the body]
|
||||
const STANDING = {
|
||||
usable: ['done', '', `An account serves it for ${harness}, and it is switched on.`],
|
||||
off: ['bad', 'It is switched off.', 'It is switched off, so worker runs refuse to start. Switch it on under Accounts and models, Models offered, or name another model in the config.'],
|
||||
off: ['bad', 'It is switched off.', 'It is switched off, so background work cannot start. Switch it on under Accounts and models, Models offered, or ask the person who manages this installation to choose another model.'],
|
||||
'not-served': ['bad', `No account serves it for ${harness}.`, `No account serves it for ${harness} now, so worker runs refuse to start.`],
|
||||
'claude-model': ['bad', 'It is a Claude model.', 'It is a Claude model. Claude models run only in the Claude harness, so worker runs refuse to start.'],
|
||||
unknown: ['off', 'Whether it can run is not known.', `${unread}, so whether it can run now is not known.`],
|
||||
unset: ['bad', 'The config names only half of it.', 'The config names only one of execution.provider and execution.model, so worker runs cannot start.'],
|
||||
unset: ['bad', 'The model choice is incomplete.', 'The model choice is incomplete, so background work cannot start. Ask the person who manages this installation to finish choosing a model.'],
|
||||
};
|
||||
const [kind, short, line] = STANDING[v.using.standing] ?? ['off', 'Whether it can run is not known.', 'Whether it can run now is not known.'];
|
||||
standing.textContent = line;
|
||||
if (v.choice?.state === 'set' && v.using.from === 'config') {
|
||||
choice.hidden = false;
|
||||
choice.textContent = `A choice saved earlier (${id(v.choice.provider, v.choice.model)}) has no effect while the config names a worker model.`;
|
||||
choice.textContent = `A choice saved earlier (${id(v.choice.provider, v.choice.model)}) has no effect while this installation has its own model set for background work.`;
|
||||
} else if (v.choice?.state === 'unreadable') {
|
||||
choice.hidden = false;
|
||||
choice.textContent = v.using.from === 'config' ? 'A choice saved earlier cannot be read. It has no effect while the config names a worker model.' : 'A choice saved earlier cannot be read.';
|
||||
choice.textContent = v.using.from === 'config' ? 'A choice saved earlier cannot be read. It has no effect while this installation has its own model set for background work.' : 'A choice saved earlier cannot be read.';
|
||||
}
|
||||
setCard('worker', kind, short ? `Worker runs use ${name}. ${short}` : `Worker runs use ${name}.`, kind === 'off' ? { badge: ['badge-muted', 'Unknown'] } : {});
|
||||
}
|
||||
@@ -1896,7 +1906,9 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
'not-available': 'Moving is not available on this Console.',
|
||||
fixture: 'It uses stand-in models.',
|
||||
};
|
||||
const rideReason = code => RIDE_REASONS[code] ?? `The change was refused (${code}).`;
|
||||
const rideReason = code => code === 'no-riding-bus' && organizationMode
|
||||
? 'Your models could not be checked. Open Model setup to try again.'
|
||||
: RIDE_REASONS[code] ?? `The change was refused (${code}).`;
|
||||
let rideResult = null;
|
||||
const rideSkips = () => rideResult?.skipped ?? (Array.isArray(state?.ride) ? state.ride : []).filter(r => !['ready', 'already', 'fixture'].includes(r.state)).map(r => ({ id: r.id, reason: r.state }));
|
||||
// What the Ride all box lists that still needs a step: organizations that can ride, skipped ones and
|
||||
@@ -1967,7 +1979,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
// True once the answer is painted, so a caller can say the list on the page is the new one.
|
||||
async function load({ onError } = {}) {
|
||||
if (!enabled || loading) return false; loading = true; let painted = false;
|
||||
try { state = await admin('status'); setProviders(state.providers); causeRound++; if (state.next?.[0] === 'accounts' && triageSet === null) await readTriage(); paint(); painted = true; if (state.init.initialized) await accountsReady(); }
|
||||
try { state = await admin('status'); setProviders(state.providers); causeRound++; if (state.next?.[0] === 'accounts' && triageSet === null) await readTriage(); paint(); painted = true; if (state.next?.[0] === 'accounts') await accountsReady(); }
|
||||
catch (error) { say(error.message, 'error'); if (providerKey === null) setProviders(null); onError?.(error); }
|
||||
finally { loading = false; }
|
||||
return painted;
|
||||
@@ -2025,6 +2037,13 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
await load();
|
||||
}
|
||||
}
|
||||
$('proxy-setup-undo').addEventListener('click', () => {
|
||||
if ($('proxy-setup-undo').disabled || !window.confirm('Remove this unfinished model service setup? Mosaic stops and removes only its own service file and unfinished state. The downloaded program and history stay. Connected accounts or organizations prevent removal.')) return;
|
||||
return act('undo', async () => {
|
||||
await admin('undo', {}); chain = null;
|
||||
say('Unfinished setup removed. You can set it up again.', 'success');
|
||||
});
|
||||
});
|
||||
const clearLock = () => act('init-lock-clear', async () => { const result = await admin('init-lock/clear', {}); addReceipt(result.receipt); say('Stale init lock cleared.', 'success'); });
|
||||
const unitAction = op => act(`unit-${op}`, async () => {
|
||||
const result = await admin(`unit/${op}`, {}); addReceipt(result.receipt);
|
||||
@@ -2040,7 +2059,7 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
});
|
||||
root.querySelectorAll('[data-unit]').forEach(button => button.addEventListener('click', () => { if (!button.disabled) unitAction(button.dataset.unit); }));
|
||||
return {
|
||||
start(config) { enabled = true; sendOk = config.proxyAdminSend === true; return load(); },
|
||||
start(config) { enabled = true; organizationMode = Object.hasOwn(config, 'orgSetup'); sendOk = config.proxyAdminSend === true; return load(); },
|
||||
accounts(n) { accountCount = n; if (state) { paintService(); paintRestart(); paintOrgsCard(); paintTriageCard(); } },
|
||||
// A sign-in, a key or a restart can change the next step: read the whole status again.
|
||||
async reread(options) { if (!enabled) return; triageSet = null; await load(options); },
|
||||
@@ -2074,11 +2093,12 @@ if (document.documentElement.hasAttribute('data-settings-proxy-document') && !lo
|
||||
window.addEventListener('pagehide', cleanup, {once:true});
|
||||
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 => {
|
||||
modelSetupFetch('/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;
|
||||
canWrite = (config.send === true || config.settingsSend === true || config.proxyAdminSend === true) && config.tester !== true && config.user !== true;
|
||||
devOwner = config.devOwner === true;
|
||||
proxyAdmin = config.proxyAdmin === true; offeredSend = proxyAdmin && config.proxyAdminSend === true;
|
||||
if (offeredSend) { const content = root.closest('.settings-model-setup'); content?.classList.remove('readonly'); content?.querySelector(':scope > .settings-readonly')?.remove(); }
|
||||
applyWrite();
|
||||
root.classList.toggle('solo', !proxyAdmin);
|
||||
if (proxyAdmin) { root.querySelectorAll('[data-admin]').forEach(part => { part.hidden = false; }); setup.start(config); }
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
<link rel="stylesheet" href="/processing.css"><script src="/processing.js" defer></script>
|
||||
<link rel="stylesheet" href="/org-create.css"><script src="/org-create.js" defer></script>
|
||||
<link rel="stylesheet" href="/onboarding.css"><script src="/onboarding.js" defer></script><link rel="stylesheet" href="/assistant.css">
|
||||
<link rel="stylesheet" href="/setup-checklist.css"><script src="/setup-checklist.js" defer></script>
|
||||
<script src="/workspace-data.js" defer></script><script src="/workspace.js" defer></script><script src="/tasks-board.js" defer></script><script src="/console-restart.js" defer></script><script src="/triage-settings.js" defer></script><script src="/display.js" defer></script><script src="/inbox.js" defer></script><script src="/files.js" defer></script><script src="/project-remote.js" defer></script><link rel="stylesheet" href="/autonomy.css"><script src="/autonomy.js" defer></script><link rel="stylesheet" href="/packs.css"><script src="/packs.js" defer></script><link rel="stylesheet" href="/workflows.css"><script src="/workflows.js" defer></script><script src="/federation.js" defer></script><script src="/brand.js" defer></script><script src="/app.js" defer></script><script src="/markdown-preview.js" defer></script><script src="/projects.js" defer></script><script src="/chat.js" defer></script><script src="/project-archive.js" defer></script><script src="/agents.js" defer></script><script src="/assistant.js" defer></script><script src="/bus.js" defer></script><script src="/requests.js" defer></script></head>
|
||||
<body>
|
||||
<div hidden aria-hidden="true"><select id="palette"></select><select id="mode"><option value="system">system</option><option value="light">light</option><option value="dim">dim</option><option value="dark">dark</option></select></div>
|
||||
|
||||
@@ -7,9 +7,24 @@
|
||||
// E2E6 minor: a command shown as "Same as" wraps between words, never inside a flag such as
|
||||
// --if-revision. Each word is an inline-block; one longer than the line still breaks inside itself.
|
||||
const cmd = v => `<code>${String(v ?? '').split(' ').map(w => `<span class="cmd-word">${txt(w)}</span>`).join(' ')}</code>`;
|
||||
const commandLine = v => `<details class="org-verb"><summary>Command line</summary>${cmd(v)}</details>`;
|
||||
// #1873 P1-6: the remote check a repository receipt records, in one plain line.
|
||||
const CHECKED = { reachable: 'reachable', 'needs-credential': 'needs a credential', unreachable: 'unreachable' };
|
||||
const checkLine = r => `Remote check: ${CHECKED[r.check.result] ?? 'unknown'}, ${r.check.message}. Origin: ${r.origin ?? 'none'}.`;
|
||||
// Quick Setup fills both routes from the selected preset. The advanced template and
|
||||
// launch list stay unchanged; only the three routing values cross between the roles.
|
||||
function quickDocument(doc) {
|
||||
const next = structuredClone(doc), roles = Object.values(next.roles || {});
|
||||
const assistant = roles.find(role => role.definition === 'assistant');
|
||||
const chief = roles.find(role => role.definition === 'chief-of-staff');
|
||||
if (assistant?.vars && chief) {
|
||||
chief.vars = { ...chief.vars };
|
||||
for (const key of ['harness', 'model', 'thinking']) {
|
||||
if (assistant.vars[key] !== undefined) chief.vars[key] = assistant.vars[key];
|
||||
}
|
||||
}
|
||||
return next;
|
||||
}
|
||||
const ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
||||
const markup = `<div id="org-admin" class="org-admin">
|
||||
<section class="panel" aria-labelledby="org-start-title" id="org-start">
|
||||
@@ -33,7 +48,9 @@
|
||||
<div id="org-banner" class="org-banner" role="alert" hidden></div>
|
||||
<section id="org-paths" class="panel" hidden aria-labelledby="org-paths-title">
|
||||
<h3 id="org-paths-title">Choose how to set up</h3>
|
||||
<div class="org-field"><label for="org-preset">Who answers?</label><select id="org-preset"></select><span class="org-help" id="org-preset-help"></span></div>
|
||||
<p id="org-preset-none" class="org-help" hidden><span id="org-preset-none-text">Connect a model account first. Agents need one to answer.</span> <a href="#/settings/model-setup">Open Model setup</a></p>
|
||||
<div class="org-field"><label for="org-preset">Who answers?</label><select id="org-preset" aria-describedby="org-preset-help org-preset-unavailable"></select><span class="org-help" id="org-preset-help"></span><span class="org-help" id="org-preset-unavailable"></span></div>
|
||||
<div class="org-field" id="org-model-field" hidden><label for="org-model">Model</label><select id="org-model"></select></div>
|
||||
<div class="org-field"><label for="org-thinking">How much thinking?</label><select id="org-thinking"></select></div>
|
||||
<div class="settings-actions org-path-actions"><button type="button" id="org-quick-open">Quick Setup</button><button type="button" class="org-secondary" id="org-advanced-open">Advanced Setup</button></div>
|
||||
</section>
|
||||
@@ -41,13 +58,14 @@
|
||||
<h3 id="org-quick-title">Quick Setup</h3>
|
||||
<div class="org-field"><label for="org-project">First project name</label><input id="org-project" value="work" autocomplete="off"><span class="org-help">Lowercase letters, digits, dot, dash or underscore.</span></div>
|
||||
<div class="org-field"><label for="org-project-remote">Project remote URL (optional)</label><input id="org-project-remote" type="text" inputmode="url" autocomplete="off" spellcheck="false" placeholder="https://git.example/team/project or git@git.example:team/project.git"><span class="org-help">https or ssh. The project checkout's origin is set to it and checked without a credential; nothing is pushed. Leave blank for local only. The organization checkout is local only.</span></div>
|
||||
<label class="org-quick-risk"><input id="org-risk-accept" type="checkbox"> I understand local-only repositories have no copy elsewhere and can be lost.</label>
|
||||
<label class="org-quick-risk"><input id="org-risk-accept" type="checkbox" aria-describedby="org-risk-error"> I understand local-only repositories have no copy elsewhere and can be lost.</label>
|
||||
<p id="org-risk-error" class="org-field-err" role="alert" hidden></p>
|
||||
<div class="settings-actions"><button type="button" id="org-quick-run">Create and set up organization</button></div>
|
||||
<ol id="org-quick-steps" class="org-steps" aria-live="polite"></ol>
|
||||
<div class="settings-actions"><button type="button" class="org-primary" id="org-quick-interview" hidden>Start onboarding interview</button><button type="button" class="org-secondary" id="org-quick-open-org" hidden>Open organization</button></div>
|
||||
</section>
|
||||
<section id="org-editor" class="org-editor" hidden aria-labelledby="org-editor-title">
|
||||
<div class="org-editor-head"><h3 id="org-editor-title">New organization</h3><p id="org-editor-verb" class="org-verb"></p></div>
|
||||
<div class="org-editor-head"><h3 id="org-editor-title">New organization</h3><div id="org-editor-verb" class="org-verb"></div></div>
|
||||
<div id="org-errors" class="org-errors" hidden tabindex="-1" aria-labelledby="org-errors-title"><h4 id="org-errors-title">Fix these fields</h4><ul></ul></div>
|
||||
<div class="org-columns">
|
||||
<form id="org-form" class="panel org-form" novalidate aria-label="Organization fields"></form>
|
||||
@@ -65,7 +83,7 @@
|
||||
<section id="org-receipt" class="panel org-receipt" hidden aria-labelledby="org-receipt-title"></section>
|
||||
<section id="org-setup" class="org-setup" hidden aria-labelledby="org-setup-title">
|
||||
<h3 id="org-setup-title">Guided setup</h3>
|
||||
<p class="org-help">Each step shows the command it equals and the receipt it left. A step whose outcome is unknown stays incomplete until it is read back.</p>
|
||||
<p class="org-help">Follow each step to finish setting up your organization. If a result is unknown, check it before trying again.</p>
|
||||
<ol id="org-steps" class="org-steps"></ol>
|
||||
</section>
|
||||
<section id="org-archive" class="panel" hidden aria-labelledby="org-archive-title">
|
||||
@@ -115,6 +133,7 @@
|
||||
const st = { mode: null, id: null, doc: null, revision: null, state: 'active', held: [], errors: [], setup: null, pending: new Set(), unknown: new Set(), choice: new Map() };
|
||||
const status = text => { $('org-status').textContent = ''; setTimeout(() => { if (alive) $('org-status').textContent = text; }, 30); };
|
||||
const banner = (text, kind = 'err') => { const b = $('org-banner'); b.hidden = !text; b.className = `org-banner ${kind}`; b.textContent = text || ''; };
|
||||
const riskError = text => { const p = $('org-risk-error'), box = $('org-risk-accept'); p.hidden = !text; p.textContent = text || ''; if (text) box.setAttribute('aria-invalid', 'true'); else box.removeAttribute('aria-invalid'); };
|
||||
const query = () => new URLSearchParams((location.hash.split('?')[1] || ''));
|
||||
const setQuery = (org, step) => {
|
||||
const q = new URLSearchParams(); if (org) q.set('org', org); if (step) q.set('step', step);
|
||||
@@ -256,7 +275,7 @@
|
||||
$('org-archive').hidden = mode !== 'edit' || state !== 'active'; $('org-archived').hidden = mode !== 'edit' || state !== 'archived';
|
||||
$('org-restore-verb').textContent = state === 'archived' ? `Same as mosaic org restore ${id} --if-revision ${revision}` : '';
|
||||
$('org-editor-title').textContent = mode === 'create' ? `New organization: ${id}` : `Organization: ${id}`;
|
||||
$('org-editor-verb').innerHTML = verb ? `Same as ${cmd(verb)}` : '';
|
||||
$('org-editor-verb').innerHTML = verb ? commandLine(verb) : '';
|
||||
$('org-save').textContent = mode === 'create' ? 'Save organization' : 'Save changes';
|
||||
$('org-errors').hidden = true;
|
||||
renderForm(); renderJSON(true);
|
||||
@@ -269,28 +288,74 @@
|
||||
const input = $('org-new-id'), id = input.value.trim();
|
||||
if (!ID.test(id)) { input.setAttribute('aria-invalid', 'true'); $('org-new-id-help').textContent = 'Organization ID: use 1-64 lowercase letters, digits, dot, dash or underscore, starting with a letter or digit.'; $('org-new-id-help').classList.add('org-field-err'); input.focus(); status('Organization ID is not valid.'); return; }
|
||||
input.removeAttribute('aria-invalid'); $('org-new-id-help').classList.remove('org-field-err'); $('org-new-id-help').textContent = 'Lowercase letters, digits, dot, dash or underscore.';
|
||||
const r = await api('GET', '/api/org-presets');
|
||||
// A new draft reuses the pending read and outdates the earlier draft's rendering.
|
||||
++presetRead;
|
||||
const r = await readPresets();
|
||||
if (!alive) return;
|
||||
if (r.status !== 200) { banner(r.body.message || `Presets could not be read (${r.body.error || r.status}).`); return; }
|
||||
presets = r.body.presets;
|
||||
st.id = id; st.mode = 'create'; editorDirty = true;
|
||||
// A new draft starts with fresh controls; an earlier run locked them only for its own draft.
|
||||
$('org-preset').disabled = false; $('org-thinking').disabled = false; $('org-quick-run').disabled = !canWrite; $('org-risk-accept').checked = false;
|
||||
$('org-preset').innerHTML = presets.map(p => `<option value="${txt(p.name)}"${p.available.ok ? '' : ' disabled'}>${txt(p.label)}${p.available.ok ? '' : ` — ${txt(p.available.reason)}`}</option>`).join('');
|
||||
$('org-preset').value = presets.find(p => p.available.ok)?.name || '';
|
||||
updatePreset();
|
||||
$('org-preset').disabled = false; $('org-model').disabled = false; $('org-thinking').disabled = false; $('org-quick-run').disabled = !canWrite; $('org-risk-accept').checked = false; riskError('');
|
||||
renderPresets(r.body.presets, '');
|
||||
$('org-paths').hidden = false; $('org-quick').hidden = true; $('org-editor').hidden = true; $('org-receipt').hidden = true; $('org-setup').hidden = true; $('org-delete').hidden = true; $('org-delete-success').hidden = true; $('org-archive').hidden = true; $('org-archived').hidden = true; resetArchive();
|
||||
$('org-quick-steps').innerHTML = ''; $('org-quick-open-org').hidden = true; $('org-quick-interview').hidden = true; quickDone = null; banner(''); setQuery(null);
|
||||
$('org-preset').focus();
|
||||
}
|
||||
// first-run-fixes-1 follow-up: keep `keep` selected while it is still available, else take the first available.
|
||||
function renderPresets(list, keep) {
|
||||
presets = list;
|
||||
$('org-preset').innerHTML = presets.map(p => `<option value="${txt(p.name)}"${p.available.ok ? '' : ' disabled'}>${txt(p.label)}</option>`).join('');
|
||||
$('org-preset-unavailable').textContent = presets.filter(p => !p.available.ok).map(p => `${p.label}: ${p.available.reason}`).join(' ');
|
||||
$('org-preset').value = presets.find(p => p.available.ok && p.name === keep)?.name || presets.find(p => p.available.ok)?.name || '';
|
||||
updatePreset();
|
||||
}
|
||||
// first-run-fixes-1 follow-up: an owner who connects an account in another tab sees it here on
|
||||
// the select's focus or when the page shows again. Only an open, unlocked new draft re-reads;
|
||||
// a failed read keeps the list, and only the newest read is used. A choice that is no longer
|
||||
// available is replaced, and the banner says so.
|
||||
let presetRead = 0, pendingPresets = null;
|
||||
// Share the request across drafts and focus events while it is still in flight.
|
||||
function readPresets() {
|
||||
if (!pendingPresets) pendingPresets = api('GET', '/api/org-presets').finally(() => { pendingPresets = null; });
|
||||
return pendingPresets;
|
||||
}
|
||||
const presetsOpen = () => alive && st.mode === 'create' && !$('org-paths').hidden && !$('org-preset').disabled;
|
||||
async function refreshPresets() {
|
||||
if (!presetsOpen() || pendingPresets) return;
|
||||
const n = ++presetRead;
|
||||
let r; try { r = await readPresets(); } catch { return; }
|
||||
if (n !== presetRead || !presetsOpen() || r.status !== 200 || !Array.isArray(r.body?.presets)) return;
|
||||
if (JSON.stringify(r.body.presets) === JSON.stringify(presets)) return;
|
||||
const keep = $('org-preset').value, was = presets.find(p => p.name === keep)?.label;
|
||||
renderPresets(r.body.presets, keep);
|
||||
const now = presets.find(p => p.name === $('org-preset').value)?.label;
|
||||
if (keep && $('org-preset').value !== keep) {
|
||||
const line = `${was || keep} is no longer available.${now ? ` ${now} is chosen.` : ''}`;
|
||||
banner(line); status(line);
|
||||
}
|
||||
}
|
||||
function updatePreset() {
|
||||
const p = presets.find(v => v.name === $('org-preset').value);
|
||||
$('org-preset-help').textContent = p?.description || 'No available presets.';
|
||||
// first-run-fixes-1 follow-up: with no preset available, one line above the select says what to
|
||||
// do and links to Model setup; it also describes the disabled buttons.
|
||||
const none = !presets.some(v => v.available.ok);
|
||||
$('org-preset-none').hidden = !none;
|
||||
$('org-preset-help').textContent = p?.description || '';
|
||||
const previous = $('org-model').value, models = p?.models || [];
|
||||
$('org-model-field').hidden = !models.length;
|
||||
$('org-model').innerHTML = models.map(m => `<option value="${txt(m.key)}">${txt(m.label)}</option>`).join('');
|
||||
if (models.some(m => m.key === previous)) $('org-model').value = previous;
|
||||
$('org-thinking').innerHTML = (p?.thinking.levels || []).map(v => `<option value="${txt(v)}"${v === p.thinking.default ? ' selected' : ''}>${txt(v)}</option>`).join('');
|
||||
$('org-quick-open').disabled = !p || !canWrite; $('org-advanced-open').disabled = !p || !canWrite;
|
||||
// A run locks the select along with the button; only an unlocked draft changes the button here.
|
||||
if (!$('org-preset').disabled) $('org-quick-run').disabled = !p || !canWrite;
|
||||
for (const b of ['org-quick-open', 'org-advanced-open', 'org-quick-run']) {
|
||||
if (none) $(b).setAttribute('aria-describedby', 'org-preset-none-text'); else $(b).removeAttribute('aria-describedby');
|
||||
}
|
||||
}
|
||||
async function selectedTemplate() {
|
||||
const q = new URLSearchParams({ id: st.id, preset: $('org-preset').value, thinking: $('org-thinking').value });
|
||||
if ($('org-preset').value === 'cliproxy' && $('org-model').value) q.set('model', $('org-model').value);
|
||||
return api('GET', `/api/org-template?${q}`);
|
||||
}
|
||||
async function openAdvanced() {
|
||||
@@ -310,7 +375,11 @@
|
||||
$('org-project').removeAttribute('aria-invalid');
|
||||
// The server applies the full URL rules (parseRepoRemote); this only catches an obvious slip.
|
||||
if (remote && (/\s/.test(remote) || !/^(https:\/\/|ssh:\/\/|[A-Za-z0-9_][A-Za-z0-9_.-]*@[^/:]+:)/.test(remote))) { banner('Enter an https or ssh repository URL, or leave it blank.'); $('org-project-remote').focus(); return; }
|
||||
if (!$('org-risk-accept').checked) { banner('Accept the risk of local-only repositories to continue.'); $('org-risk-accept').focus(); return; }
|
||||
// first-run-fixes-1 (F6): the line sits under the checkbox it names, not in the banner above the panel.
|
||||
// The name and URL checks passed, so an earlier banner about them no longer holds.
|
||||
banner('');
|
||||
if (!$('org-risk-accept').checked) { riskError('Accept the risk of local-only repositories to continue.'); $('org-risk-accept').focus(); return; }
|
||||
riskError('');
|
||||
const id = st.id, enc = encodeURIComponent, local = { mode: 'local-only', acceptLocalLossRisk: true };
|
||||
const steps = [
|
||||
{ title: 'Create organization', verb: `mosaic org create ${id} --from <file>` },
|
||||
@@ -321,14 +390,14 @@
|
||||
{ title: 'Initialize project records', verb: `mosaic project init ${id} ${project}` },
|
||||
];
|
||||
const list = $('org-quick-steps');
|
||||
list.innerHTML = steps.map((s, i) => `<li class="panel org-step" data-quick-step="${i}" tabindex="-1"><div class="org-step-head"><h4>${txt(s.title)}</h4><span class="org-pill">Not started</span></div><p class="org-verb">Same as ${cmd(s.verb)}</p><p class="org-field-err" role="alert"></p></li>`).join('');
|
||||
const run = $('org-quick-run'); run.disabled = true; $('org-quick-open').disabled = true; $('org-advanced-open').disabled = true; $('org-preset').disabled = true; $('org-thinking').disabled = true; banner('');
|
||||
list.innerHTML = steps.map((s, i) => `<li class="panel org-step" data-quick-step="${i}" tabindex="-1"><div class="org-step-head"><h4>${txt(s.title)}</h4><span class="org-pill">Not started</span></div><p class="org-field-err" role="alert"></p></li>`).join('');
|
||||
const run = $('org-quick-run'); run.disabled = true; $('org-quick-open').disabled = true; $('org-advanced-open').disabled = true; $('org-preset').disabled = true; $('org-model').disabled = true; $('org-thinking').disabled = true; banner('');
|
||||
let current = 0;
|
||||
try {
|
||||
const template = await selectedTemplate();
|
||||
if (template.status !== 200) throw Error(template.body.message || 'Could not load the template.');
|
||||
if (!template.body.doc || typeof template.body.doc !== 'object') throw Error('The template reply could not be read.');
|
||||
const doc = template.body.doc; doc.projects = { [project]: {} };
|
||||
const doc = quickDocument(template.body.doc); doc.projects = { [project]: {} };
|
||||
const requests = [
|
||||
['/api/orgs', { id, doc }, 'create'],
|
||||
[`/api/orgs/${enc(id)}/setup/queue`, local, 'queue'],
|
||||
@@ -346,8 +415,7 @@
|
||||
if (step === 'chat-project' ? !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(result.body.id || '') : result.body.outcome !== 'done' || result.body.step !== step) throw Error('The reply could not be read, so this step\'s outcome is unknown.');
|
||||
if (step === 'chat-project') quickDone = { org: id, chatProject: result.body.id, repo: project };
|
||||
card.querySelector('.org-pill').textContent = 'Done'; card.classList.add('org-step-done');
|
||||
if (result.body.verb) card.querySelector('code').textContent = result.body.verb;
|
||||
if (step === 'project' && result.body.receipt?.check) card.querySelector('.org-verb').insertAdjacentHTML('afterend', `<p class="org-help" data-remote-check>${txt(checkLine(result.body.receipt))}</p>`);
|
||||
if (step === 'project' && result.body.receipt?.check) card.querySelector('.org-step-head').insertAdjacentHTML('afterend', `<p class="org-help" data-remote-check>${txt(checkLine(result.body.receipt))}</p>`);
|
||||
}
|
||||
editorDirty = false; $('org-new-id').value = ''; $('org-quick-open-org').hidden = false; $('org-quick-interview').hidden = !window.MosaicOnboarding; status('Organization setup complete.');
|
||||
// E1 (P1-5): the sidebar and header list the new organization without a reload.
|
||||
@@ -407,7 +475,7 @@
|
||||
}
|
||||
function showReceipt(title, body) {
|
||||
const box = $('org-receipt');
|
||||
box.innerHTML = `<h3 id="org-receipt-title">${txt(title)}</h3><p>Same as ${cmd(body.verb)}</p><pre class="org-pre">${txt(JSON.stringify(body.receipt, null, 2))}</pre>`;
|
||||
box.innerHTML = `<h3 id="org-receipt-title">${txt(title)}</h3>${commandLine(body.verb)}<pre class="org-pre">${txt(JSON.stringify(body.receipt, null, 2))}</pre>`;
|
||||
box.hidden = false; status(`${title}. Receipt shown.`);
|
||||
}
|
||||
async function refreshList() {
|
||||
@@ -457,7 +525,7 @@
|
||||
const c = st.choice.get(key) || {}, remote = c.mode === 'remote';
|
||||
return `<li class="panel org-step org-step-${cls}" data-step="${txt(key)}" aria-labelledby="org-step-${i}-title">
|
||||
<div class="org-step-head"><h4 id="org-step-${i}-title"><span class="org-step-n">${i + 1}</span> ${txt(title)}</h4><span class="org-pill ${cls}">${txt(stateLabel)}</span></div>
|
||||
<p class="org-verb">Same as ${cmd(s.verb || '')}</p>
|
||||
${commandLine(s.verb || '')}
|
||||
${s.message ? `<p class="org-help">${txt(s.message)}</p>` : ''}
|
||||
${key.startsWith('project:') && s.receipt?.check ? `<p class="org-help" data-remote-check>${txt(checkLine(s.receipt))}</p>` : ''}
|
||||
${s.lastError ? `<p class="org-field-err" role="alert">${txt(s.lastError)}</p>` : ''}
|
||||
@@ -665,9 +733,12 @@
|
||||
[$('org-delete-final'), 'click', runDelete],
|
||||
[$('org-new-form'), 'submit', startNew],
|
||||
[$('org-preset'), 'change', updatePreset],
|
||||
[$('org-preset'), 'focus', refreshPresets],
|
||||
[document, 'visibilitychange', () => { if (document.visibilityState === 'visible') refreshPresets(); }],
|
||||
[$('org-quick-open'), 'click', openQuick],
|
||||
[$('org-advanced-open'), 'click', openAdvanced],
|
||||
[$('org-quick-run'), 'click', quickRun],
|
||||
[$('org-risk-accept'), 'change', () => { if ($('org-risk-accept').checked) riskError(''); }],
|
||||
// F2: the interview opens a conversation with the assistant; Open organization skips it.
|
||||
[$('org-quick-interview'), 'click', async () => { const b = $('org-quick-interview'); b.disabled = true; if (!await window.MosaicOnboarding?.start({ ...quickDone, status })) b.disabled = false; }],
|
||||
[$('org-quick-open-org'), 'click', () => { history.replaceState(null, '', `#/orgs/${encodeURIComponent(st.id)}/chat`); location.reload(); }],
|
||||
@@ -707,5 +778,5 @@
|
||||
}).catch(() => banner('The Console configuration could not be read.'));
|
||||
return () => { alive = false; delete window.MosaicOrgCreate.hasDraft; for (const [el, ev, fn] of handlers) el.removeEventListener(ev, fn); };
|
||||
}
|
||||
window.MosaicOrgCreate = { markup, mount };
|
||||
window.MosaicOrgCreate = { markup, mount, quickDocument };
|
||||
})();
|
||||
@@ -35,7 +35,7 @@
|
||||
};
|
||||
// Why a hire did not happen, by the code the bus recorded. An unknown code is shown as itself.
|
||||
const HIRE_WHY = {
|
||||
'pack-hire-route-missing': 'neither the chief of staff nor the assistant has a harness and model to give it; set them under Settings, Routing',
|
||||
'pack-hire-route-missing': 'neither the chief of staff nor the assistant has a harness and model to give it; set them under Settings, Models',
|
||||
'no-chief-of-staff': 'the organization has no chief of staff',
|
||||
'hire-owner-required': 'it has flagged or credential lines only the owner approves',
|
||||
'definition-not-hireable': 'its role is on the no-hire list',
|
||||
|
||||
@@ -46,6 +46,9 @@
|
||||
}
|
||||
async function refresh() {
|
||||
if (busy || out()) return;
|
||||
await window.MosaicOrg?.ready;
|
||||
if (document.documentElement.hasAttribute('data-organizations') && !window.MosaicOrg?.id) { host.hidden = true; banner.hidden = true; return; }
|
||||
host.hidden = false;
|
||||
const current = ++sequence;
|
||||
try {
|
||||
const [configResponse, stateResponse] = await Promise.all([
|
||||
|
||||
@@ -65,6 +65,13 @@
|
||||
async function mountTree({container,path:route}) {
|
||||
if(!container || document.body.classList.contains('signed-out')) return;
|
||||
const generation=++treeGeneration;
|
||||
await window.MosaicOrg?.ready;
|
||||
if (generation!==treeGeneration || !container.isConnected) return;
|
||||
if (document.documentElement.hasAttribute('data-organizations') && !window.MosaicOrg?.id) {
|
||||
container.textContent = 'Create an organization to see projects here.';
|
||||
delete container.dataset.treePaint;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (!treeRead || Date.now()-treeReadAt>10000) {
|
||||
treeReadAt=Date.now();
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/* State-derived setup checklist. Geometry follows the approved setup frames. */
|
||||
.setup-card { max-width: 940px; background: var(--surface); border: 1px solid var(--line); border-radius: 10px; overflow: hidden; margin-bottom: 16px; }
|
||||
.setup-head { padding: 16px 20px 14px; border-bottom: 1px solid var(--line); }
|
||||
.setup-head .setup-where-am-i { font-size: 11px; letter-spacing: .06em; color: var(--action); font-weight: 700; margin: 0 0 4px; }
|
||||
.setup-head h2 { margin: 0; font-size: 20px; color: var(--strong); line-height: 1.4; }
|
||||
.setup-head p { margin: 6px 0 0; color: var(--muted); }
|
||||
.setup-bar { display: flex; gap: 4px; margin-top: 12px; width: 320px; max-width: 100%; }
|
||||
.setup-bar i { flex: 1; height: 6px; border-radius: 3px; background: var(--raised); }
|
||||
.setup-bar .on { background: var(--success); }.setup-bar .cur { background: var(--action); }.setup-bar .bad { background: var(--danger); }
|
||||
.checklist-steps { list-style: none; margin: 0; padding: 0; }
|
||||
.checklist-step { display: grid; grid-template-columns: 32px minmax(0, 1fr) auto; column-gap: 14px; align-items: start; padding: 10px 20px; border-bottom: 1px solid color-mix(in srgb, var(--line) 70%, transparent); }
|
||||
.checklist-step:last-child { border-bottom: 0; }
|
||||
.setup-num { width: 28px; height: 28px; border-radius: 50%; border: 1.5px solid var(--line); display: grid; place-items: center; font-size: 13px; color: var(--muted); margin-top: 1px; }
|
||||
.setup-done .setup-num { border-color: var(--success); color: var(--success); background: color-mix(in srgb, var(--success) 10%, transparent); }
|
||||
.setup-open { background: color-mix(in srgb, var(--action) 6%, var(--surface)); box-shadow: inset 3px 0 0 var(--action); padding-top: 14px; padding-bottom: 15px; }
|
||||
.setup-open .setup-num { border-color: var(--action); background: var(--action); color: var(--onAction); }
|
||||
.setup-failed { background: color-mix(in srgb, var(--danger) 7%, var(--surface)); box-shadow: inset 3px 0 0 var(--danger); }
|
||||
.setup-failed .setup-num { color: var(--danger); border-color: var(--danger); background: color-mix(in srgb, var(--danger) 12%, transparent); }
|
||||
.setup-not-applicable .setup-num, .setup-optional .setup-num { border-style: dashed; }
|
||||
.setup-title { color: var(--strong); font-size: 15px; font-weight: 700; line-height: 1.35; }
|
||||
.setup-waiting .setup-title { color: var(--text); font-weight: 600; }
|
||||
.setup-description { color: var(--muted); font-size: 13.5px; margin: 2px 0 0; }
|
||||
.setup-right { display: flex; align-items: center; gap: 12px; margin-top: 2px; font-size: 13px; }
|
||||
.setup-pill { display: inline-flex; align-items: center; white-space: nowrap; gap: 5px; border: 1px solid var(--line); border-radius: 999px; padding: 1px 9px; color: var(--muted); font-size: 12px; line-height: 1.5; }
|
||||
.setup-pill::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
|
||||
.setup-next .setup-pill { color: var(--action); border-color: color-mix(in srgb, var(--action) 45%, var(--line)); }
|
||||
.setup-done .setup-pill { color: var(--success); }.setup-failed .setup-pill { color: var(--danger); }.setup-checking .setup-pill { color: var(--warning); }
|
||||
.setup-body { grid-column: 2 / 4; margin-top: 10px; }
|
||||
.setup-body p { max-width: 640px; margin: 0 0 10px; }
|
||||
.setup-actions { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
|
||||
.setup-actions .btn { min-height: 40px; text-decoration: none; display: inline-flex; align-items: center; padding: 8px 16px; }
|
||||
.setup-where { font-size: 12.5px; color: var(--muted); }
|
||||
.setup-list-split { padding: 10px 20px 6px; font-size: 11px; line-height: 1.3; letter-spacing: .04em; color: var(--muted); border-bottom: 1px solid var(--line); margin: 0; }
|
||||
.setup-needs { grid-column: 2 / 4; font-size: 13px; margin-top: 6px; }
|
||||
.setup-needs summary { cursor: pointer; color: var(--action); }
|
||||
.setup-needs p { max-width: 680px; margin: 8px 0 0; }
|
||||
.setup-strip { display: flex; align-items: center; gap: 12px; border: 1px solid var(--line); background: var(--surface); border-radius: 10px; padding: 9px 14px; margin: 0 0 16px; font-size: 13.5px; }
|
||||
.setup-ok { width: 20px; height: 20px; border-radius: 50%; display: grid; place-items: center; background: color-mix(in srgb, var(--success) 16%, transparent); color: var(--success); }
|
||||
.setup-show { margin-left: auto; border: 0; color: var(--action); background: none; font: inherit; font-size: 13px; cursor: pointer; padding: 4px; }
|
||||
.setup-alert { border: 1px solid color-mix(in srgb, var(--danger) 45%, var(--line)); border-radius: 10px; background: color-mix(in srgb, var(--danger) 7%, var(--surface)); margin-bottom: 16px; overflow: hidden; }
|
||||
.setup-alert .checklist-step { padding: 14px 18px; }
|
||||
.setup-foot-line { display: flex; gap: 10px; align-items: center; padding: 8px 18px 9px 64px; border-top: 1px solid var(--line); font-size: 12.5px; color: var(--muted); }
|
||||
.setup-read-error { padding: 16px; }
|
||||
.setup-status-link { display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--line); border-radius: 999px; padding: 1px 6px; white-space: nowrap; color: var(--strong); font-size: 12px; text-decoration: none; }
|
||||
.setup-status-link::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: var(--action); }
|
||||
.setup-status-link.setup-has-failure::before { background: var(--danger); }
|
||||
.setup-status-replaced { display: none !important; }
|
||||
.setup-status-link[hidden] { display: none; }
|
||||
@media (max-width: 700px) {
|
||||
.setup-head { padding: 16px; }.setup-head h2 { font-size: 19px; }
|
||||
.checklist-step { grid-template-columns: 28px minmax(0, 1fr); column-gap: 12px; padding: 12px 16px; }
|
||||
.setup-right { grid-column: 2; margin-top: 6px; }.setup-body, .setup-needs { grid-column: 1 / 3; }
|
||||
.setup-body { margin-top: 12px; }.setup-actions { align-items: stretch; flex-direction: column; gap: 12px; }
|
||||
.setup-actions .btn { justify-content: center; width: 100%; }.setup-strip { flex-wrap: wrap; gap: 8px; }
|
||||
.setup-foot-line { padding: 8px 16px; flex-wrap: wrap; }.setup-status-link { max-width: 135px; white-space: normal; font-size: 11px; }
|
||||
}
|
||||
/* Override the workspace's generic list and section heading rules inside this card only. */
|
||||
html[data-organizations] .ws .setup-steps { padding: 0; margin: 0; list-style: none; }
|
||||
html[data-organizations] .ws .setup-head h2 { font-size: 20px; line-height: 1.4; margin: 0; }
|
||||
html[data-organizations] .ws .setup-list-split { font-size: 11px; font-weight: 700; padding: 10px 20px 6px; margin: 0; }
|
||||
html[data-organizations] .ws .setup-head .setup-where-am-i { font-size: 11px; line-height: 1.3; }
|
||||
@media (max-width: 700px) { html[data-organizations] .ws .setup-head h2 { font-size: 19px; } }
|
||||
@media (min-width: 701px) {
|
||||
.checklist-step.setup-optional, .checklist-step:has(.setup-needs) { position: relative; }
|
||||
.setup-needs { grid-column: 2 / 4; margin-top: 0; }
|
||||
.setup-needs summary { position: absolute; right: 112px; top: 11px; list-style: none; }
|
||||
.setup-needs summary::-webkit-details-marker { display: none; }
|
||||
.setup-needs[open] p { margin-top: 12px; }
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// Readiness presentation only. No step list, completion flag, provider list or write request.
|
||||
(() => {
|
||||
'use strict';
|
||||
const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const satisfied = r => r && ['done', 'not-applicable'].includes(r.state);
|
||||
function derive(input) {
|
||||
const rows = input.map(r => ({ ...r, order: { after: [...(r.order?.after ?? [])] } }));
|
||||
const byId = new Map(rows.map(r => [r.id, r])), ordered = [], seen = new Set(), visiting = new Set();
|
||||
function visit(r) {
|
||||
if (seen.has(r.id)) return;
|
||||
if (visiting.has(r.id)) { for (const id of visiting) { const part = byId.get(id); part.state = 'failed'; part.invalidOrder = true; part.reason = "Couldn't check the order of these steps. Refresh to try again."; } return; }
|
||||
visiting.add(r.id);
|
||||
for (const id of r.order.after) {
|
||||
if (byId.has(id)) visit(byId.get(id));
|
||||
else { r.state = 'failed'; r.reason = "Couldn't check an earlier step. Refresh to try again."; }
|
||||
}
|
||||
visiting.delete(r.id); seen.add(r.id); ordered.push(r);
|
||||
}
|
||||
rows.forEach(visit);
|
||||
const required = ordered.filter(r => r.required && r.state !== 'not-applicable'), optional = ordered.filter(r => !r.required);
|
||||
required.forEach((r, i) => { r.number = i + 1; });
|
||||
const current = required.find(r => !satisfied(r)) ?? null;
|
||||
const alerts = required.filter(r => r.state === 'failed').map(r => ({ ...r }));
|
||||
const alertsOnly = alerts.length > 0 && required.every(r => satisfied(r) || r.state === 'failed');
|
||||
// Completed evidence stays completed when an earlier check fails later.
|
||||
function blocker(r, trail = new Set()) {
|
||||
if (trail.has(r.id)) return r;
|
||||
trail.add(r.id);
|
||||
for (const id of r.order.after) { const dep = byId.get(id); if (!satisfied(dep)) return dep ? blocker(dep, trail) ?? dep : r; }
|
||||
return satisfied(r) ? null : r;
|
||||
}
|
||||
for (const r of required) {
|
||||
if (satisfied(r) || r.invalidOrder) continue;
|
||||
if (r === current) { if (!['failed', 'checking'].includes(r.state)) r.state = 'next'; continue; }
|
||||
const dep = blocker(r);
|
||||
if (dep && dep !== r) { r.state = 'waiting'; r.waitStep = Math.min(dep.number ?? current?.number, current?.number); }
|
||||
else { r.state = 'waiting'; r.waitStep = current?.number; }
|
||||
}
|
||||
const complete = required.length > 0 && required.every(satisfied);
|
||||
const failures = alerts;
|
||||
return { rows: [...ordered.filter(r => r.required), ...optional], required, optional, current, total: required.length, done: required.filter(satisfied).length, step: current?.number ?? required.length, complete,
|
||||
alertsOnly, failures };
|
||||
}
|
||||
function target(fix) {
|
||||
if (!fix || typeof fix.page !== 'string' || !/^#\/[A-Za-z0-9/?&=._%:-]*$/.test(fix.page)) return null;
|
||||
return fix.step && [1, 2].includes(fix.step) ? `${fix.page}${fix.page.includes('?') ? '&' : '?'}step=${fix.step}` : fix.page;
|
||||
}
|
||||
function oneRow(r, current, alert = false) {
|
||||
const open = current?.id === r.id || alert, failed = r.state === 'failed';
|
||||
const words = { next: 'Next', checking: 'Checking', waiting: `After step ${r.waitStep ?? current?.number ?? 1}`, done: 'Done', failed: "Needs a fix", 'not-applicable': 'Not needed', optional: 'Optional' };
|
||||
const href = r.state === 'not-applicable' ? null : target(r.fix), optional = !r.required;
|
||||
return `<li class="checklist-step ${open ? 'setup-open ' : ''}setup-${esc(r.state)}">
|
||||
<span class="setup-num" aria-hidden="true">${failed ? '!' : satisfied(r) ? '✓' : r.number ?? '+'}</span>
|
||||
<div class="setup-copy"><div class="setup-title">${esc(r.title)}</div><p class="setup-description">${esc(satisfied(r) || failed && open ? r.reason : r.purpose)}</p></div>
|
||||
<div class="setup-right">${satisfied(r) && href ? `<a href="${esc(href)}">Open</a>` : ''}<span class="setup-pill">${esc(words[r.state] ?? 'Checking')}</span></div>
|
||||
${open ? `<div class="setup-body">${!(failed || satisfied(r)) && r.reason ? `<p>${esc(r.reason)}</p>` : ''}${href ? `<div class="setup-actions"><a class="btn primary" href="${esc(href)}">${esc(r.fix.label)}</a><span class="setup-where">Opens the page for this step</span></div>` : ''}</div>` : ''}
|
||||
${optional ? `<details class="setup-needs"><summary>What this needs</summary><p>${esc(r.reason)}</p></details>` : ''}
|
||||
</li>`;
|
||||
}
|
||||
function card(s) {
|
||||
const title = s.current ? `Step ${s.step} of ${s.total}: ${s.current.title.charAt(0).toLowerCase()}${s.current.title.slice(1)}` : 'Setup checks';
|
||||
return `<section class="setup-card" aria-label="Set up Mosaic Stack"><header class="setup-head"><p class="setup-where-am-i">Set up Mosaic Stack</p><h2>${esc(title)}</h2><p>${s.complete ? 'Each check reads current state. Open a finished step to see its settings.' : 'One step at a time. The blue button is the thing to do now.'}</p><div class="setup-bar" aria-label="${s.done} of ${s.total} steps complete">${s.required.map(r => `<i class="${satisfied(r) ? 'on' : r === s.current ? r.state === 'failed' ? 'bad' : 'cur' : ''}"></i>`).join('')}</div></header><ol class="setup-steps">${s.rows.filter(r => r.required).map(r => oneRow(r, s.current)).join('')}</ol>${s.optional.length ? `<h3 class="setup-list-split">Later, when you need it</h3><ul class="setup-steps">${s.optional.map(r => oneRow(r, null)).join('')}</ul>` : ''}</section>`;
|
||||
}
|
||||
function render(s, expanded = false) {
|
||||
if (s.complete) return `<section class="setup-strip" aria-label="Setup checks"><span class="setup-ok" aria-hidden="true">✓</span><strong>Setup done.</strong><span>All ${s.total} checks pass.</span><span class="muted">Checked just now.</span><button type="button" class="setup-show" data-setup-show aria-expanded="${expanded}">${expanded ? 'Hide checks' : 'Show checks'}</button></section>${expanded ? card(s) : ''}`;
|
||||
if (s.alertsOnly && !expanded) return s.failures.map(r => `<section class="setup-alert" aria-label="Setup needs a fix"><ul class="setup-steps">${oneRow(r, r, true)}</ul><div class="setup-foot-line">This is step ${r.number} from setup. Its check needs a fix.<button type="button" class="setup-show" data-setup-show aria-expanded="false">Show checks</button></div></section>`).join('');
|
||||
return card(s);
|
||||
}
|
||||
let last = null, expanded = false;
|
||||
const fetchRead = window.fetch?.bind(window);
|
||||
function paintShell(s = last?.state) {
|
||||
if (!s || typeof document === 'undefined') return;
|
||||
let pill = document.getElementById('setup-short');
|
||||
const processing = document.getElementById('processing-link');
|
||||
if (!pill && processing) { pill = document.createElement('a'); pill.id = 'setup-short'; pill.className = 'setup-status-link'; pill.href = '#/dashboard'; processing.before(pill); }
|
||||
if (pill) { pill.hidden = s.complete; pill.textContent = `Setup: step ${s.step} of ${s.total}`; pill.classList.toggle('setup-has-failure', s.current?.state === 'failed'); }
|
||||
if (processing) processing.classList.toggle('setup-status-replaced', !s.complete);
|
||||
const hint = document.querySelector('#ws-org-list .ws-line');
|
||||
const organization = s.required.find(r => target(r.fix)?.startsWith('#/settings/organizations'));
|
||||
if (hint && !last?.organizations.length && organization) { const text = `None yet. Step ${organization.number} creates one.`; if (hint.textContent !== text) hint.textContent = text; }
|
||||
}
|
||||
let pendingRead = null, recentRead = null, reuseUntil = 0;
|
||||
function read() {
|
||||
// Shell startup and theme changes can render home again immediately. Share that read.
|
||||
if (pendingRead) return pendingRead;
|
||||
if (recentRead && Date.now() < reuseUntil) return Promise.resolve(recentRead);
|
||||
pendingRead = load().then(result => {
|
||||
recentRead = result; reuseUntil = Date.now() + 2000; return result;
|
||||
}).finally(() => { pendingRead = null; });
|
||||
return pendingRead;
|
||||
}
|
||||
async function load() {
|
||||
try {
|
||||
const response = await fetchRead('/api/setup', { cache: 'no-store', redirect: 'manual' });
|
||||
if (!response.ok) throw Error();
|
||||
const body = await response.json();
|
||||
if (!Array.isArray(body.rows) || !Array.isArray(body.organizations) || !body.rows.length) throw Error();
|
||||
const state = derive(body.rows);
|
||||
last = { state, organizations: body.organizations }; paintShell(state);
|
||||
const html = render(state, expanded), empty = !body.organizations.length && !state.complete;
|
||||
return { html, empty, page: `<article class="ws ws-home" data-ws-home><div class="ws-vh"><h1 tabindex="-1">Dashboard</h1><p class="sub">${state.done ? `${state.done} of ${state.total} steps done.` : 'Nothing is set up yet.'} Work down this list. Each step checks itself, so it stays right even if you set something up elsewhere.</p></div><div data-setup-region>${html}</div></article>` };
|
||||
} catch {
|
||||
const html = '<section class="setup-alert setup-read-error" role="status"><strong>Couldn\'t check setup.</strong> Refresh to try again.</section>';
|
||||
return { html, empty: false };
|
||||
}
|
||||
}
|
||||
window.MosaicSetup = Object.freeze({ derive, render, read, paintShell });
|
||||
if (typeof document === 'undefined' || !document.documentElement.hasAttribute('data-organizations')) return;
|
||||
document.addEventListener('click', event => {
|
||||
if (!event.target.closest?.('[data-setup-show]') || !last) return;
|
||||
expanded = !expanded; recentRead = null;
|
||||
const region = document.querySelector('[data-setup-region]');
|
||||
if (region) { region.innerHTML = render(last.state, expanded); region.querySelector('[data-setup-show]')?.focus(); }
|
||||
});
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
window.MosaicInitialOrganizations?.then(async rows => {
|
||||
if (Array.isArray(rows) && !rows.length && ['', '#', '#/'].includes(location.hash)) {
|
||||
const setup = await read();
|
||||
if (setup.empty && ['', '#', '#/'].includes(location.hash)) location.hash = '#/dashboard';
|
||||
}
|
||||
});
|
||||
const nav = document.getElementById('workspace-nav');
|
||||
if (nav) new MutationObserver(() => paintShell()).observe(nav, { childList: true, subtree: true });
|
||||
});
|
||||
})();
|
||||
@@ -451,6 +451,7 @@
|
||||
<label>Title<input name="title" required maxlength="250" autocomplete="off"></label>
|
||||
<label>Requirement<input name="requirement" required pattern="${REQUIREMENT}" placeholder="REQ-WEB-1" autocomplete="off" aria-describedby="tb-req-note"></label>
|
||||
<p class="tb-field-note" id="tb-req-note">The requirement this task serves, written as REQ-AREA-N.</p>
|
||||
<p class="tb-field-note" id="tb-req-error" role="alert"></p>
|
||||
<div class="tb-row2">${stateSelect('todo')}${prioSelect(0)}<label>Due date<input type="date" name="due_date"></label></div>
|
||||
<div data-tb-roles>${roleBoxes(org.roles, [])}</div>
|
||||
<p class="tb-form-status" role="alert" data-tb-form-status></p>
|
||||
@@ -563,6 +564,23 @@
|
||||
try { await reload(); } catch {}
|
||||
paint();
|
||||
}
|
||||
// Native validation fires before submit. Explain this field inline for both empty
|
||||
// and malformed values, including a screen-reader announcement and focus.
|
||||
document.addEventListener('invalid', e => {
|
||||
const field = e.target;
|
||||
if (field.name !== 'requirement' || !field.closest('[data-tb-form="create"]')) return;
|
||||
e.preventDefault();
|
||||
field.setAttribute('aria-invalid', 'true');
|
||||
field.setAttribute('aria-describedby', 'tb-req-note tb-req-error');
|
||||
field.form.querySelector('#tb-req-error').textContent = 'Type a requirement ID using capital letters and a number, for example REQ-WEB-1.';
|
||||
field.focus();
|
||||
}, true);
|
||||
document.addEventListener('input', e => {
|
||||
const field = e.target;
|
||||
if (field.name !== 'requirement' || !field.closest('[data-tb-form="create"]')) return;
|
||||
field.removeAttribute('aria-invalid'); field.setAttribute('aria-describedby', 'tb-req-note');
|
||||
field.form.querySelector('#tb-req-error').textContent = '';
|
||||
});
|
||||
async function archive(form) {
|
||||
if (form.querySelector('[data-tb-archive]')?.disabled) return;
|
||||
const t = opened && key(opened) === form.dataset.tbKey ? opened : null;
|
||||
|
||||
@@ -97,7 +97,7 @@
|
||||
const held = on && agents ? agents.find(a => a?.role === name && item.running.includes(a.holder_run)) : null;
|
||||
return ACTIVITY[held?.state] || (on ? ['s-working', '●', 'running'] : ['s-idle', '–', 'not running']);
|
||||
};
|
||||
// The inline model control: the change itself happens on Settings, Routing, with its own checks.
|
||||
// The inline model control: the change itself happens on Settings, Models, with its own checks.
|
||||
const modelCell = (agent, model) => (model ? `${esc(model)} <a class="ws-change" href="#/settings/routing" data-focus-key="${esc(`model:${agent}`)}" aria-label="${esc(`Change the model for ${agent}`)}">Change</a>` : '<span class="muted">not reported</span>');
|
||||
|
||||
// Focus survives a repaint: the focused control's data-focus-key is found again afterwards.
|
||||
@@ -562,7 +562,7 @@
|
||||
const chooser = projectIds.length ? `<label class="ws-psel">${av(selOrg, 'xs')}<span class="ws-sr">Project</span><select data-agents-project="${esc(selected)}" data-focus-key="agents-project">${projectIds.map(id => `<option value="${esc(id)}"${id === pick ? ' selected' : ''}>${esc(ctx.names(id))}</option>`).join('')}</select></label>` : '';
|
||||
const title = projectIds.length ? 'Available in a project' : `Agents in ${esc(label(selOrg))}`;
|
||||
const table = !mine ? '<p class="ws-panel tight note">The selected organization is not on the list.</p>' : levelsTable(ctx, pick);
|
||||
const rules = `<div class="ws-panel tight ws-rules"><p><span class="ws-lvl root">root</span>You define root agents in agents.json in your configuration directory. The chief cannot change them.</p><p><span class="ws-lvl org">org</span>Agents come from the organization file. Add, change or remove them under Settings, Agents.</p><p><span class="ws-lvl proj">project</span>A project in the organization file can add an agent, narrow an inherited agent's limits or exclude one. It never widens them.</p><p><span class="ws-lvl proj">override</span>The most specific level wins. A row says which definition it replaces.</p><p class="muted">An agent's harness, model and thinking are set under Settings, Routing.</p></div>`;
|
||||
const rules = `<div class="ws-panel tight ws-rules"><p><span class="ws-lvl root">root</span>You define root agents in agents.json in your configuration directory. The chief cannot change them.</p><p><span class="ws-lvl org">org</span>Agents come from the organization file. Add, change or remove them under Settings, Agents.</p><p><span class="ws-lvl proj">project</span>A project in the organization file can add an agent, narrow an inherited agent's limits or exclude one. It never widens them.</p><p><span class="ws-lvl proj">override</span>The most specific level wins. A row says which definition it replaces.</p><p class="muted">An agent's harness, model and thinking are set under Settings, Models.</p></div>`;
|
||||
const receipt = selected === window.MosaicOrg?.id ? `<div data-agents-receipt role="status">${window.MosaicDecide?.fireNote() ?? ''}</div>` : '';
|
||||
return `<section class="ws ws-agents" data-org-agents>${head}${receipt}${band}${levelsGrid}
|
||||
<div class="ws-split ws-split-agents"><section><div class="ws-sec-h"><h2>${title}</h2>${chooser}</div><div data-agents-available data-agents-org="${esc(selected)}">${table}</div></section><section>${secH('Who changes what')}${rules}</section></div>
|
||||
@@ -666,6 +666,8 @@
|
||||
|
||||
// ---- main dashboard (sample 02) ----
|
||||
async function home() {
|
||||
const setup = await window.MosaicSetup?.read();
|
||||
if (setup?.empty) return setup.page;
|
||||
let body;
|
||||
let levels = null, listed = null;
|
||||
// SP1: the agent counts come from the organization files (GET /api/agents/levels, owner only), so a
|
||||
@@ -768,6 +770,7 @@
|
||||
: `${body.summary?.read ?? o.rows.length - o.unread.length} of ${plural(o.rows.length, 'organization')} answered. Totals add up the ones that answered; ${andList(o.unread.map(stateWords))}.`;
|
||||
return `<article class="ws ws-home" data-ws-home>
|
||||
<div class="ws-vh"><h1 tabindex="-1">Dashboard</h1><p class="sub">${sub}</p></div>
|
||||
<div data-setup-region>${setup?.html ?? ''}</div>
|
||||
${tiles}
|
||||
<div class="ws-split ws-home-split">
|
||||
<section aria-label="Organizations, projects and tasks">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { AUTONOMY_ROUTE, autonomyHTTP } from './autonomy-http.mjs';
|
||||
import { proxyHTTP } from './proxy-http.mjs';
|
||||
import { proxyHTTP, OWNER_PROXY_PATHS } from './proxy-http.mjs';
|
||||
import { proxyAdminHTTP } from './proxy-admin.mjs';
|
||||
import { triageHTTP, TRIAGE_PATHS } from './triage-http.mjs';
|
||||
import { createServer } from 'node:http';
|
||||
@@ -72,6 +72,8 @@ const files = new Map([
|
||||
['/projects.css', ['projects.css', 'text/css; charset=utf-8']],
|
||||
['/files.css', ['files.css', 'text/css; charset=utf-8']],
|
||||
...['shared/app.css', 'tokens.css', 'console.css', 'live.css', 'bus.css', 'shell.css', 'chat.css', 'project-archive.css', 'processing.css', 'org-create.css', 'onboarding.css', 'tasks-board.css', 'assistant.css'].map(f => ['/' + f, [f, 'text/css; charset=utf-8']]),
|
||||
['/setup-checklist.js', ['setup-checklist.js', 'text/javascript; charset=utf-8']],
|
||||
['/setup-checklist.css', ['setup-checklist.css', 'text/css; charset=utf-8']],
|
||||
['/display.js', ['display.js', 'text/javascript; charset=utf-8']],
|
||||
['/inbox.js', ['inbox.js', 'text/javascript; charset=utf-8']],
|
||||
['/inbox.css', ['inbox.css', 'text/css; charset=utf-8']],
|
||||
@@ -460,7 +462,7 @@ const AGENT_REASONS = {
|
||||
'limit-reached': 'a launch limit is reached',
|
||||
'no-route': 'the instance has no harness, model and thinking yet; set its route first',
|
||||
'skill-not-enabled': "A skill this role needs isn't turned on: scripts/skill.sh activate <name>",
|
||||
'unsupported-harness': 'Choose a supported harness in Routing',
|
||||
'unsupported-harness': 'choose a supported harness in Settings, under Models in an organization or Routing elsewhere',
|
||||
'unknown-role': 'the business has no such instance',
|
||||
'unknown-request': 'the bus has no such request',
|
||||
'instance-not-listed': 'the instance isn\'t on the launch list',
|
||||
@@ -939,6 +941,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
} else if (!orgList && path !== '/api/config' && !hook
|
||||
// #1873 triage-host: the Triage routes pass only for the instance owner's own session on the
|
||||
// public name; every other caller gets this Console's unknown /api/ answer. The gate below checks again.
|
||||
&& !((path.startsWith('/api/proxy/admin/') || OWNER_PROXY_PATHS.includes(path)) && !tester && named && sso !== null && sso.session(req)?.rootOwner === true)
|
||||
&& !(triage && TRIAGE_PATHS.includes(path) && !tester && named && sso !== null && sso.session(req)?.rootOwner === true)) {
|
||||
return json(res, 404, { error: 'org-unavailable' });
|
||||
}
|
||||
@@ -1046,12 +1049,15 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
}
|
||||
// #1873: proxy setup. Instance-wide host actions (fetch, unit) and the init and fence verbs on
|
||||
// the selected bus; only the instance owner's own session reaches them, never an org owner.
|
||||
const instanceModelSetup = organizations && orgId === null && (path.startsWith('/api/proxy/admin/') || OWNER_PROXY_PATHS.includes(path)) && currentSession?.rootOwner === true;
|
||||
if (instanceModelSetup && typeof proxyAdmin?.ownerCall === 'function')
|
||||
proxyCall = (verb, args) => proxyAdmin.ownerCall(verb, args, { provider: currentSession.provider, iss: currentSession.iss, sub: currentSession.sub });
|
||||
if (path.startsWith('/api/proxy/admin/')) return proxyAdminHTTP(req, res, { path, admin: proxyAdmin, call: proxyCall, named, tester, granted,
|
||||
owner: !tester && !granted && named && sso !== null && currentSession?.rootOwner === true, send: owner.send !== null,
|
||||
origin: sso ? (localOrigin ?? sso.publicOrigin) : `https://${preview.host}`, user: signer?.user,
|
||||
principal: currentSession ? { provider: currentSession.provider, iss: currentSession.iss, sub: currentSession.sub } : null, log });
|
||||
if (path.startsWith('/api/proxy/')) return proxyHTTP(req, res, { path, call: proxyCall, named, tester, granted,
|
||||
send, origin: sso ? (localOrigin ?? sso.publicOrigin) : `https://${preview.host}`, user: signer?.user, log,
|
||||
send: instanceModelSetup ? owner.send : send, origin: sso ? (localOrigin ?? sso.publicOrigin) : `https://${preview.host}`, user: signer?.user, log,
|
||||
record: proxyAdmin && typeof proxyAdmin.recordAccount === 'function' ? entry => proxyAdmin.recordAccount({ ...entry, org: orgId }) : null });
|
||||
}
|
||||
// #1873 triage-host: the Triage session's two routes answer only the instance owner's own session on
|
||||
@@ -1254,6 +1260,9 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
if (path === '/api/config') return json(res, 200, { board: upstream, viewer: viewerOf(currentSession), ...(organizations && preselect ? { preselect } : {}), ...(tester ? { tester: true } : {}), ...(sso ? { sso: true } : {}), ...(sso?.devOwner ? { devOwner: true } : {}), ...(granted ? { user: true, chatGrants } : {}), ...(!tester && !granted && named && sso !== null && requestRead ? { requests: true, requestWrites: Boolean(send && requestWrite), workspaceFiles: true, projectRemotes: true, projectRemoteWrites: Boolean(send && requestWrite) } : {}), ...(hub ? { federation: hub } : {}), ...(organizations ? { orgSetup: !tester && !granted && named && sso !== null && owner.send !== null } : {}), ...(proxyAdmin && !tester && !granted && named && sso !== null && currentSession?.rootOwner === true ? { proxyAdmin: true, proxyAdminSend: owner.send !== null } : {}), ...(triage && !tester && !granted && named && sso !== null && orgId === null && currentSession?.rootOwner === true ? { triage: true, triageSend: owner.send !== null } : {}), send: !organizations && !tester && Boolean(send) && named, ...(organizations && orgId ? { chatSend: !tester && Boolean(send) && named && orgBusHealthy, settingsSend: !tester && !granted && Boolean(send) && named && orgBusHealthy } : {}), boot, consoleRestart: !tester && named && currentSession?.instanceRole === 'operator' && owner.send !== null && restart !== null && trail !== null, decide: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(decisionWrite) && named && sso !== null, edit: !organizations && !tester && !granted && Boolean(send) && Boolean(projectSave) && named, northStarApprove: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(projectSave) && Boolean(projectFile) && named });
|
||||
if (path === '/healthz') return json(res, 200, { ok: true, ...(sso ? { sso: sso.health() } : {}) });
|
||||
if (path === '/favicon.ico') { res.writeHead(204); return res.end(); }
|
||||
// first-run-fixes-1 (F1): the Dashboard lives at `#/dashboard` on the one page. A typed
|
||||
// `/dashboard` reaches it the way `/proxy` reaches Model setup, after the same fences as `/`.
|
||||
if (path === '/dashboard') { res.writeHead(303, { location: '/#/dashboard', 'cache-control': 'no-store' }); return res.end(); }
|
||||
const file = files.get(path);
|
||||
if (!file) return json(res, 404, { error: 'not found' });
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
// Owner-only instance readiness. Every dependency is a read; no seed, log, receipt or repair.
|
||||
import { setupState } from '../../plugins/src/kinds.mjs';
|
||||
import { readService } from '../../model-proxy/src/setup-state.mjs';
|
||||
|
||||
const states = new Set(['next', 'checking', 'waiting', 'done', 'failed', 'not-applicable', 'optional']);
|
||||
const unavailable = { state: 'failed', reason: "Couldn't check. Open this step to try again.", code: 'setup-check-unavailable' };
|
||||
const json = (res, status, body) => { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(body)); };
|
||||
|
||||
export async function readSetup({ organizations, session, sources = setupState.map(path => () => import(new URL('../../' + path, import.meta.url)).then(m => m.setupState)), service, timeoutMs = 4000, ...deps } = {}) {
|
||||
const controller = new AbortController(), deadline = Date.now() + timeoutMs;
|
||||
let timer;
|
||||
const expired = new Promise((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(Error('setup deadline')); }, timeoutMs); });
|
||||
// Keep this rejection observed even when all the checks complete before the deadline.
|
||||
expired.catch(() => {});
|
||||
const bounded = fn => Promise.race([Promise.resolve().then(fn), expired]);
|
||||
const bound = { signal: controller.signal, deadline };
|
||||
// Load row descriptions while admission runs, so a slow registry read cannot erase their fixes.
|
||||
const loaded = sources.map(load => bounded(load).then(rows => Array.isArray(rows) ? rows : null, () => null));
|
||||
const memo = new Map();
|
||||
const once = (key, fn) => { if (!memo.has(key)) memo.set(key, bounded(fn)); return memo.get(key); };
|
||||
const ctx = { ...deps, signal: controller.signal, service: () => once('service', () => service ? service(bound) : readService({ ...deps, signal: controller.signal })) };
|
||||
if (deps.accounts) ctx.accounts = () => once('accounts', () => deps.accounts(bound));
|
||||
let members = [], memberError = null;
|
||||
try { members = await bounded(() => organizations.members(session, { timeoutMs })); if (!Array.isArray(members)) throw Error(); }
|
||||
catch (e) { memberError = e; }
|
||||
Object.defineProperty(ctx, 'members', { get() { if (memberError) throw memberError; return members; } });
|
||||
ctx.read = (org, name, args) => once(JSON.stringify([org.id, name, args]), async () => {
|
||||
if (org.invalid) throw Error('organization unavailable');
|
||||
if (name === 'status') return org.status(bound);
|
||||
const options = await once(`options:${org.id}`, () => org.options(bound));
|
||||
const reads = {
|
||||
accounts: () => options.proxyCall('proxy.accounts', {}),
|
||||
routes: () => options.bus.routes(),
|
||||
plugins: () => options.proxyCall('plugins', {}),
|
||||
tasks: () => options.bus.tasks(),
|
||||
threads: () => options.chat.threads({}),
|
||||
sessions: () => options.chat.sessions(args),
|
||||
messages: () => options.chat.messages(args),
|
||||
};
|
||||
if (!Object.hasOwn(reads, name)) throw Error('unknown setup read');
|
||||
return reads[name]();
|
||||
});
|
||||
try {
|
||||
const groups = await Promise.all(loaded.map(async (pending, index) => {
|
||||
const definitions = await pending;
|
||||
if (!definitions) return [{ id: `setup.part-${index + 1}`, title: 'Check setup', purpose: 'One part could not report its setup state.', required: true, order: { after: [] }, fix: null, ...unavailable }];
|
||||
return Promise.all(definitions.map(async ({ check, ...row }) => {
|
||||
try {
|
||||
const result = await bounded(() => check(ctx));
|
||||
if (!states.has(result?.state) || typeof result.reason !== 'string') throw Error();
|
||||
return { ...row, state: result.state, reason: result.reason, ...(result.fix ? { fix: result.fix } : {}) };
|
||||
} catch { return { ...row, ...unavailable }; }
|
||||
}));
|
||||
}));
|
||||
return { rows: groups.flat(), organizations: members.map(m => ({ id: m.id })) };
|
||||
} finally { clearTimeout(timer); controller.abort(); }
|
||||
}
|
||||
|
||||
export function setupRoutes(deps) {
|
||||
return table => table.add('GET', '/api/setup', async (req, res, context) => {
|
||||
if (!context.owner || !context.session) return json(res, 403, { error: 'owner-only', message: 'Setup checks are for the instance owner.' });
|
||||
if (context.orgId !== null) return json(res, 404, { error: 'not found' });
|
||||
const { session } = context;
|
||||
// Match Model setup's root-owner admission and principal. Other Console modes keep their readers.
|
||||
const accounts = deps.organizations && session.rootOwner === true && typeof deps.proxyAdmin?.setupAccounts === 'function'
|
||||
? () => deps.proxyAdmin.setupAccounts({ provider: session.provider, iss: session.iss, sub: session.sub }) : deps.accounts;
|
||||
const service = async bound => ({
|
||||
...await (deps.service ? deps.service(bound) : readService({ ...deps, ...bound })),
|
||||
...(deps.proxyAdmin ? { stoppedSetup: deps.proxyAdmin.stoppedSetup } : {}),
|
||||
});
|
||||
return json(res, 200, await readSetup({ ...deps, accounts, session, service }));
|
||||
});
|
||||
}
|
||||
@@ -19,13 +19,12 @@ process.once('exit', () => { for (const child of live) killGroup(child); });
|
||||
// so by default every page this browser opens starts with Show machine sessions on, as if the
|
||||
// person had turned it on before. Pass { machine: false } to see the page as a first visit does.
|
||||
// `args` adds Chromium flags, for example --host-resolver-rules for a test host name.
|
||||
// #1873 CB5: the system Chromium starts with --disable-extensions, so no host extension (and no
|
||||
// native host it would start) runs in a test. A CHROMIUM launcher is the zoom tests' wrapper, which
|
||||
// loads their one extension with --disable-extensions-except, so it gets no blanket flag.
|
||||
// Disable host extensions for every launch, including a custom zoom launcher. The zoom
|
||||
// launcher also sets the profile's default zoom, so it needs no running extension.
|
||||
export async function browser({ machine = true, args = [] } = {}) {
|
||||
const profile = await mkdtemp(join(tmpdir(), 'dewey-brand-browser-'));
|
||||
const child = spawn(process.env.CHROMIUM || '/usr/bin/chromium', [
|
||||
'--headless', '--no-first-run', '--no-default-browser-check', ...(process.env.CHROMIUM ? [] : ['--disable-extensions']),
|
||||
'--headless', '--no-first-run', '--no-default-browser-check', '--disable-extensions',
|
||||
'--disable-dev-shm-usage', '--remote-debugging-pipe', `--user-data-dir=${profile}`, ...args,
|
||||
], { detached: true, stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'] });
|
||||
live.add(child);
|
||||
|
||||
@@ -19,7 +19,7 @@ test('served Console browser: real board fixtures, keyboard, drafts, receipts, t
|
||||
await b.evaluate('document.querySelector("#hide-offline").click()');
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("table.sessions tbody tr").length'), 4);
|
||||
// Rows 129, 154, 191, 194 and 294: chat.js, editor.js, processing.js, agents.js and federation.js are the scripts added, and #1839 adds requests.js (the intake panel under an owner's chat message), all same origin; the list is the pin, so another script is a visible change. #797 adds project-archive.js immediately after chat.js. F2 adds onboarding.js after org-create.js, and F3 adds console-restart.js after it. U2 (#1873) adds workspace-data.js and workspace.js before console-restart.js, and U4b adds tasks-board.js after workspace.js. triage-settings (#1873) adds triage-settings.js after console-restart.js. U5 (#1873) added panes.js (Side by side) just before bus.js; SP6 replaces it with assistant.js (the Assistant page), which bus.js mounts.
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("script")].map(s => s.getAttribute("src"))'), ['/editor.js', '/processing.js', '/org-create.js', '/onboarding.js', '/workspace-data.js', '/workspace.js', '/tasks-board.js', '/console-restart.js', '/triage-settings.js', '/display.js', '/inbox.js', '/files.js', '/project-remote.js', '/autonomy.js', '/packs.js', '/workflows.js', '/federation.js', '/brand.js', '/app.js', '/markdown-preview.js', '/projects.js', '/chat.js', '/project-archive.js', '/agents.js', '/assistant.js', '/bus.js', '/requests.js']);
|
||||
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("script")].map(s => s.getAttribute("src"))'), ['/editor.js', '/processing.js', '/org-create.js', '/onboarding.js', '/setup-checklist.js', '/workspace-data.js', '/workspace.js', '/tasks-board.js', '/console-restart.js', '/triage-settings.js', '/display.js', '/inbox.js', '/files.js', '/project-remote.js', '/autonomy.js', '/packs.js', '/workflows.js', '/federation.js', '/brand.js', '/app.js', '/markdown-preview.js', '/projects.js', '/chat.js', '/project-archive.js', '/agents.js', '/assistant.js', '/bus.js', '/requests.js']);
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('script[src="/processing.js"]').length`), 1);
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('script[src="/chat.js"]').length`), 1);
|
||||
assert.equal(await b.evaluate('!!window.injected'), false);
|
||||
|
||||
@@ -329,7 +329,7 @@ test('D4 hire start: the other proposal checks that run before the decision inse
|
||||
// E2E6 P1-2: every definite refusal of a start keeps its own code and a next step. Only a reply that
|
||||
// never came, could not be read, or the bus server's request codes stay outcome-unknown.
|
||||
test('E2E6 hire start: an unknown project, an unknown agent on fire and an unknown harness keep their code',async()=>{
|
||||
for(const [code,re] of [['project-agents-invalid',/code project/],['organization-unknown-instance',/Agents page/],['harness-off',/Settings > Routing/]]) {
|
||||
for(const [code,re] of [['project-agents-invalid',/code project/],['organization-unknown-instance',/Agents page/],['harness-off',/Settings > Models/]]) {
|
||||
const {r,s}=await startWith(new BusReadError(code));
|
||||
assert.equal(r.status,409,`${code}: ${r.text}`);
|
||||
assert.equal(r.json().error,code);assert.match(r.json().message,re);
|
||||
@@ -373,7 +373,7 @@ test('E2E6 hire start: an apply-phase decision-stale on a fire does not say noth
|
||||
});
|
||||
test('E2E6 hire start: invalid-request from the bus says the values, not the shape, were refused',async()=>{
|
||||
const {r}=await startWith(new BusReadError('invalid-request'));
|
||||
assert.equal(r.status,400);assert.equal(r.json().error,'invalid-request');assert.match(r.json().message,/Settings > Routing/);
|
||||
assert.equal(r.status,400);assert.equal(r.json().error,'invalid-request');assert.match(r.json().message,/Settings > Models/);
|
||||
});
|
||||
test('E2E6 hire start: the bus server request codes and organization-uncertain stay outcome-unknown',async()=>{
|
||||
for(const code of ['revision-conflict-revoked','request-timeout','invalid-envelope','incomplete-request','organization-uncertain'])
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { startServer } from '../src/serve.mjs';
|
||||
import { createDevOwner } from '../src/dev-owner.mjs';
|
||||
import { setupRoutes } from '../src/setup-http.mjs';
|
||||
import { browser } from './browser.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
|
||||
test('an empty organization Console makes no organization requests or errors and hides business settings and the board address', { timeout: 30000 }, async t => {
|
||||
const organizations = { list: async () => [], members: async () => [] };
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations, board: 'http://127.0.0.1:9', log: () => {},
|
||||
routes: [setupRoutes({ organizations, service: async () => ({ release: {}, init: {}, unit: {} }), docker: async () => false, runs: () => [] })] });
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
const errors = [], reads = [];
|
||||
b.on('Network.responseReceived', ({ response }) => { if (response.status >= 400 && response.status < 500) errors.push([response.status, response.url]); });
|
||||
b.on('Network.requestWillBeSent', ({ request }) => reads.push(new URL(request.url).pathname));
|
||||
await b.call('Network.enable');
|
||||
const wait = expression => b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/dashboard`);
|
||||
await wait('document.querySelector(".setup-card")');
|
||||
await wait('document.querySelector("#project-tree")?.textContent.includes("Create an organization")');
|
||||
assert.equal(await b.evaluate('document.querySelector("#board-url").getClientRects().length'), 0);
|
||||
assert.doesNotMatch(await b.evaluate('document.body.innerText'), /Projects unavailable|Board: http/);
|
||||
await b.evaluate('location.hash="#/settings/appearance"');
|
||||
await wait('document.querySelector("#settings-nav")');
|
||||
assert.doesNotMatch(await b.evaluate('document.querySelector("#settings-nav").textContent'), /This business|Routing|Launch limits|Token use|Assistant|Business|Agents/);
|
||||
// Cover periodic processing refresh, too.
|
||||
await new Promise(resolve => setTimeout(resolve, 5500));
|
||||
for (const path of ['/api/business', '/api/processing', '/api/chat/projects', '/api/chat/threads', '/api/bus-status']) assert.ok(!reads.includes(path), path);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { firstOrg } from './first-org-fixture.mjs';
|
||||
import { browser } from './browser.mjs';
|
||||
test('the first organization selects the owner model, completes Quick Setup and finishes checklist step three', { timeout: 60000 }, async t => {
|
||||
const f = await firstOrg(t), b = await browser({ machine: false, args: ['--disable-extensions'] }); t.after(() => b.close());
|
||||
const wait = expression => b.evaluate(`(async()=>{for(let n=0;n<150;n++){if(${expression})return;await new Promise(r=>setTimeout(r,40));}throw Error(${JSON.stringify(expression)})})()`);
|
||||
await b.navigate(f.base + '/#/settings/organizations?new=1');
|
||||
await wait('document.querySelector("#org-new-form [data-write]") && !document.querySelector("#org-new-form [data-write]").disabled');
|
||||
await b.evaluate(`document.querySelector('#org-new-id').value='alpha';document.querySelector('#org-new-form [data-write]').click()`);
|
||||
await wait('document.querySelector("#org-paths") && !document.querySelector("#org-paths").hidden');
|
||||
assert.equal(await b.evaluate(`document.querySelector('#org-preset option[value="cliproxy"]').disabled`), false);
|
||||
await b.evaluate(`document.querySelector('#org-preset').value='cliproxy';document.querySelector('#org-preset').dispatchEvent(new Event('change',{bubbles:true}))`);
|
||||
assert.equal(await b.evaluate(`document.querySelector('#org-model').value`), 'claude-claude-opus-5-5');
|
||||
assert.match(await b.evaluate(`document.querySelector('#org-model').textContent`), /claude-opus-5-5/);
|
||||
await b.evaluate(`document.querySelector('#org-quick-open').click();document.querySelector('#org-risk-accept').click();document.querySelector('#org-quick-run').click()`);
|
||||
await wait(`document.querySelector('[data-quick-step="5"] .org-pill')?.textContent === 'Done' || [...document.querySelectorAll('[data-quick-step] .org-pill')].some(e=>e.textContent==='Stopped')`);
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-quick-step] .org-pill')].map(e=>e.textContent)`), Array(6).fill('Done'), await b.evaluate(`document.querySelector('#org-quick-steps').innerText`));
|
||||
const shown = await f.service.showOrg({ ...f.ctx, principal: { provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner' } }, 'alpha');
|
||||
assert.deepEqual(shown.doc.roles.chief.vars, shown.doc.roles.assistant.vars);
|
||||
assert.deepEqual(shown.doc.launch.instances, ['assistant'], 'routing the chief must not launch it');
|
||||
const setup = await f.call('GET', '/api/setup');
|
||||
const routed = setup.body.rows.find(r => r.id === 'agents.routed');
|
||||
assert.doesNotMatch(routed.reason, /Choose a model for both/);
|
||||
assert.equal(routed.state, 'checking');
|
||||
assert.equal(routed.reason, 'The chosen programs have not passed their check yet. Choose models to check them.');
|
||||
await b.navigate(f.base + '/#/dashboard');
|
||||
await wait('document.querySelectorAll(".checklist-step").length === 7');
|
||||
assert.equal(await b.evaluate(`document.querySelectorAll('.setup-card ol .checklist-step')[2].classList.contains('setup-done')`), true);
|
||||
assert.doesNotMatch(await b.evaluate(`document.querySelectorAll('.setup-card ol .checklist-step')[3].textContent`), /Choose a model for both/);
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
// Real organization service and broker, with a scratch-only model service and owner client.
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { startServer } from '../src/serve.mjs';
|
||||
import { createDevOwner } from '../src/dev-owner.mjs';
|
||||
import { createOrgAdmin } from '../src/org-admin.mjs';
|
||||
import { organizationConsole } from '../src/organizations.mjs';
|
||||
import { setupRoutes } from '../src/setup-http.mjs';
|
||||
import * as service from '../../organization/src/org-service.mjs';
|
||||
import * as registry from '../../organization/src/org-registry.mjs';
|
||||
import { createOwnerProxyRuntime } from '../../bus/src/proxy-owner.mjs';
|
||||
import { startBroker } from '../../bus/src/runtime.mjs';
|
||||
import { Registry } from '../../seat/src/session.mjs';
|
||||
import { bootConfig, orgPaths } from '../../cli/src/config.mjs';
|
||||
import { createProxyAdmin } from '../../model-proxy/src/admin-control.mjs';
|
||||
import { ownerModelsReader } from '../../model-proxy/src/ride.mjs';
|
||||
import { initializeProxy, installPaths } from '../../model-proxy/src/settings.mjs';
|
||||
import { writeOffered } from '../../model-proxy/src/models-offered.mjs';
|
||||
import { PIN } from '../../model-proxy/src/common.mjs';
|
||||
export const bytes = dir => fs.readdirSync(dir, { recursive: true }).sort().map(name => {
|
||||
const file = join(dir, name); return [name, fs.lstatSync(file).isDirectory() ? null : fs.readFileSync(file).toString('base64')];
|
||||
});
|
||||
export async function firstOrg(t, { mode = 'organizations', viewer = 'root', readFailure = null } = {}) {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'fo-')), configDir = join(root, 'config'), dataRoot = join(root, 'data');
|
||||
fs.mkdirSync(configDir, { mode: 0o700 }); fs.mkdirSync(dataRoot, { mode: 0o700 });
|
||||
const pendingReads = [];
|
||||
const brokers = new Map(), state = { keys: [], accounts: [{ id: 'fixture', name: 'fixture', auth_index: 'fixture', provider: 'claude', status: 'active' }], models: [{ id: 'claude-opus-5-5' }, { id: 'claude-sonnet-4-6' }], reads: 0 };
|
||||
const key = 'fixture-management-value';
|
||||
const proxy = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, 'http://127.0.0.1');
|
||||
if (url.pathname === '/v1/models') { res.writeHead(state.keys.includes(req.headers.authorization?.slice(7)) ? 200 : 401); res.end('{}'); return; }
|
||||
if (req.headers.authorization !== `Bearer ${key}`) { res.writeHead(401); res.end('{}'); return; }
|
||||
if (url.pathname === '/v8/management/config/access/api-keys') {
|
||||
if (req.method === 'PUT') { const parts = []; for await (const p of req) parts.push(p); state.keys = JSON.parse(Buffer.concat(parts)); res.end('{"status":"ok"}'); }
|
||||
else res.end(JSON.stringify(state.keys));
|
||||
return;
|
||||
}
|
||||
const value = url.pathname === '/v8/management/credentials' ? { files: state.accounts }
|
||||
: url.pathname === '/v8/management/credentials/models' ? { models: state.models } : [];
|
||||
res.end(JSON.stringify(value));
|
||||
});
|
||||
let server;
|
||||
t.after(async () => {
|
||||
// Release synthetic stalls so a broken production deadline cannot strand the test process.
|
||||
for (const resolve of pendingReads) resolve({ files: state.accounts });
|
||||
if (server) { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
|
||||
for (const b of brokers.values()) await b.close();
|
||||
proxy.closeAllConnections(); await new Promise(resolve => proxy.close(resolve));
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
const hash = text => createHash('sha256').update(text).digest('hex');
|
||||
const pin = { ...PIN, binary: { sha256: hash('binary') }, panel: { ...PIN.panel, sha256: hash('panel') } };
|
||||
const paths = installPaths(dataRoot, pin); fs.mkdirSync(join(paths.dir, 'static'), { recursive: true }); fs.writeFileSync(paths.binary, 'binary'); fs.writeFileSync(paths.panel, 'panel');
|
||||
const settings = await initializeProxy({ configDir, dataRoot, key, pin });
|
||||
await new Promise(resolve => proxy.listen(settings.port, '127.0.0.1', resolve));
|
||||
writeOffered(dataRoot, { version: 1, providers: { claude: { on: ['claude-opus-5-5'], seen: ['claude-opus-5-5', 'claude-sonnet-4-6'] } } });
|
||||
const runtime = createOwnerProxyRuntime({ configDir, dataRoot, checkHuman: () => { state.reads++; if (readFailure && readFailure !== 'slow') throw Object.assign(Error('/private/path token=hidden'), { code: readFailure }); }, load: async () => ({
|
||||
getCredentials: async () => readFailure === 'slow' ? new Promise(resolve => pendingReads.push(resolve)) : { files: state.accounts },
|
||||
getCredentialModels: async () => ({ models: state.models }), getUpstreamGroups: async () => [],
|
||||
}) });
|
||||
const ctx = { configDir, dataRoot, instance: 'test' }, projects = [];
|
||||
const bus = {
|
||||
busStatus: async (_ctx, id) => ({ healthy: brokers.has(id), pid: brokers.has(id) ? process.pid : null }),
|
||||
busStart: async (_ctx, id) => {
|
||||
const org = await registry.resolveOrg(ctx, id); new Registry(org.root);
|
||||
const config = bootConfig({ system: { configVersion: 1, environment: 'development', dataRoot, execution: { backend: 'docker', provider: 'zai', model: 'glm-5.3-flash', adapter: 'mock' }, proxy: settings }, businessId: id, orgRoot: org.root, env: { HOME: root, MOSAIC_CONFIG: join(configDir, 'config.json') } });
|
||||
const b = await startBroker(config); brokers.set(id, b); return { healthy: true };
|
||||
},
|
||||
};
|
||||
const options = ({ id }) => ({ send: async () => ({}), bus: { routes: () => ask(id, 'routes') }, proxyCall: (verb, args) => ask(id, verb, args), chat: {
|
||||
projects: async () => projects, threads: async () => [], createProject: async args => { const p = { id: '20000000-0000-4000-8000-000000000002', ...args }; projects.push(p); return p; },
|
||||
} });
|
||||
function ask(id, verb, args) { const b = brokers.get(id); if (!b) throw Error('not started'); return b.broker.request(b.broker.bindHuman({ business: id, human: 'local-dev-owner', via: 'cli', outsideAgent: true }), { verb, args }); }
|
||||
const organizations = mode === 'organizations' ? organizationConsole({ ctx, ...registry, showOrg: service.showOrg, orgPaths, busStatus: bus.busStatus, options }) : null;
|
||||
const ownerModels = ownerModelsReader({ proxy: () => true, organizations, ownerProxy: runtime, rideRiders: async () => [], timeoutMs: 30 });
|
||||
const admin = createOrgAdmin({ service, registry, bus, context: () => ctx, ownerModels, devFixture: async () => ({ ready: false }) });
|
||||
const proxyAdmin = createProxyAdmin({ configDir, dataRoot, ownerProxy: runtime });
|
||||
const owner = createDevOwner();
|
||||
const sso = viewer === 'root' && mode !== 'sso' ? owner : { ...owner, devOwner: false, publicHost: 'console.example', publicOrigin: 'https://console.example', session: () => ({ ...owner.session(), ...(viewer === 'root' ? {} : { rootOwner: false, instanceRole: 'member', ...(viewer === 'member' ? { user: 'member' } : {}) }) }) };
|
||||
server = await startServer({ port: 0, sso, organizations, orgAdmin: admin, proxyAdmin, send: async () => ({}), board: 'http://127.0.0.1:9', log: () => {}, routes: [setupRoutes({ organizations, proxyAdmin, service: async () => ({ release: { verified: true }, init: { initialized: true }, unit: { active: 'active', healthy: true, listening: true } }), docker: async () => false, runs: () => [] })] });
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
const call = (method, path, body) => new Promise((resolve, reject) => {
|
||||
const text = body === undefined ? null : JSON.stringify(body);
|
||||
const req = http.request(base + path, { method, headers: {
|
||||
...(sso.publicHost ? { Host: sso.publicHost } : {}),
|
||||
...(text ? { Origin: base, 'sec-fetch-site': 'same-origin', 'content-type': 'application/json', 'content-length': Buffer.byteLength(text) } : {}),
|
||||
} }, res => {
|
||||
let text = ''; res.setEncoding('utf8'); res.on('data', chunk => { text += chunk; });
|
||||
res.on('end', () => { try { resolve({ status: res.statusCode, body: JSON.parse(text) }); } catch (error) { reject(error); } });
|
||||
}); req.on('error', reject); req.end(text);
|
||||
});
|
||||
return { base, call, ctx, configDir, dataRoot, runtime, state, brokers, ask, service };
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { firstOrg, bytes } from './first-org-fixture.mjs';
|
||||
const preset = result => result.body.presets.find(p => p.name === 'cliproxy');
|
||||
test('first organization presets are read-only and Quick Setup boots the shared provider and automatic model key', async t => {
|
||||
const f = await firstOrg(t);
|
||||
const before = [bytes(f.configDir), bytes(f.dataRoot)];
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const r = await f.call('GET', '/api/org-presets'); assert.equal(r.status, 200);
|
||||
assert.deepEqual(preset(r).available, { ok: true });
|
||||
assert.deepEqual(preset(r).models.map(m => m.key), ['claude-claude-opus-5-5'], 'the switched-off Sonnet row stays out');
|
||||
}
|
||||
assert.deepEqual([bytes(f.configDir), bytes(f.dataRoot)], before);
|
||||
const template = await f.call('GET', '/api/org-template?id=alpha&preset=cliproxy'); assert.equal(template.status, 200);
|
||||
const chosen = await f.call('GET', '/api/org-template?id=alpha&preset=cliproxy&model=claude-claude-opus-5-5'); assert.deepEqual(chosen.body.doc, template.body.doc);
|
||||
const made = await f.call('POST', '/api/orgs', { id: 'alpha', doc: template.body.doc }); assert.equal(made.status, 201, JSON.stringify(made));
|
||||
const shown = await f.service.showOrg({ ...f.ctx, principal: { provider: 'local-dev', iss: 'local-dev', sub: 'local-dev-owner' } }, 'alpha');
|
||||
assert.deepEqual(shown.doc.plugins['model-provider'], ['cliproxy']);
|
||||
assert.deepEqual(shown.doc.roles.assistant.vars, { harness: 'claude-code', model: 'claude-claude-opus-5-5', thinking: 'low' });
|
||||
for (const step of ['queue', 'project/work']) {
|
||||
const result = await f.call('POST', `/api/orgs/alpha/setup/${step}`, { mode: 'local-only', acceptLocalLossRisk: true }); assert.equal(result.status, 201, JSON.stringify(result));
|
||||
}
|
||||
const started = await f.call('POST', '/api/orgs/alpha/setup/bus', {}); assert.equal(started.status, 201, JSON.stringify(started));
|
||||
const routes = await f.ask('alpha', 'routes');
|
||||
assert.equal(routes.catalogue.status, 'ready'); assert.equal(routes.instances.assistant.model, 'claude-claude-opus-5-5'); assert.equal(routes.instances.assistant.harness, 'claude-code');
|
||||
assert.equal(f.state.keys.some(k => k.includes('-alpha-sentinel-')), true, 'normal broker boot registers the first organization');
|
||||
const b = f.brokers.get('alpha');
|
||||
const ready = await b.modelPreflight({ business: 'alpha', role: 'assistant' });
|
||||
assert.equal(f.state.keys.includes(ready.key), true, 'normal launch preflight issues the model key without an owner action');
|
||||
const setup = await f.call('GET', '/api/setup'); assert.equal(setup.body.rows.find(r => r.id === 'organization.ready').state, 'done');
|
||||
});
|
||||
test('four other viewer and Console cases never read the owner catalogue', async t => {
|
||||
for (const options of [{ viewer: 'member' }, { viewer: 'org-owner' }, { mode: 'single' }, { mode: 'sso' }]) {
|
||||
const f = await firstOrg(t, options), before = f.state.reads;
|
||||
const r = await f.call('GET', '/api/org-presets');
|
||||
if (options.viewer) assert.equal(r.status, options.viewer === 'member' ? 403 : 404);
|
||||
else { assert.equal(r.status, 200); assert.equal(preset(r).available.ok, false); assert.match(preset(r).available.reason, /No organization uses/); assert.doesNotMatch(preset(r).available.reason, /Ride all/); }
|
||||
assert.equal(f.state.reads, before);
|
||||
}
|
||||
});
|
||||
test('slow, busy, paused and refused catalogue reads leave the form usable and disclose nothing', { timeout: 3000 }, async t => {
|
||||
for (const failure of ['slow', 'proxy-admin-busy', 'human-required', 'paused']) {
|
||||
const f = await firstOrg(t, { readFailure: failure }), before = [bytes(f.configDir), bytes(f.dataRoot)];
|
||||
const start = Date.now(), r = await f.call('GET', '/api/org-presets');
|
||||
assert.equal(r.status, 200); assert.ok(Date.now() - start < 1500);
|
||||
assert.deepEqual(preset(r).available, { ok: false, reason: 'Your models could not be checked. Open Model setup to try again.' });
|
||||
assert.doesNotMatch(JSON.stringify(r.body), /private|hidden|token=|human-required|proxy-admin-busy/);
|
||||
assert.deepEqual([bytes(f.configDir), bytes(f.dataRoot)], before);
|
||||
}
|
||||
const f = await firstOrg(t), before = [bytes(f.configDir), bytes(f.dataRoot)];
|
||||
await f.runtime.withRemoval(async () => assert.equal(preset(await f.call('GET', '/api/org-presets')).available.ok, false));
|
||||
assert.deepEqual([bytes(f.configDir), bytes(f.dataRoot)], before);
|
||||
});
|
||||
test('no account or no offered model shares the account connection reason', async t => {
|
||||
const f = await firstOrg(t);
|
||||
for (const field of ['accounts', 'models']) {
|
||||
const saved = f.state[field]; f.state[field] = [];
|
||||
const p = preset(await f.call('GET', '/api/org-presets'));
|
||||
assert.equal(p.available.ok, false); assert.match(p.available.reason, /account on the Model setup page/); assert.doesNotMatch(p.available.reason, /Ride all|No organization/);
|
||||
f.state[field] = saved;
|
||||
}
|
||||
});
|
||||
@@ -91,9 +91,10 @@ const homeReady = 'document.querySelector("[data-ws-home] [data-ws-tiles] [data-
|
||||
test('The Dashboard tiles add both answering organizations\' numbers, one row, each tile a link to the page that lists it', async t => {
|
||||
const { b, wait, text } = await setup(t);
|
||||
await wait(homeReady);
|
||||
// One row: no second tile group anywhere on the page, and the row leads the page under its heading.
|
||||
// One tile row follows the setup checks under the dashboard heading.
|
||||
assert.equal(await b.evaluate('document.querySelectorAll("[data-ws-home] [data-ws-tiles]").length'), 1);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-home] .ws-vh").nextElementSibling.hasAttribute("data-ws-tiles")'), true);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-home] .ws-vh").nextElementSibling.hasAttribute("data-setup-region")'), true);
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-home] [data-setup-region]").nextElementSibling.hasAttribute("data-ws-tiles")'), true);
|
||||
assert.deepEqual(await b.evaluate(tileKeys('[data-ws-home]')), ['agents', 'orgs', 'needs', 'tasks', 'done', 'projects']);
|
||||
// Agents working of total: acme's coder works; beta's pm waits; chief and writer run nothing.
|
||||
assert.equal(await b.evaluate(big('[data-ws-home]', 'agents')), '1 of 4');
|
||||
|
||||
@@ -461,7 +461,7 @@ test('the Settings page ships the organization assets', async t => {
|
||||
assert.match(index.raw, /<script src="\/org-create\.js" defer><\/script>/);
|
||||
assert.match(index.raw, /<link rel="stylesheet" href="\/org-create\.css">/);
|
||||
const js = await c.call('GET', '/org-create.js');
|
||||
assert.equal(js.status, 200); assert.match(js.raw, /window\.MosaicOrgCreate = \{ markup, mount \}/);
|
||||
assert.equal(js.status, 200); assert.match(js.raw, /window\.MosaicOrgCreate = \{ markup, mount, quickDocument \}/);
|
||||
assert.equal((await c.call('GET', '/org-create.css')).status, 200);
|
||||
const bus = readFileSync(new URL('../src/public/bus.js', import.meta.url), 'utf8');
|
||||
assert.match(bus, /\['organizations','Organizations'\]/);
|
||||
@@ -584,6 +584,64 @@ test('preset routes expose installed choices and refuse invalid queries', async
|
||||
assert.equal((await c.call('GET', '/api/org-presets?extra=x')).status, 422);
|
||||
});
|
||||
|
||||
// first-run-fixes-1 (B2): the Test model preset is offered only when the instance's dev fixture
|
||||
// would answer a chat: a record for this instance whose endpoint process still runs.
|
||||
test('B2: the Test model preset is hidden until the instance\'s dev fixture runs', async t => {
|
||||
const { spawn } = await import('node:child_process');
|
||||
const { chmodSync } = await import('node:fs');
|
||||
const { ENDPOINT } = await import('../../cli/src/dev-fixture.mjs');
|
||||
const { FIXTURE_ENTRY } = await import('../../plugins/model-provider/fixture/index.mjs');
|
||||
const { fixtureState } = await import('../src/org-admin.mjs');
|
||||
const service = await import('../../organization/src/org-service.mjs');
|
||||
const dataRoot = mkdtempSync(join(tmpdir(), 'b2-fixture-')); t.after(() => rmSync(dataRoot, { recursive: true, force: true }));
|
||||
const context = async () => ({ configDir: '/cfg', dataRoot, instance: 'test' });
|
||||
const c = await console_(t, { orgAdmin: createOrgAdmin({ service, context, devFixture: fixtureState(context) }) });
|
||||
const fixtureOf = async () => { const r = await c.call('GET', '/api/org-presets'); assert.equal(r.status, 200, r.raw); return r.body.presets.find(p => p.name === 'fixture')?.available; };
|
||||
const notReady = undefined;
|
||||
assert.deepEqual(await fixtureOf(), notReady, 'no fixture record');
|
||||
const dir = join(dataRoot, 'dev-fixture'); mkdirSync(dir, { mode: 0o700 });
|
||||
const record = over => { const file = join(dir, 'fixture.json'); writeFileSync(file, JSON.stringify({ fixtureVersion: 1, model: 'deterministic', instance: 'test', entry: FIXTURE_ENTRY, ...over })); chmodSync(file, 0o600); return file; };
|
||||
record({ endpoint: 'http://127.0.0.1:45678', port: 45678, pid: process.pid });
|
||||
assert.deepEqual(await fixtureOf(), notReady, 'a recorded pid that is not the endpoint');
|
||||
const child = spawn(process.execPath, [ENDPOINT], { env: { PATH: process.env.PATH, MOSAIC_FIXTURE_TTL_S: '60' }, stdio: ['ignore', 'pipe', 'ignore'] });
|
||||
t.after(() => child.kill('SIGTERM'));
|
||||
const ready = await new Promise((resolve, reject) => { let out = ''; child.stdout.on('data', d => { out += d; if (out.includes('\n')) resolve(JSON.parse(out)); }); child.on('exit', code => reject(new Error(`endpoint exited ${code}`))); });
|
||||
const at = { endpoint: `http://127.0.0.1:${ready.port}`, port: ready.port, pid: child.pid };
|
||||
record({ ...at, instance: 'other' });
|
||||
assert.deepEqual(await fixtureOf(), notReady, 'a fixture started for another instance');
|
||||
record(at);
|
||||
assert.deepEqual(await fixtureOf(), { ok: true }, 'this instance\'s running endpoint');
|
||||
// Review P3-2: an endpoint started from another checkout's copy reads ready too.
|
||||
const elsewhere = join(dataRoot, 'other-checkout', 'packages', 'plugins', 'model-provider', 'fixture'); mkdirSync(elsewhere, { recursive: true });
|
||||
writeFileSync(join(elsewhere, 'endpoint.mjs'), "process.stdout.write('{}\\n'); setInterval(() => {}, 1000);\n");
|
||||
const other = spawn(process.execPath, [join(elsewhere, 'endpoint.mjs')], { env: { PATH: process.env.PATH }, stdio: ['ignore', 'pipe', 'ignore'] });
|
||||
t.after(() => other.kill('SIGTERM'));
|
||||
await new Promise((resolve, reject) => { other.stdout.once('data', resolve); other.on('exit', code => reject(new Error(`copy exited ${code}`))); });
|
||||
record({ ...at, pid: other.pid });
|
||||
assert.deepEqual(await fixtureOf(), { ok: true }, 'an endpoint run from another checkout');
|
||||
record(at);
|
||||
chmodSync(record(at), 0o644);
|
||||
assert.deepEqual(await fixtureOf(), notReady, 'a record the launcher would refuse');
|
||||
const throws = await console_(t, { orgAdmin: createOrgAdmin({ service, context, devFixture: async () => { throw new Error('read failed'); } }) });
|
||||
assert.deepEqual((await throws.call('GET', '/api/org-presets')).body.presets.find(p => p.name === 'fixture')?.available, notReady, 'a failing read is not ready');
|
||||
assert.equal(await fixtureState(async () => null)(), undefined, 'no instance context says nothing');
|
||||
assert.equal(typeof defaultOrgAdmin({}).devFixture, 'function', 'the default wiring reads the fixture');
|
||||
});
|
||||
|
||||
// first-run-fixes-1 follow-up (Lead on P3-1): an owner is never told to open a terminal. No
|
||||
// presets reason names the fixture command, or any `mosaic` command, whether or not it runs.
|
||||
test('the presets response names no command for an owner to run', async t => {
|
||||
const service = await import('../../organization/src/org-service.mjs');
|
||||
const context = async () => ({ configDir: '/cfg', dataRoot: '/data', instance: 'test' });
|
||||
for (const [devFixture, listed] of [[async () => ({ ready: false }), false], [async () => ({ ready: true }), true], [async () => { throw new Error('read failed'); }, false]]) {
|
||||
const c = await console_(t, { orgAdmin: createOrgAdmin({ service, context, devFixture }) });
|
||||
const r = await c.call('GET', '/api/org-presets');
|
||||
assert.equal(r.status, 200, r.raw);
|
||||
assert.equal(r.body.presets.some(p => p.name === 'fixture'), listed, 'the Test model entry is listed only while running');
|
||||
assert.doesNotMatch(r.raw, /mosaic |fixture init|fixture start|--instance|`/i);
|
||||
}
|
||||
});
|
||||
|
||||
test('organization delete route enforces write fence and validates confirmation and revision', async t => {
|
||||
const c = await console_(t);
|
||||
assert.equal((await c.call('POST', '/api/orgs/acme/delete', { confirm: 'acme', revision: 1 }, { 'sec-fetch-site': 'cross-site' })).status, 403);
|
||||
|
||||
@@ -6,6 +6,7 @@ import assert from 'node:assert/strict';
|
||||
import { startServer } from '../src/serve.mjs';
|
||||
import { createDevOwner } from '../src/dev-owner.mjs';
|
||||
import { createOrgAdmin } from '../src/org-admin.mjs';
|
||||
import { setupRoutes } from '../src/setup-http.mjs';
|
||||
import { browser } from './browser.mjs';
|
||||
import { close } from './fixture.mjs';
|
||||
|
||||
@@ -23,10 +24,12 @@ async function consoleWith(t, ids) {
|
||||
const registry = { listOrgs: async () => [...docs.keys()].map(id => ({ id, state: 'active' })) };
|
||||
const organizations = {
|
||||
list: async () => [...docs.keys()].map(id => ({ id, label: id, busHealthy: true })),
|
||||
members: async () => [],
|
||||
resolve: async id => docs.has(id) ? { busHealthy: true, send: async () => ({}), reads: { business: async () => ({ business: { id, projects: ['work'], appearance: docs.get(id).appearance } }), busStatus: async () => ({ live: true }) }, bus: {} } : null,
|
||||
};
|
||||
const orgAdmin = createOrgAdmin({ service, registry, context: async () => ({ configDir: '/cfg', dataRoot: '/data', instance: 'test' }) });
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations, orgAdmin, send: async () => ({}), board: 'http://127.0.0.1:9', log: () => {} });
|
||||
const routes = ids.length ? [] : [setupRoutes({ organizations, service: async () => ({ release: {}, init: {}, unit: {} }), docker: async () => false, runs: () => [] })];
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations, orgAdmin, routes, send: async () => ({}), board: 'http://127.0.0.1:9', log: () => {} });
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
const wait = (expression, label = expression) => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error('Timed out: '+${JSON.stringify(label)}+'\\n'+document.body.innerText.slice(0,800))})()`);
|
||||
@@ -72,16 +75,16 @@ test('the sidebar Organizations group offers New organization', { timeout: 60000
|
||||
await formFocused('#/orgs/alpha', 'sidebar');
|
||||
});
|
||||
|
||||
test('the no-organization empty state offers New organization next to its Settings link', { timeout: 60000 }, async t => {
|
||||
test('the empty dashboard explains organization setup and keeps its sidebar create link', { timeout: 60000 }, async t => {
|
||||
const { base, b, wait, formFocused } = await consoleWith(t, []);
|
||||
await b.viewport(1400, 900);
|
||||
await b.navigate(`${base}#/`);
|
||||
const button = `document.querySelector('#held a.btn[href="#/settings/organizations?new=1"]')`;
|
||||
await wait(`document.querySelector('.setup-card ol .checklist-step:nth-child(3)')`, 'setup checklist');
|
||||
assert.match(await b.evaluate(`document.querySelector('.setup-card ol .checklist-step:nth-child(3)').textContent`), /Create your organization/);
|
||||
assert.match(await b.evaluate(`document.querySelector('#ws-org-list').textContent`), /None yet. Step 3 creates one/);
|
||||
const button = `document.querySelector('#workspace-nav a.ws-add[href="#/settings/organizations?new=1"]')`;
|
||||
await wait(button, 'empty state button');
|
||||
const held = await b.evaluate(`document.querySelector('#held').textContent`);
|
||||
assert.match(held, /No organizations yet/);
|
||||
assert.equal(await b.evaluate(`!!document.querySelector('#held a[href="#/settings/organizations"]')`), true, 'the Settings link stays');
|
||||
assert.equal(await b.evaluate(`${button}.textContent`), 'New organization');
|
||||
assert.equal(await b.evaluate(`${button}.getAttribute('aria-label')`), 'New organization');
|
||||
await b.evaluate(`${button}.click()`);
|
||||
await formFocused('#', 'empty state');
|
||||
});
|
||||
@@ -21,6 +21,39 @@ test('setup paths and preset controls are visible', { timeout: 45000 }, async t
|
||||
await b.evaluate(`document.querySelector('#org-quick-open').click()`);
|
||||
await wait('!document.querySelector("#org-quick").hidden');
|
||||
for (const selector of ['#org-project', '#org-project-remote', '#org-risk-accept', '#org-quick-run']) assert.equal(await shown(selector), true, selector);
|
||||
await b.evaluate(`document.querySelector('#org-advanced-open').click()`);
|
||||
await wait('!document.querySelector("#org-editor").hidden');
|
||||
assert.equal(await b.evaluate(`document.querySelector('#org-editor-verb details').open`), false);
|
||||
assert.equal(await b.evaluate(`document.querySelector('#org-editor-verb summary').textContent`), 'Command line');
|
||||
assert.match(await b.evaluate(`document.querySelector('#org-editor-verb code').textContent`), /mosaic org/);
|
||||
});
|
||||
|
||||
// first-run-fixes-1 (F6): the walk found the local-only refusal at the top of the panel, scrolled
|
||||
// away from the checkbox and the button. It now shows under the checkbox, which takes focus.
|
||||
test('F6: an unticked local-only risk box says so beside itself and takes focus', { timeout: 45000 }, async t => {
|
||||
const admin = createOrgAdmin({ service, registry: { listOrgs: async () => [] }, context: async () => ({ configDir: '/cfg', dataRoot: '/data', instance: 'test' }) });
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), orgAdmin: admin, send: async () => ({}), board: 'http://127.0.0.1:9', log: () => {} }); t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
const wait = expression => b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/settings/organizations`);
|
||||
await wait('document.querySelector("#org-new-form [data-write]") && !document.querySelector("#org-new-form [data-write]").disabled');
|
||||
await b.evaluate(`document.querySelector('#org-new-id').value='alpha';document.querySelector('#org-new-form [data-write]').click()`);
|
||||
await wait('document.querySelector("#org-paths") && !document.querySelector("#org-paths").hidden');
|
||||
await b.evaluate(`document.querySelector('#org-quick-open').click()`);
|
||||
await wait('!document.querySelector("#org-quick").hidden');
|
||||
// A name refusal first: once the name is fixed, its banner goes and only the risk line shows.
|
||||
const project = await b.evaluate(`(()=>{const p=document.querySelector('#org-project'),v=p.value;p.value='bad name';document.querySelector('#org-quick-run').click();return v})()`);
|
||||
assert.equal(await b.evaluate(`(()=>{const banner=document.querySelector('#org-banner');return banner.hidden?'':banner.textContent})()`), 'Enter a valid project name.');
|
||||
await b.evaluate(`document.querySelector('#org-project').value=${JSON.stringify(project || 'work')}`);
|
||||
await b.evaluate(`document.querySelector('#org-quick-run').click()`);
|
||||
const line = 'Accept the risk of local-only repositories to continue.';
|
||||
const seen = await b.evaluate(`(()=>{const box=document.querySelector('#org-risk-accept'),err=document.querySelector('#org-risk-error'),banner=document.querySelector('#org-banner');
|
||||
return {text:err?.textContent,shown:!!err&&!err.hidden&&err.getClientRects().length>0,next:box.closest('label').nextElementSibling===err,
|
||||
describedby:box.getAttribute('aria-describedby'),invalid:box.getAttribute('aria-invalid'),focus:document.activeElement===box,
|
||||
banner:banner.hidden?'':banner.textContent,steps:document.querySelectorAll('[data-quick-step]').length}})()`);
|
||||
assert.deepEqual(seen, { text: line, shown: true, next: true, describedby: 'org-risk-error', invalid: 'true', focus: true, banner: '', steps: 0 });
|
||||
await b.evaluate(`document.querySelector('#org-risk-accept').click()`);
|
||||
assert.deepEqual(await b.evaluate(`(()=>{const box=document.querySelector('#org-risk-accept'),err=document.querySelector('#org-risk-error');return {hidden:err.hidden,text:err.textContent,invalid:box.getAttribute('aria-invalid')}})()`), { hidden: true, text: '', invalid: null });
|
||||
});
|
||||
|
||||
for (const scenario of ['bus-refused', 'project-refused', 'project-unknown', 'success']) test(`quick setup creates real repositories: ${scenario}`, { timeout: 45000 }, async t => {
|
||||
@@ -59,18 +92,18 @@ for (const scenario of ['bus-refused', 'project-refused', 'project-unknown', 'su
|
||||
assert.match(await b.evaluate(`document.querySelector('[data-quick-step="3"]').textContent`), /bus refused/);
|
||||
assert.equal(await b.evaluate('document.activeElement.dataset.quickStep'), '3');
|
||||
}
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-quick-step="3"] code').textContent`), 'mosaic bus start alpha --dev-local-owner --detach');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-quick-step="3"] code')`), null);
|
||||
assert.equal(starts, 1);
|
||||
assert.ok(existsSync(join(dataRoot, 'org-runtime/alpha/checkout/.git')));
|
||||
assert.ok(existsSync(join(dataRoot, 'org-runtime/alpha/projects/work/.git')));
|
||||
if (scenario === 'success') {
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-quick-step="5"] code').textContent`), 'mosaic project init alpha work');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-quick-step="5"] code')`), null);
|
||||
assert.ok(existsSync(join(dataRoot, 'org-runtime/alpha/projects/alpha/work/spec/north-star.md')));
|
||||
const readback = await b.evaluate(`fetch('/api/orgs/alpha/setup/records/work').then(r=>r.json())`);
|
||||
assert.equal(readback.state, 'done'); assert.equal(readback.verb, 'mosaic project init alpha work');
|
||||
}
|
||||
if (scenario !== 'bus-refused') {
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-quick-step="4"] code').textContent`), 'mosaic project create work --repo work --business alpha');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-quick-step="4"] code')`), null);
|
||||
if (scenario !== 'success') {
|
||||
assert.match(await b.evaluate(`document.querySelector('[data-quick-step="4"]').textContent`), scenario === 'project-refused' ? /Project refused/ : /Outcome unknown/i);
|
||||
assert.equal(await b.evaluate('document.activeElement.dataset.quickStep'), '4');
|
||||
@@ -156,3 +189,106 @@ test('quick setup in remote mode sets origin and shows the check', { timeout: 45
|
||||
// The organization checkout stays local only.
|
||||
assert.equal(execFileSync('git', ['-C', join(dataRoot, 'org-runtime/alpha/checkout'), 'remote', '-v'], { env: { PATH: process.env.PATH, HOME: '/nonexistent', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' }, encoding: 'utf8' }).trim(), '');
|
||||
});
|
||||
|
||||
// first-run-fixes-1 follow-up (Lead on P3-1): with no preset available, one plain line above the
|
||||
// select points to Model setup and describes the disabled buttons. The select re-reads the presets
|
||||
// on focus and when the page shows again, so an account connected in another tab appears here.
|
||||
// A refresh keeps the owner's choice while it stays available, says so when it does not, keeps the
|
||||
// list on a failed read, and does not run once a Quick setup run has locked the select.
|
||||
test('no available preset points to Model setup, and a refocus or a shown page re-reads the list', { timeout: 60000 }, async t => {
|
||||
const on = { claude: false, codex: false }; let reads = 0, failNext = false, releaseReads = [], holdRead = false, note = 'Answers with Claude.';
|
||||
const entry = (name, label, description) => ({ name, label, description, thinking: { levels: ['low', 'high'], default: 'low' }, available: on[name] ? { ok: true } : { ok: false, reason: 'No model account is connected.' } });
|
||||
const orgPresets = async () => {
|
||||
reads++;
|
||||
if (holdRead) await new Promise(resolve => { releaseReads.push(resolve); });
|
||||
if (failNext) { failNext = false; throw Object.assign(new Error('read failed'), { code: 'org-invalid' }); }
|
||||
return [entry('claude', 'Claude', note), entry('codex', 'Codex', 'Answers with Codex.')];
|
||||
};
|
||||
const admin = createOrgAdmin({ service: { ...service, orgPresets }, registry: { listOrgs: async () => [] }, context: async () => ({ configDir: '/cfg', dataRoot: '/data', instance: 'test' }) });
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), orgAdmin: admin, send: async () => ({}), board: 'http://127.0.0.1:9', log: () => {} }); t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
const wait = expression => b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
|
||||
const settle = async before => { for (let i = 0; i < 100 && reads === before; i++) await new Promise(r => setTimeout(r, 30)); await new Promise(r => setTimeout(r, 300)); };
|
||||
const refocus = `(()=>{const s=document.querySelector('#org-preset');s.blur();s.focus()})()`;
|
||||
const shown = `(()=>{document.querySelector('#org-preset').blur();document.dispatchEvent(new Event('visibilitychange'))})()`;
|
||||
const look = () => b.evaluate(`(()=>{const q=s=>document.querySelector(s),none=q('#org-preset-none'),link=none.querySelector('a');
|
||||
return {none:!none.hidden&&none.getClientRects().length>0,text:q('#org-preset-none-text').textContent,link:link.textContent,href:link.getAttribute('href'),
|
||||
above:!!(none.compareDocumentPosition(q('#org-preset'))&Node.DOCUMENT_POSITION_FOLLOWING),help:q('#org-preset-help').textContent,value:q('#org-preset').value,
|
||||
buttons:['#org-quick-open','#org-advanced-open','#org-quick-run'].map(s=>[q(s).disabled,q(s).getAttribute('aria-describedby')])}})()`);
|
||||
const bannerText = () => b.evaluate(`(()=>{const x=document.querySelector('#org-banner');return x.hidden?'':x.textContent})()`);
|
||||
const blocked = { none: true, text: 'Connect a model account first. Agents need one to answer.', link: 'Open Model setup', href: '#/settings/model-setup', above: true, help: '', value: '',
|
||||
buttons: [[true, 'org-preset-none-text'], [true, 'org-preset-none-text'], [true, 'org-preset-none-text']] };
|
||||
const ready = (value, help) => ({ none: false, text: blocked.text, link: blocked.link, href: blocked.href, above: true, help, value, buttons: [[false, null], [false, null], [false, null]] });
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/settings/organizations`);
|
||||
await wait('document.querySelector("#org-new-form [data-write]") && !document.querySelector("#org-new-form [data-write]").disabled');
|
||||
await b.evaluate(`document.querySelector('#org-new-id').value='alpha';document.querySelector('#org-new-form [data-write]').click()`);
|
||||
await wait('document.querySelector("#org-paths") && !document.querySelector("#org-paths").hidden');
|
||||
assert.deepEqual(await look(), blocked);
|
||||
assert.equal(await b.evaluate(`[...document.querySelector('#org-preset').options].map(o=>o.textContent).join('|')`),
|
||||
'Claude|Codex');
|
||||
assert.equal(await b.evaluate(`document.querySelector('#org-paths').textContent.includes('mosaic ')`), false, 'no command for the owner');
|
||||
|
||||
assert.equal(await b.evaluate(`document.querySelector('#org-preset-unavailable').textContent`), 'Claude: No model account is connected. Codex: No model account is connected.');
|
||||
assert.doesNotMatch(await b.evaluate(`document.querySelector('.settings-helper').textContent`), /command/);
|
||||
|
||||
// Accounts are connected elsewhere; the select's next focus picks them up without a reload.
|
||||
on.claude = on.codex = true;
|
||||
await b.evaluate(refocus);
|
||||
await wait('document.querySelector("#org-preset").value === "claude"');
|
||||
assert.deepEqual(await look(), ready('claude', 'Answers with Claude.'));
|
||||
assert.equal(await bannerText(), '', 'a first choice is no switch');
|
||||
|
||||
// Focus and visibility events share the pending read, including a second new draft.
|
||||
holdRead = true;
|
||||
let pendingBefore = reads;
|
||||
await b.evaluate(refocus);
|
||||
for (let i = 0; i < 100 && reads === pendingBefore; i++) await new Promise(r => setTimeout(r, 20));
|
||||
assert.equal(reads, pendingBefore + 1);
|
||||
await b.evaluate(`${refocus};window.dispatchEvent(new Event('focus'));document.dispatchEvent(new Event('visibilitychange'));document.querySelector('#org-new-id').value='beta';document.querySelector('#org-new-form [data-write]').click()`);
|
||||
await new Promise(r => setTimeout(r, 200));
|
||||
const pendingReads = reads;
|
||||
holdRead = false; releaseReads.splice(0).forEach(resolve => resolve());
|
||||
await new Promise(r => setTimeout(r, 300));
|
||||
assert.equal(pendingReads, pendingBefore + 1, 'one pending presets request is reused');
|
||||
|
||||
// The owner picks Codex; a changed list that still offers it keeps it.
|
||||
await b.evaluate(`(()=>{const s=document.querySelector('#org-preset');s.value='codex';s.dispatchEvent(new Event('change'))})()`);
|
||||
note = 'Answers with Claude, now faster.';
|
||||
let before = reads;
|
||||
await b.evaluate(refocus); await settle(before);
|
||||
assert.ok(reads > before, 'the focus read again');
|
||||
assert.deepEqual(await look(), ready('codex', 'Answers with Codex.'));
|
||||
|
||||
// Codex goes away while the page is in another tab; the shown page switches and says so.
|
||||
on.codex = false;
|
||||
await b.evaluate(shown);
|
||||
await wait('document.querySelector("#org-preset").value === "claude"');
|
||||
assert.deepEqual(await look(), ready('claude', 'Answers with Claude, now faster.'));
|
||||
assert.equal(await bannerText(), 'Codex is no longer available. Claude is chosen.');
|
||||
|
||||
// A failed read keeps the list as it was.
|
||||
on.claude = false; failNext = true; before = reads;
|
||||
await b.evaluate(refocus); await settle(before);
|
||||
assert.ok(reads > before, 'the focus read again');
|
||||
assert.deepEqual(await look(), ready('claude', 'Answers with Claude, now faster.'));
|
||||
|
||||
// The next read finds nothing available: the line comes back and the banner names the lost choice.
|
||||
await b.evaluate(shown);
|
||||
await wait('!document.querySelector("#org-preset-none").hidden');
|
||||
assert.deepEqual(await look(), blocked);
|
||||
assert.equal(await bannerText(), 'Claude is no longer available.');
|
||||
|
||||
// A run locks the select; a shown page then does not read, and the buttons stay as the run left them.
|
||||
on.claude = true;
|
||||
await b.evaluate(`['#org-preset','#org-thinking','#org-quick-open','#org-advanced-open','#org-quick-run'].forEach(s=>document.querySelector(s).disabled=true)`);
|
||||
before = reads; await b.evaluate(shown); await new Promise(r => setTimeout(r, 400));
|
||||
assert.equal(reads, before, 'a locked select does not read');
|
||||
assert.deepEqual(await b.evaluate(`['#org-quick-open','#org-advanced-open','#org-quick-run'].map(s=>document.querySelector(s).disabled)`), [true, true, true]);
|
||||
|
||||
// A hidden page does not read.
|
||||
await b.evaluate(`document.querySelector('#org-preset').disabled=false`);
|
||||
before = reads;
|
||||
await b.evaluate(`(()=>{Object.defineProperty(document,'visibilityState',{configurable:true,get:()=>'hidden'});document.dispatchEvent(new Event('visibilitychange'))})()`);
|
||||
await new Promise(r => setTimeout(r, 400));
|
||||
assert.equal(reads, before, 'a hidden page does not read');
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
import * as service from '../../organization/src/org-service.mjs';
|
||||
const context = { window: {}, structuredClone };
|
||||
vm.runInNewContext(readFileSync(new URL('../src/public/org-create.js', import.meta.url), 'utf8'), context);
|
||||
const model = { key: 'claude-claude-opus-5-5', module: 'cliproxy', upstream: 'claude', provider: 'anthropic', model: 'claude-opus-5-5', available: true, reason: null, harnesses: ['claude-code', 'pi'] };
|
||||
test('Quick Setup routes assistant and chief for every installed preset without launching or granting anything', async () => {
|
||||
const presets = await service.orgPresets({ env: { PATH: '/usr/bin:/bin' } });
|
||||
assert.ok(presets.length >= 3);
|
||||
for (const preset of presets) {
|
||||
const advanced = await service.templateRender('alpha', { preset: preset.name, model });
|
||||
const before = structuredClone(advanced);
|
||||
const quick = JSON.parse(JSON.stringify(context.window.MosaicOrgCreate.quickDocument(advanced)));
|
||||
assert.deepEqual(quick.roles.chief.vars, quick.roles.assistant.vars, preset.name);
|
||||
assert.deepEqual(quick.launch, advanced.launch, 'routing does not launch the chief or change the launcher');
|
||||
assert.deepEqual(quick.roles.chief.definition, advanced.roles.chief.definition);
|
||||
const expected = structuredClone(advanced); expected.roles.chief.vars = structuredClone(expected.roles.assistant.vars);
|
||||
assert.deepEqual(quick, expected, 'only chief routing changes');
|
||||
assert.deepEqual(advanced, before, 'Advanced Setup keeps its original template');
|
||||
assert.equal(advanced.roles.chief.vars, undefined);
|
||||
}
|
||||
});
|
||||
|
||||
test('Quick Setup routing completes the existing checklist when its recorded program check has passed', async () => {
|
||||
const { setupState } = await import('../../organization/src/setup/setup-routing.mjs');
|
||||
const template = await service.templateRender('alpha', { preset: 'cliproxy', model });
|
||||
const doc = context.window.MosaicOrgCreate.quickDocument(template);
|
||||
const instances = Object.fromEntries(Object.entries(doc.roles).map(([name, role]) => [name, role.vars]));
|
||||
const member = { id: 'alpha', doc };
|
||||
const result = await setupState[0].check({ members: [member], read: async (_org, name) => name === 'routes'
|
||||
? { harnesses: template.plugins.harness, models: Object.keys(template.launch.models), instances }
|
||||
: { harnessWatch: [{ name: doc.roles.assistant.vars.harness, state: 'fit', checkedAt: '2026-11-22T10:00:00Z' }] } });
|
||||
assert.equal(result.state, 'done');
|
||||
assert.equal(result.reason, 'Your assistant and chief have models, and their programs passed the recorded check.');
|
||||
});
|
||||
|
||||
test('Quick Setup copies route values without copying assistant authority or other role settings', () => {
|
||||
const doc = { roles: {
|
||||
aide: { definition: 'assistant', vars: { harness: 'example', model: 'example-model', thinking: 'medium', 'limits.authority': ['message.send'] } },
|
||||
lead: { definition: 'chief-of-staff', vars: { 'limits.network': 'none' } },
|
||||
}, launch: { by: 'lead', instances: ['aide'] } };
|
||||
const quick = JSON.parse(JSON.stringify(context.window.MosaicOrgCreate.quickDocument(doc)));
|
||||
assert.deepEqual(quick.roles.lead.vars, { 'limits.network': 'none', harness: 'example', model: 'example-model', thinking: 'medium' });
|
||||
assert.deepEqual(quick.launch, doc.launch);
|
||||
});
|
||||
|
||||
|
||||
test('Quick Setup preserves chief route keys the assistant does not define', () => {
|
||||
const doc = { roles: {
|
||||
assistant: { definition: 'assistant', vars: { harness: 'example', model: undefined } },
|
||||
chief: { definition: 'chief-of-staff', vars: { harness: 'old', model: 'kept-model', thinking: 'high' } },
|
||||
} };
|
||||
const quick = context.window.MosaicOrgCreate.quickDocument(doc);
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(quick.roles.chief.vars)), { harness: 'example', model: 'kept-model', thinking: 'high' });
|
||||
assert.equal(doc.roles.chief.vars.harness, 'old');
|
||||
});
|
||||
@@ -14,7 +14,7 @@ test('organization header and footer never display null board values', async t =
|
||||
for (const [width, height] of [[1400, 900], [390, 844]]) {
|
||||
await b.viewport(width, height);
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/alpha/`);
|
||||
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(/Board:|No board/.test(document.querySelector('#board-url').textContent))return;await new Promise(r=>setTimeout(r,30))}throw Error('footer not loaded')})()`);
|
||||
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('#board-url').hidden)return;await new Promise(r=>setTimeout(r,30))}throw Error('footer not loaded')})()`);
|
||||
const text = await b.evaluate(`document.querySelector('header').textContent + ' ' + document.querySelector('footer').textContent`);
|
||||
assert.doesNotMatch(text, /\b(?:null|undefined)\b/i);
|
||||
}
|
||||
|
||||
@@ -119,11 +119,11 @@ test('PD apply hires the proposals, the pack card counts them, Hire the N propos
|
||||
|
||||
await b.evaluate(`document.querySelector('[data-pack-apply]').click();true`);
|
||||
await waitFor(b, `/^Applied\\./.test(document.querySelector('[data-packs-status]')?.textContent??'')`, 'apply status');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), 'Applied. Added board. Hired coder-1, reviewer-1. Not hired: scout-1, neither the chief of staff nor the assistant has a harness and model to give it; set them under Settings, Routing.');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), 'Applied. Added board. Hired coder-1, reviewer-1. Not hired: scout-1, neither the chief of staff nor the assistant has a harness and model to give it; set them under Settings, Models.');
|
||||
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-hired]')`, 'hired count');
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-pack-hired]').textContent`), '2 agents hired: coder-1, reviewer-1');
|
||||
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-pack-open-hire]')].map(l=>[l.dataset.packOpenHire,l.dataset.packOpenState,l.textContent])`),
|
||||
[['scout-1', 'refused', 'scout-1: Proposed by starter pack software-team for scout work. not hired: neither the chief of staff nor the assistant has a harness and model to give it; set them under Settings, Routing']]);
|
||||
[['scout-1', 'refused', 'scout-1: Proposed by starter pack software-team for scout work. not hired: neither the chief of staff nor the assistant has a harness and model to give it; set them under Settings, Models']]);
|
||||
assert.equal(await b.evaluate(`document.querySelector('[data-pack-hire-button]').textContent`), 'Hire the 1 proposed agent');
|
||||
await shot(b, 'pack-card-after-1440', '[data-pack="software-team"]');
|
||||
|
||||
|
||||
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user