Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8947256a29 | ||
|
|
ab186a83ba | ||
|
|
5c6082fde1 | ||
|
|
c68440e9da |
No files matched your search
@@ -2,7 +2,7 @@
|
||||
// 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 } from '../../plugins/model-provider/cliproxy/index.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);
|
||||
@@ -16,9 +16,20 @@ export async function readService({ configDir, dataRoot, instance, unitDir = nul
|
||||
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 read = !ctx.members.length && ctx.accounts ? [ctx.accounts] : ctx.members.map(org => async () => {
|
||||
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');
|
||||
@@ -48,6 +59,8 @@ export const setupState = Object.freeze([
|
||||
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');
|
||||
|
||||
@@ -3,6 +3,28 @@ 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');
|
||||
|
||||
@@ -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) ||
|
||||
@@ -87,7 +87,7 @@ async function discoverPresets() {
|
||||
// {proxy, riding, models}. A preset that does not use it ignores it.
|
||||
// `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();
|
||||
const presets = await discoverPresets({ env, owner, fixture });
|
||||
return Promise.all([...presets.values()].map(async p => {
|
||||
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');
|
||||
|
||||
@@ -8,25 +8,28 @@ export const setupState = Object.freeze([
|
||||
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]);
|
||||
if (chosen.some(c => !c?.harness || !c.model || !r.harnesses.includes(c.harness) || !r.models.includes(c.model)))
|
||||
return { state: 'next', reason: 'Choose a model for both your assistant and your chief.', fix };
|
||||
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 { state: 'failed', reason: 'A chosen program did not pass its check. Choose models to check the program.', fix };
|
||||
if (fits.some(h => h?.state === 'unknown')) return { state: 'failed', reason: 'The program check did not finish. Choose models to try again.', fix };
|
||||
if (fits.some(h => !['fit', 'changed'].includes(h?.state) || !h?.checkedAt)) return { state: 'checking', reason: 'The chosen programs have not passed their check yet. Choose models to check them.', fix };
|
||||
return { state: 'done', reason: 'Your assistant and chief have models, and their programs passed the recorded check.' };
|
||||
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." : '') };
|
||||
},
|
||||
},
|
||||
|
||||
@@ -9,16 +9,16 @@ 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('B2: the Test model preset reads unavailable only 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').available;
|
||||
assert.deepEqual(await fixtureOf({ ready: false }), { ok: false, reason: 'Developer test fixture is not running.' });
|
||||
assert.deepEqual(await fixtureOf({ ready: true }), { ok: true });
|
||||
assert.deepEqual(await fixtureOf(undefined), { ok: true }, 'no word from the Console keeps it offered');
|
||||
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');
|
||||
});
|
||||
|
||||
@@ -3,12 +3,32 @@ 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');
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -19,11 +19,12 @@ export const FIXTURE_TEMPLATE = Object.freeze({
|
||||
// Organization setup is supplied by this module, alongside its model route.
|
||||
// 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 reads unavailable when the Console says it is not ready. With no word from
|
||||
// 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() {
|
||||
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: ({ fixture } = {}) => (fixture?.ready === false ? { ok: false, reason: FIXTURE_NOT_READY } : { ok: true }),
|
||||
|
||||
@@ -17,7 +17,9 @@ export const setupState = Object.freeze([
|
||||
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) {
|
||||
const [service, account, docker] = await Promise.allSettled([modelSetupState[0].check(ctx), accountState(ctx), (ctx.docker ?? (() => dockerAnswers({ signal: ctx.signal })))()]);
|
||||
// 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();
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
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);
|
||||
|
||||
@@ -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);
|
||||
})();
|
||||
@@ -296,7 +296,7 @@
|
||||
function sections(route) {
|
||||
if (window.MosaicOrg) return orgSections(route);
|
||||
const focused = $('sections').contains(document.activeElement) ? document.activeElement.getAttribute('href') : null;
|
||||
const items = [['/', 'Dashboard', '', 'board'], ['/projects', 'Projects', '', 'inbox'], ['/inbox', 'Inbox', inboxCount?.open > 0 ? `<span class="count" aria-label="${inboxCount.open} open for you">${inboxCount.open}</span>${inboxCount.blocking ? ` ${blockChip(`${inboxCount.blocking} blocking`)}` : ''}` : '', 'inbox'], ['/messages', 'Assistant', messageCount > 0 ? `<span class="count" aria-label="${messageCount} unread messages">${messageCount}</span>` : '', 'talk'], ['/tasks', 'Tasks', '', 'tasks'], ['/agents', 'Agents', '', 'agents'], ['/queue', 'Queue', '', 'queue'], ['/docs', 'Docs', '', 'library'], ['/settings', 'Settings', '', 'settings']];
|
||||
const items = [[document.documentElement.hasAttribute('data-organizations') ? '/dashboard' : '/', 'Dashboard', '', 'board'], ['/projects', 'Projects', '', 'inbox'], ['/inbox', 'Inbox', inboxCount?.open > 0 ? `<span class="count" aria-label="${inboxCount.open} open for you">${inboxCount.open}</span>${inboxCount.blocking ? ` ${blockChip(`${inboxCount.blocking} blocking`)}` : ''}` : '', 'inbox'], ['/messages', 'Assistant', messageCount > 0 ? `<span class="count" aria-label="${messageCount} unread messages">${messageCount}</span>` : '', 'talk'], ['/tasks', 'Tasks', '', 'tasks'], ['/agents', 'Agents', '', 'agents'], ['/queue', 'Queue', '', 'queue'], ['/docs', 'Docs', '', 'library'], ['/settings', 'Settings', '', 'settings']];
|
||||
$('sections').innerHTML = items.map(([h, l, extra, icon]) => {
|
||||
const cur = h === '/' ? (route === '/' || route === '/board') : route.startsWith(h) || (h === '/projects' && route.startsWith('/chat')) || (h === '/tasks' && route.startsWith('/trail/task')) || (h === '/inbox' && (route.startsWith('/trail/decision') || route.startsWith('/trail/message')));
|
||||
return `<li><a href="#${h}" class="s1-section"${cur ? ' aria-current="page"' : ''}><svg class="i" aria-hidden="true">${h === '/projects' ? '<path d="M2 5h6l2 2h8v11H2z"/>' : `<use href="/icons.svg${spriteVersion ? `?retry=${spriteVersion}` : ''}#i-${icon}"/>`}</svg>${l}${extra ? ` ${extra}` : ''}</a>${h === '/projects' ? '<div id="project-tree" aria-label="Project conversations"></div>' : ''}</li>`;
|
||||
@@ -942,7 +942,7 @@
|
||||
<section aria-labelledby="b-claims"><h2 id="b-claims">Held roles <span class="count">${claims.length}</span></h2><p class="small muted">The current holder of each claimed role. A role nobody holds does not appear. Working: the holder has messages it received and hasn't answered yet. Waiting: a decision the role raised is open in your inbox. Otherwise idle.</p>
|
||||
${claims.length ? `<div class="table-wrap" tabindex="0" role="region" aria-label="Held roles, scroll for all columns"><table class="s1-table s1-agents"><thead><tr>${['Role', 'State', 'Attention', 'Holder', 'Harness', 'Held since'].map(h => `<th scope="col">${h}</th>`).join('')}</tr></thead><tbody>${rows}</tbody></table></div>` : empty('No role is held right now.', 'A role shows here while a run holds its claim on the bus.')}</section>
|
||||
${threadSection}
|
||||
<p class="small muted">Board seats stay on the <a href="${window.MosaicOrg ? '#/board' : '#/'}">control board</a>. This view is about roles.</p>`;
|
||||
<p class="small muted">Board seats stay on the <a href="${document.documentElement.hasAttribute('data-organizations') ? '#/board' : '#/'}">control board</a>. This view is about roles.</p>`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- queue, business, settings
|
||||
@@ -1582,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>`;
|
||||
@@ -1590,12 +1590,13 @@
|
||||
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.'); }
|
||||
// F3: Settings > Console (console-restart.js). The server checks the owner, Origin and trail.
|
||||
if (page==='console') { await configRead; await window.MosaicConsole?.ready; return settingsShell(page,window.MosaicConsole?.settingsMarkup()??'<section class="panel"><p class="small warn">The Console controls did not load. Reload the page to try again.</p></section>','Restart this Console on the same address and configuration.'); }
|
||||
if (page === 'about' && document.documentElement.hasAttribute('data-organizations') && !window.MosaicOrg) return settingsShell(page, '<section class="panel"><p>No organization yet. Organization details appear here after you create one.</p></section>');
|
||||
const s = await get.api('settings'), n = s.notifier || {};
|
||||
let usage, names = null, instances = null, routes = null, limitRows = [], limitsRefused = false;
|
||||
if (page==='tokens') { try { [usage] = await get('usage'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } try { limitRows = await get('limits'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; limitsRefused = true; } }
|
||||
@@ -1691,6 +1692,7 @@
|
||||
const lf = v => String(v).replace(/\r\n?/g, '\n');
|
||||
const DOC_PATH = /^(spec\/north-star\.md|docs\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.md)$/;
|
||||
async function docsView(get) {
|
||||
if (document.documentElement.hasAttribute('data-organizations') && !window.MosaicOrg) return `${head('Docs')}${empty('No organization yet.', 'Create an organization to see its project documents.')}`;
|
||||
const projects = (await get.api('business')).business?.projects, names = Array.isArray(projects) ? projects.filter(p => typeof p === 'string' && SAFE.test(p)) : [];
|
||||
const blocks = [];
|
||||
for (const p of names) {
|
||||
@@ -1796,7 +1798,10 @@
|
||||
});
|
||||
|
||||
// Not found and states
|
||||
function notFound(why) { return `${head('Not found')}<div class="empty nf"><b>${why || 'No page at this address.'}</b><p>Nothing is at <code>${txt(location.hash || '#/')}</code>. <a href="${window.MosaicOrg ? '#/dashboard' : '#/'}">Go to the ${window.MosaicOrg ? 'Dashboard' : 'Board'}</a> or press <kbd>Ctrl K</kbd> to search.</p></div>`; }
|
||||
function notFound(why) {
|
||||
const orgMode = document.documentElement.hasAttribute('data-organizations');
|
||||
return `${head('Not found')}<div class="empty nf"><b>${why || 'No page at this address.'}</b><p>Nothing is at <code>${txt(location.hash || '#/')}</code>. <a href="${orgMode ? '#/dashboard' : '#/'}">Go to the ${orgMode ? 'Dashboard' : 'Board'}</a> or press <kbd>Ctrl K</kbd> to search.</p></div>`;
|
||||
}
|
||||
const loadingView = (source = null) => `${head('Reading…')}<div class="skel-rows" aria-busy="true"><span class="sr-only">${source ? `Reading the ${esc(source.toLowerCase())}.` : 'Reading from the bus.'}</span><span class="skel"></span><span class="skel"></span><span class="skel"></span><span class="skel"></span></div>`;
|
||||
const retry = '<div class="actions"><button type="button" class="btn" data-retry>Read again</button></div>';
|
||||
// Why a read failed, in words, with the bus code as given. Never a path or a guess.
|
||||
@@ -2109,7 +2114,7 @@
|
||||
let html, state = 'fresh';
|
||||
const live = reader(true);
|
||||
try {
|
||||
if (path !== '/organization' && !wsPage(path) && !(path === '/agents' && window.MosaicOrg) && path !== '/messages' && !['/settings','/settings/appearance','/settings/model-setup','/settings/triage','/settings/organizations'].includes(path)) {
|
||||
if (!(document.documentElement.hasAttribute('data-organizations') && !window.MosaicOrg) && path !== '/organization' && !wsPage(path) && !(path === '/agents' && window.MosaicOrg) && path !== '/messages' && !['/settings','/settings/appearance','/settings/model-setup','/settings/triage','/settings/organizations'].includes(path)) {
|
||||
try { await live('messages'); }
|
||||
catch (err) { messageCount = null; if (err.status === 403 || err.code === 'signed-out') throw err; }
|
||||
}
|
||||
@@ -2203,13 +2208,14 @@
|
||||
// Ctrl+K opens it. It lists the views, and the decisions and tasks from the last inbox and
|
||||
// tasks reads (opening it reads both again, GET only). Enter goes; Esc closes and puts focus
|
||||
// back where it was. It only navigates.
|
||||
const VIEWS = [['#/', 'Dashboard'], ['#/projects', 'Projects'], ['#/inbox', 'Inbox'], ...(window.MosaicAssistant ? [['#/assistant', 'Assistant'], ['#/messages', 'Messages']] : [['#/messages', 'Assistant']]), ['#/tasks', 'Tasks'], ['#/agents', 'Agents'], ['#/queue', 'Queue'], ['#/settings/business', 'Business'], ['#/docs', 'Docs'], ['#/settings', 'Settings'], ['#/settings/display', 'Sidebar display']];
|
||||
const VIEWS = [[document.documentElement.hasAttribute('data-organizations') ? '#/dashboard' : '#/', 'Dashboard'], ['#/projects', 'Projects'], ['#/inbox', 'Inbox'], ...(window.MosaicAssistant ? [['#/assistant', 'Assistant'], ['#/messages', 'Messages']] : [['#/messages', 'Assistant']]), ['#/tasks', 'Tasks'], ['#/agents', 'Agents'], ['#/queue', 'Queue'], ['#/settings/business', 'Business'], ['#/docs', 'Docs'], ['#/settings', 'Settings'], ['#/settings/display', 'Sidebar display']];
|
||||
let pkAll = [], pkShown = [], pkAt = 0, pkBack = null;
|
||||
function pkItems() {
|
||||
const views = VIEWS.filter(([href]) => href !== '#/settings/business' || !document.documentElement.hasAttribute('data-organizations') || window.MosaicOrg);
|
||||
const decisions = (last.get('inbox')?.rows || []).map(d => ({ href: `#/inbox/${enc(d.id)}`, label: first(d.question), group: `decision ${short(d.id)}` }));
|
||||
const tasks = (last.get('tasks')?.rows || []).filter(r => TASK.test(String(r.task_ref))).map(r => { const t = task(r); return { href: `#/tasks/${enc(t.ref)}`, label: `#${t.id} ${t.title ?? '(no title in the current read)'}`, group: 'task' }; });
|
||||
const rows = (last.get('api:queue')?.rows || []).filter(r => Number.isInteger(r.id)).map(r => ({ href: `#/queue/${r.id}`, label: `${r.id} ${r.piece ?? ''}`, group: `queue row, ${r.state}` }));
|
||||
pkAll = [...VIEWS.map(([href, label]) => ({ href, label, group: 'view' })), ...(window.MosaicProjects?.palette?.() || []), ...decisions, ...tasks, ...rows];
|
||||
pkAll = [...views.map(([href, label]) => ({ href, label, group: 'view' })), ...(window.MosaicProjects?.palette?.() || []), ...decisions, ...tasks, ...rows];
|
||||
}
|
||||
function pkFill() {
|
||||
const q = $('cmdk-input').value.trim().toLowerCase();
|
||||
@@ -2225,6 +2231,7 @@
|
||||
if (d.open) return;
|
||||
pkBack = document.activeElement; pkAt = 0; $('cmdk-input').value = '';
|
||||
pkItems(); pkFill(); d.showModal(); $('cmdk-input').focus();
|
||||
if (document.documentElement.hasAttribute('data-organizations') && !window.MosaicOrg) return;
|
||||
const epoch = orgEpoch;
|
||||
Promise.allSettled(['inbox', 'tasks'].map(async v => { const r = await fetchRead(v); if (epoch === orgEpoch) last.set(v, r); })).then(rs => {
|
||||
if (epoch !== orgEpoch) return;
|
||||
|
||||
@@ -378,7 +378,16 @@ const modelSetupFetch = (input, init) => window.fetch(new URL(input, location.hr
|
||||
const orgParam = hash => { const q = hash.split('?')[1]; const v = q ? new URLSearchParams(q).get('org') : null; return v ? encodeURIComponent(v) : null; };
|
||||
const orgOf = hash => /^#\/orgs\/([^/?]+)/.exec(hash)?.[1] ?? (/^#\/settings\//.test(hash) ? orgParam(hash) : null);
|
||||
const atLoad = orgOf(location.hash);
|
||||
// The single-business Console keeps its original board home.
|
||||
if (!document.documentElement.hasAttribute('data-organizations')) document.querySelector('.wordmark')?.setAttribute('href', '#/');
|
||||
if (!atLoad && !document.documentElement.hasAttribute('data-organizations')) return;
|
||||
// Home always names the single-pane Dashboard, even before any organization exists.
|
||||
// Replace the alias entry so Back returns to the page the person came from.
|
||||
const normalizeHome = () => {
|
||||
const home = location.hash.split('?')[0];
|
||||
if (document.documentElement.hasAttribute('data-organizations') && ['', '#', '#/'].includes(home)) history.replaceState(history.state, '', `#/dashboard${location.hash.slice(home.length)}`);
|
||||
};
|
||||
normalizeHome();
|
||||
// current: the scoping organization as its hash segment. settled: false only while the first
|
||||
// list read picks one for an address that names none. With no valid organization at all the
|
||||
// page stays in its first-run mode (window.MosaicOrg reads undefined), as before.
|
||||
@@ -531,9 +540,9 @@ const modelSetupFetch = (input, init) => window.fetch(new URL(input, location.hr
|
||||
// Capture phase: this runs before bus.js renders, so a switch is scoped before the page reads.
|
||||
window.addEventListener('hashchange', event => {
|
||||
const oldHash = event.oldURL ? new URL(event.oldURL).hash : previous;
|
||||
normalizeHome();
|
||||
const raw = location.hash;
|
||||
// First run (no organization yet) keeps its own addresses: #/ is its board, not #/dashboard.
|
||||
// Before the first list read settles, the settle step normalizes whatever address it finds.
|
||||
// Organization-scoped addresses wait for a selection; home needs no organization.
|
||||
if (!settled || !current) { previous = raw; return; }
|
||||
const seg = orgOf(raw) ?? current, next = normalize(raw, seg);
|
||||
if (next !== raw) history.replaceState(null, '', next);
|
||||
@@ -1594,7 +1603,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')]));
|
||||
@@ -1603,30 +1612,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'] } : {});
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
<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>
|
||||
<a class="skip" href="#main">Skip to content</a>
|
||||
<header class="cmdbar"><button type="button" id="nav-open" class="btn" aria-controls="console-nav" aria-expanded="false" aria-label="Open menu" title="Menu"><svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 6h16M4 12h16M4 18h16"/></svg></button><a href="#/" class="wordmark" aria-label="Mosaic Stack Dashboard"><svg class="mosaic-logo" viewBox="0 0 36 36" aria-hidden="true"><rect x="3" y="12" width="13" height="10" rx="2"/><rect x="18" y="3" width="13" height="12" rx="2"/><rect x="3" y="24" width="13" height="10" rx="2"/><rect x="18" y="17" width="13" height="12" rx="2"/></svg><span>Mosaic Stack</span></a>
|
||||
<header class="cmdbar"><button type="button" id="nav-open" class="btn" aria-controls="console-nav" aria-expanded="false" aria-label="Open menu" title="Menu"><svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 6h16M4 12h16M4 18h16"/></svg></button><a href="#/dashboard" class="wordmark" aria-label="Mosaic Stack Dashboard"><svg class="mosaic-logo" viewBox="0 0 36 36" aria-hidden="true"><rect x="3" y="12" width="13" height="10" rx="2"/><rect x="18" y="3" width="13" height="12" rx="2"/><rect x="3" y="24" width="13" height="10" rx="2"/><rect x="18" y="17" width="13" height="12" rx="2"/></svg><span>Mosaic Stack</span></a>
|
||||
<button type="button" class="cmdk" id="cmdk" aria-haspopup="dialog" aria-controls="cmdk-dialog" aria-label="Search" title="Search"><svg class="i" aria-hidden="true"><use href="/icons.svg#i-search"/></svg><span>Go to a view, decision or task</span><kbd>Ctrl K</kbd></button>
|
||||
<nav id="federation" class="federation small" aria-label="Consoles" hidden></nav><p class="fresh" id="fresh"><span id="fresh-board"></span><span id="fresh-bus"></span></p>
|
||||
<div class="cmd-right"><a href="#/" id="processing-link" class="processing-link"><span aria-hidden="true">●</span> <span id="processing-short">Processing unavailable</span></a><button class="header-action" id="refresh" type="button" aria-label="Refresh" title="Refresh"><svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 7v5h-5M4 17v-5h5M5 9a7 7 0 0 1 12-3l3 3M19 15a7 7 0 0 1-12 3l-3-3"/></svg><span>Refresh</span></button><button class="header-action" id="pause" type="button" aria-label="Pause" title="Pause" aria-pressed="false"><svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M9 5v14M15 5v14"/></svg><span>Pause</span></button><button id="theme-switch" class="theme-switch" type="button" role="switch" aria-checked="false" aria-label="Dark mode" title="Dark mode"><span class="theme-track" aria-hidden="true"><svg class="theme-sun" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4"/><path d="M12 2v2m0 16v2M2 12h2m16 0h2M5 5l1.5 1.5m11 11L19 19M19 5l-1.5 1.5m-11 11L5 19"/></svg><svg class="theme-moon" viewBox="0 0 24 24"><path d="M20 15a8 8 0 0 1-11-11 8 8 0 1 0 11 11Z"/></svg><span class="theme-thumb"></span></span></button><div class="avatar-wrap"><button type="button" id="avatar-button" aria-haspopup="menu" aria-expanded="false" aria-controls="avatar-menu"><span class="avatar-initial">L</span><span id="avatar-name">Local operator</span><span aria-hidden="true">⌄</span></button><div id="avatar-menu" class="avatar-menu" role="menu" hidden><a href="#/settings" role="menuitem">Settings</a><a href="#/" id="mobile-processing-link" class="mobile-menu-item" role="menuitem">Processing unavailable</a><button id="mobile-refresh" class="mobile-menu-item" type="button" role="menuitem">Refresh</button><button id="mobile-pause" class="mobile-menu-item" type="button" role="menuitem">Pause</button><form id="sign-out" method="post" action="/auth/logout" hidden><button type="submit" role="menuitem">Sign out</button></form><div id="local-sign-out" role="menuitem" aria-disabled="true">Sign out <small>Not signed in (local dev)</small></div></div></div></div></header>
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
// 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'}.`;
|
||||
@@ -48,7 +49,7 @@
|
||||
<section id="org-paths" class="panel" hidden aria-labelledby="org-paths-title">
|
||||
<h3 id="org-paths-title">Choose how to set up</h3>
|
||||
<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"></select><span class="org-help" id="org-preset-help"></span></div>
|
||||
<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>
|
||||
@@ -64,7 +65,7 @@
|
||||
<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>
|
||||
@@ -82,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">
|
||||
@@ -274,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);
|
||||
@@ -303,7 +304,8 @@
|
||||
// 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)}${p.available.ok ? '' : ` — ${txt(p.available.reason)}`}</option>`).join('');
|
||||
$('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();
|
||||
}
|
||||
@@ -388,7 +390,7 @@
|
||||
{ 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('');
|
||||
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 {
|
||||
@@ -413,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.
|
||||
@@ -474,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() {
|
||||
@@ -524,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>` : ''}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
visiting.delete(r.id); seen.add(r.id); ordered.push(r);
|
||||
}
|
||||
rows.forEach(visit);
|
||||
const required = ordered.filter(r => r.required), optional = ordered.filter(r => !r.required);
|
||||
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 }));
|
||||
@@ -38,7 +38,7 @@
|
||||
}
|
||||
const complete = required.length > 0 && required.every(satisfied);
|
||||
const failures = alerts;
|
||||
return { rows: [...required, ...optional], required, optional, current, total: required.length, done: required.filter(satisfied).length, step: current?.number ?? required.length, complete,
|
||||
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) {
|
||||
@@ -48,9 +48,9 @@
|
||||
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 = target(r.fix), optional = !r.required;
|
||||
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 ? '!' : r.state === 'done' ? '✓' : r.number ?? '+'}</span>
|
||||
<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>` : ''}
|
||||
@@ -59,7 +59,7 @@
|
||||
}
|
||||
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.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>`;
|
||||
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) : ''}`;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
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: 60000 }, 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}/#/`);
|
||||
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/);
|
||||
const dashboard = async (hash = '#/dashboard') => {
|
||||
await wait(`location.hash === ${JSON.stringify(hash)} && document.querySelector(".setup-card")`);
|
||||
assert.doesNotMatch(await b.evaluate('document.body.innerText'), /Business overview|Held roles/);
|
||||
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]")?.getAttribute("href")'), '#/dashboard');
|
||||
assert.equal(await b.evaluate('document.querySelector("a.wordmark").getAttribute("href")'), '#/dashboard');
|
||||
assert.deepEqual(errors, []);
|
||||
};
|
||||
const settings = async (page = 'model-setup') => {
|
||||
await b.evaluate(`location.hash=${JSON.stringify(`#/settings/${page}`)}`);
|
||||
await wait(`document.querySelector(".settings-${page}")`);
|
||||
};
|
||||
const dashboardLink = '([...document.querySelectorAll("a.s1-section")].find(a => a.textContent.trim() === "Dashboard"))';
|
||||
await settings();
|
||||
assert.equal(await b.evaluate(`${dashboardLink}.getAttribute("href")`), '#/dashboard');
|
||||
await b.evaluate(`${dashboardLink}.click()`);
|
||||
await dashboard();
|
||||
await settings();
|
||||
await b.evaluate('document.querySelector("a.wordmark").click()');
|
||||
await dashboard();
|
||||
for (const alias of ['#/', '#', '', '#/?from=mail']) {
|
||||
await settings();
|
||||
const length = await b.evaluate('history.length');
|
||||
await b.evaluate(`location.hash=${JSON.stringify(alias)}`);
|
||||
await dashboard(alias.includes('?') ? '#/dashboard?from=mail' : '#/dashboard');
|
||||
assert.equal(await b.evaluate('history.length'), length + 1, 'normalization replaces the alias entry');
|
||||
await b.evaluate('history.back()');
|
||||
await wait('location.hash === "#/settings/model-setup" && document.querySelector(".settings-model-setup")');
|
||||
await b.evaluate('history.forward()');
|
||||
await dashboard(alias.includes('?') ? '#/dashboard?from=mail' : '#/dashboard');
|
||||
}
|
||||
// Every instance Settings destination available before an organization exists returns home safely.
|
||||
for (const page of ['appearance', 'organizations', 'console', 'about']) {
|
||||
await settings(page);
|
||||
await b.evaluate(`${dashboardLink}.click()`);
|
||||
await dashboard();
|
||||
}
|
||||
await b.evaluate('location.hash="#/docs"');
|
||||
await wait('location.hash === "#/docs" && document.querySelector("#bus-view h1")?.textContent === "Docs"');
|
||||
await b.evaluate('document.querySelector("a.wordmark").click()');
|
||||
await dashboard();
|
||||
await settings();
|
||||
await b.evaluate('document.querySelector("#cmdk").click()');
|
||||
await wait('document.querySelector("#cmdk-dialog").open');
|
||||
assert.equal(await b.evaluate('document.querySelector("#cmdk-list [data-href]").dataset.href'), '#/dashboard');
|
||||
assert.equal(await b.evaluate('[...document.querySelectorAll("#cmdk-list [data-href]")].some(e => e.dataset.href === "#/settings/business")'), false);
|
||||
await b.key('Enter');
|
||||
await dashboard();
|
||||
await b.evaluate('location.hash="#/nowhere"');
|
||||
await wait('document.querySelector("#bus-view .nf")');
|
||||
assert.equal(await b.evaluate('document.querySelector(".nf a").getAttribute("href")'), '#/dashboard');
|
||||
assert.equal(await b.evaluate('document.querySelector(".nf a").textContent'), 'Go to the Dashboard');
|
||||
await b.evaluate('document.querySelector(".nf a").click()');
|
||||
await dashboard();
|
||||
// Fresh document loads cover all root spellings, including the empty hash.
|
||||
for (const alias of ['', '#', '#/']) {
|
||||
await b.navigate('about:blank');
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/${alias}`);
|
||||
await dashboard();
|
||||
}
|
||||
// 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, []);
|
||||
});
|
||||
|
||||
test('without organization mode root remains the legacy board and wordmark returns to it', async t => {
|
||||
const server = await startServer({ port: 0, board: 'http://127.0.0.1:9', log: () => {} });
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/`);
|
||||
assert.equal(await b.evaluate('document.documentElement.hasAttribute("data-organizations")'), false);
|
||||
assert.equal(await b.evaluate('location.hash'), '#/');
|
||||
assert.match(await b.evaluate('document.body.innerText'), /Business overview|Held roles/);
|
||||
assert.equal(await b.evaluate('document.querySelector("a.wordmark").getAttribute("href")'), '#/');
|
||||
await b.evaluate('location.hash="#/settings/appearance"');
|
||||
await b.evaluate('(async()=>{for(let i=0;i<150;i++){if(document.querySelector(".settings-appearance"))return;await new Promise(r=>setTimeout(r,30))}throw Error("Settings")})()');
|
||||
await b.evaluate('document.querySelector("a.wordmark").click()');
|
||||
await b.evaluate('(async()=>{for(let i=0;i<150;i++){if(location.hash==="#/" && !document.body.classList.contains("on-bus"))return;await new Promise(r=>setTimeout(r,30))}throw Error("Board")})()');
|
||||
assert.match(await b.evaluate('document.body.innerText'), /Business overview|Held roles/);
|
||||
assert.equal(await b.evaluate('document.querySelector(".setup-card")'), null);
|
||||
});
|
||||
@@ -586,7 +586,7 @@ test('preset routes expose installed choices and refuse invalid queries', async
|
||||
|
||||
// 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 reads unavailable until the instance\'s dev fixture runs', async t => {
|
||||
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');
|
||||
@@ -596,8 +596,8 @@ test('B2: the Test model preset reads unavailable until the instance\'s dev fixt
|
||||
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 = { ok: false, reason: 'Developer test fixture is not running.' };
|
||||
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; };
|
||||
@@ -623,7 +623,7 @@ test('B2: the Test model preset reads unavailable until the instance\'s dev fixt
|
||||
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.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');
|
||||
});
|
||||
@@ -633,11 +633,11 @@ test('B2: the Test model preset reads unavailable until the instance\'s dev fixt
|
||||
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 of [async () => ({ ready: false }), async () => ({ ready: true }), async () => { throw new Error('read failed'); }]) {
|
||||
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.ok(r.body.presets.some(p => p.name === 'fixture'), 'the Test model entry is listed');
|
||||
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);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -21,6 +21,11 @@ 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
|
||||
@@ -87,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');
|
||||
@@ -193,12 +198,11 @@ test('quick setup in remote mode sets origin and shows the check', { timeout: 45
|
||||
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 fixture = { name: 'fixture', label: 'Test model', description: 'A fixed test reply.', thinking: { levels: ['none'], default: 'none' }, available: { ok: false, reason: 'Developer test fixture is not running.' } };
|
||||
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.'), fixture];
|
||||
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));
|
||||
@@ -221,9 +225,12 @@ test('no available preset points to Model setup, and a refocus or a shown page r
|
||||
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 — No model account is connected.|Codex — No model account is connected.|Test model — Developer test fixture is not running.');
|
||||
'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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -27,20 +27,26 @@ test('an invalid organization is explained instead of appearing as an empty regi
|
||||
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}/#/`);
|
||||
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('#held [role=alert]'))return;await new Promise(r=>setTimeout(r,30))}throw Error('admission error missing')})()`);
|
||||
const body = await b.evaluate('document.body.textContent');
|
||||
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('#org-list-banner[role=alert]'))return;await new Promise(r=>setTimeout(r,30))}throw Error('admission error missing')})()`);
|
||||
assert.equal(await b.evaluate('location.hash'), '#/dashboard');
|
||||
assert.equal(await b.evaluate('document.querySelector("#org-list-banner").getClientRects().length > 0'), true);
|
||||
const body = await b.evaluate('document.body.innerText');
|
||||
assert.match(body, /alpha.*invalid.*document and registry disagree/is);
|
||||
assert.doesNotMatch(body, /No organizations yet/);
|
||||
await b.evaluate('location.hash="#/board"');
|
||||
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('#held [role=alert]'))return;await new Promise(r=>setTimeout(r,30))}throw Error('board admission error missing')})()`);
|
||||
assert.match(await b.evaluate('document.querySelector("#held [role=alert]").textContent'), /alpha.*invalid.*document and registry disagree/is);
|
||||
}
|
||||
});
|
||||
|
||||
test('fresh dashboard points to organization setup while real list errors remain errors', async t => {
|
||||
// The retained control board keeps its own setup/error recovery at its existing route.
|
||||
test('the control board points to organization setup while real list errors remain errors', async t => {
|
||||
for (let broken of [false, true]) {
|
||||
const organizations = { list: async () => { if (broken) throw Error('registry down'); return []; }, resolve: async () => null };
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations, board: 'http://127.0.0.1:9', log: () => {} });
|
||||
const b = await browser({ machine: false });
|
||||
try {
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/`);
|
||||
await b.navigate(`http://127.0.0.1:${server.address().port}/#/board`);
|
||||
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('#held .banner, #held a[href="#/settings/organizations"]'))return;await new Promise(r=>setTimeout(r,30))}throw Error('held roles did not settle')})()`);
|
||||
const held = await b.evaluate(`({ text: document.querySelector('#held').textContent, error: !!document.querySelector('#held .banner.err, #held .banner.ref'), link: !!document.querySelector('#held a[href="#/settings/organizations"]') })`);
|
||||
if (broken) {
|
||||
|
||||
@@ -5,13 +5,13 @@ import { runInNewContext } from 'node:vm';
|
||||
const source = new URL('../src/public/processing.js', import.meta.url);
|
||||
const GEN = '12345678-1234-4234-8234-123456789abc';
|
||||
const flush = async () => { for (let i = 0; i < 8; i++) await new Promise(resolve => setImmediate(resolve)); };
|
||||
async function fixture({ send = true, halted = false, unknown = false, partial = false, confirm = true } = {}) {
|
||||
async function fixture({ send = true, halted = false, unknown = false, partial = false, confirm = true, organizations = false } = {}) {
|
||||
const nodes = new Map(), requests = [], events = new Map(), classes = new Set(); let confirmations = 0;
|
||||
for (const id of ['processing-controls', 'processing-state', 'processing-halt', 'processing-resume', 'processing-unavailable', 'processing-receipt', 'processing-banner'])
|
||||
nodes.set(id, { id, hidden: false, disabled: false, textContent: '', dataset: {}, listeners: new Map(), addEventListener(name, fn) { this.listeners.set(name, fn); } });
|
||||
const state = { version: 1, generation: GEN, halted, quiescent: !partial, remaining: partial ? 1 : 0, stopped: 0 };
|
||||
runInNewContext(readFileSync(source, 'utf8'), {
|
||||
document: { getElementById: id => nodes.get(id), body: { classList: { contains: name => classes.has(name) } },
|
||||
document: { documentElement: { hasAttribute: name => organizations && name === 'data-organizations' }, getElementById: id => nodes.get(id), body: { classList: { contains: name => classes.has(name) } },
|
||||
addEventListener: (name, fn) => events.set(name, fn),
|
||||
dispatchEvent: event => { if (event.type === 'mosaic-signed-out') classes.add('signed-out'); events.get(event.type)?.(event); } },
|
||||
Event, CustomEvent,
|
||||
@@ -33,6 +33,13 @@ async function fixture({ send = true, halted = false, unknown = false, partial =
|
||||
const click = async id => { await nodes.get(id).listeners.get('click')(); await flush(); };
|
||||
return { nodes, requests, events, state, click, confirmations: () => confirmations };
|
||||
}
|
||||
test('an organization Console without a selected organization never reads processing controls', async () => {
|
||||
const f = await fixture({ organizations: true });
|
||||
await f.events.get('hashchange')(); await flush();
|
||||
assert.deepEqual(f.requests, []);
|
||||
assert.equal(f.nodes.get('processing-controls').hidden, true);
|
||||
assert.equal(f.nodes.get('processing-banner').hidden, true);
|
||||
});
|
||||
test('interim read-only controls show CLI recovery, disable both writes and retain a halted banner across views', async () => {
|
||||
const f = await fixture({ send: false, halted: true });
|
||||
assert.equal(f.nodes.get('processing-halt').disabled, true); assert.equal(f.nodes.get('processing-resume').disabled, true);
|
||||
|
||||
@@ -25,10 +25,16 @@ test('the first unfinished required row is next and failures and checking keep t
|
||||
});
|
||||
test('optional checks never change the count and not applicable is satisfied', () => {
|
||||
const s = derive([row('a', [], 'not-applicable'), row('b', ['a'], 'done'), row('worker', [], 'failed', false)]);
|
||||
assert.equal(s.complete, true); assert.equal(s.total, 2); assert.equal(s.done, 2); assert.equal(s.current, null);
|
||||
assert.equal(s.complete, true); assert.equal(s.total, 1); assert.equal(s.done, 1); assert.equal(s.current, null);
|
||||
assert.match(render(s), /Setup done/); assert.match(render(s), /Show checks/);
|
||||
assert.ok(!render(s).includes('setup-card'));
|
||||
});
|
||||
test('not needed rows stay visible without holding back or numbering later steps', () => {
|
||||
const s = derive([row('service', [], 'not-applicable'), row('account', ['service'], 'not-applicable'), row('org', ['account'], 'done'), row('chat', ['org'])]);
|
||||
assert.equal(s.total, 2); assert.equal(s.step, 2); assert.equal(s.current.id, 'chat');
|
||||
assert.equal(s.rows[0].state, 'not-applicable'); assert.equal(s.rows[1].state, 'not-applicable');
|
||||
assert.match(render(s), /Step 2 of 2/); assert.match(render(s), /Not needed/);
|
||||
});
|
||||
test('the checklist opens exactly one row, has one primary action and preserves completed evidence', () => {
|
||||
const s = derive([row('a'), row('b', ['a']), row('c', ['b'], 'done')]);
|
||||
const html = render(s);
|
||||
|
||||
@@ -5,6 +5,16 @@ import { startServer } from '../src/serve.mjs';
|
||||
import { createDevOwner } from '../src/dev-owner.mjs';
|
||||
|
||||
const row = (id, check) => ({ id, title: 'Check this part', purpose: 'See whether it works.', required: true, order: { after: [] }, fix: null, check });
|
||||
test('a failed members read leaves both model rows unavailable', async () => {
|
||||
const body = await readSetup({ organizations: { members: async () => { throw Error('private fault'); } }, service: async () => ({ release: {}, init: {}, unit: {} }) });
|
||||
for (const id of ['model-service.running', 'model-account.connected']) assert.equal(body.rows.find(r => r.id === id).code, 'setup-check-unavailable');
|
||||
});
|
||||
test('non-proxy organizations skip both model rows without making account or service reads', async () => {
|
||||
const body = await readSetup({ organizations: { members: async () => [{ id: 'local', doc: { plugins: {} } }] },
|
||||
sources: [async () => (await import('../../model-proxy/src/setup-state.mjs')).setupState],
|
||||
service: () => { throw Error('unneeded service'); }, accounts: () => { throw Error('unneeded accounts'); } });
|
||||
for (const id of ['model-service.running', 'model-account.connected']) assert.equal(body.rows.find(r => r.id === id).state, 'not-applicable');
|
||||
});
|
||||
test('setup collects part rows, isolates throws and never reflects exception text', async () => {
|
||||
const sources = [async () => [row('a', () => ({ state: 'done', reason: 'Ready.' })), row('b', () => { throw Error('secret path'); })]];
|
||||
const result = await readSetup({ sources, organizations: { members: async () => [] }, session: {} });
|
||||
@@ -152,12 +162,15 @@ test('an existing organization uses its own proxy truth even when the root owner
|
||||
let orgEntries = [];
|
||||
const org = { id: 'separate', options: async () => ({ bus: { routes: async () => ({ catalogue: { status: 'ready', models: [{ upstream: 'claude', available: true }] } }) }, proxyCall: async () => ({ accounts: orgEntries }) }) };
|
||||
const read = await accountServer(t, { proxyAdmin, organizations: { list: async () => [], members: async () => [org] } });
|
||||
assert.equal(accountRow((await read()).body).state, 'next'); assert.equal(instanceReads, 0);
|
||||
const first = (await read()).body;
|
||||
assert.equal(accountRow(first).state, 'next');
|
||||
assert.match(first.rows.find(r => r.id === 'worker.ready').reason, /Account: connected/);
|
||||
assert.equal(instanceReads, 1, 'only the worker row uses the instance account');
|
||||
// The contribution must also prefer organization truth when both readers are present.
|
||||
const body = await readSetup({ organizations: { members: async () => [org] }, accounts: proxyAdmin.setupAccounts, service: runningService, docker: async () => false, runs: () => [] });
|
||||
assert.equal(accountRow(body).state, 'next'); assert.equal(instanceReads, 0);
|
||||
assert.equal(accountRow(body).state, 'next'); assert.equal(instanceReads, 2);
|
||||
orgEntries = [{ provider: 'claude', status: 'active' }];
|
||||
assert.equal(accountRow((await read()).body).state, 'done'); assert.equal(instanceReads, 0);
|
||||
assert.equal(accountRow((await read()).body).state, 'done'); assert.equal(instanceReads, 3);
|
||||
});
|
||||
test('slow, busy, paused and refused owner reads stay inside the setup deadline and disclose no exception text', async t => {
|
||||
for (const failure of ['slow', 'proxy-admin-busy', 'paused', 'human-required']) {
|
||||
|
||||
@@ -181,16 +181,13 @@ test('at 390 px the dashboard lists the organizations without a horizontal scrol
|
||||
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= window.innerWidth'), true);
|
||||
});
|
||||
|
||||
// Review round finding 1: with no organization yet the page keeps its first-run addresses, so the
|
||||
// wordmark (href "#/") opens the first-run board, not a #/dashboard the first-run page has no view for.
|
||||
test('first run: the wordmark opens the first-run board, not a Not found page', async t => {
|
||||
// The organization Console has one home even before it has an organization.
|
||||
test('first run: the wordmark opens the single-pane Dashboard, not a Not found page', async t => {
|
||||
const { b, wait } = await setup(t, { path: '/#/settings/appearance', empty: true });
|
||||
await wait('document.querySelector("#bus-view h1")');
|
||||
await b.evaluate('document.querySelector(".wordmark").click()');
|
||||
// The board route empties the page view; give the router and render time to settle before checking.
|
||||
await wait('location.hash !== "#/settings/appearance"');
|
||||
await new Promise(r => setTimeout(r, 800));
|
||||
assert.equal(await b.evaluate('location.hash'), '#/');
|
||||
await wait('location.hash === "#/dashboard" && document.querySelector("[data-ws-home]")');
|
||||
assert.equal(await b.evaluate('location.hash'), '#/dashboard');
|
||||
assert.equal(await b.evaluate('!!document.querySelector("#bus-view .nf")'), false);
|
||||
assert.equal(await b.evaluate('window.MosaicOrg'), undefined);
|
||||
});
|
||||
|
||||
@@ -241,6 +241,22 @@ const HOLD_CONFLICT_READ = `(() => {
|
||||
})()`;
|
||||
const SAVE_AS = title => `(() => { const f = document.querySelector("#tb-dialog form"); f.title.value = ${JSON.stringify(title)}; f.requestSubmit(); })()`;
|
||||
const STATUS = 'document.querySelector("#tb-dialog [data-tb-form-status]")?.textContent';
|
||||
test('new tasks explain empty and malformed requirement ids inline and focus the field', async t => {
|
||||
const { b, wait, orgs } = await open(t);
|
||||
await b.evaluate('document.querySelector("[data-tb-new]").click()');
|
||||
await wait('document.querySelector("#tb-dialog").open');
|
||||
for (const value of ['', 'REQ-web-0']) {
|
||||
await b.evaluate(`(()=>{const f=document.querySelector('#tb-dialog form');f.title.value='A task';f.requirement.value=${JSON.stringify(value)};f.requestSubmit()})()`);
|
||||
assert.equal(await b.evaluate('document.activeElement.name'), 'requirement');
|
||||
assert.equal(await b.evaluate('document.querySelector("#tb-req-error").textContent'), 'Type a requirement ID using capital letters and a number, for example REQ-WEB-1.');
|
||||
assert.equal(await b.evaluate('document.querySelector("#tb-req-error").getAttribute("role")'), 'alert');
|
||||
assert.equal(await b.evaluate('document.querySelector("#tb-dialog [name=requirement]").getAttribute("aria-invalid")'), 'true');
|
||||
}
|
||||
assert.deepEqual(orgs.writes, []);
|
||||
await b.evaluate(`(()=>{const f=document.querySelector('#tb-dialog form');f.requirement.value='REQ-WEB-1';f.requestSubmit()})()`);
|
||||
await wait('!document.querySelector("#tb-dialog").open');
|
||||
assert.equal(orgs.writes[0][2].requirement, 'REQ-WEB-1');
|
||||
});
|
||||
|
||||
test('an Archive conflict reopens on the current task and never sends the old digest again', async t => {
|
||||
const { b, wait, orgs } = await open(t);
|
||||
|
||||
@@ -36,7 +36,7 @@ const shot = async (b, name, width) => {
|
||||
await b.evaluate('document.querySelector("#setup-step-worker").scrollIntoView({ block: "start" }); true');
|
||||
await b.screenshot(join(SHOTS, `${name}-${width}.png`));
|
||||
};
|
||||
const HOW = 'Choosing the worker model on this page is not built yet. To change it, edit execution.provider and execution.model in the config.';
|
||||
const HOW = 'Choosing the model for background work on this page is not available yet. Ask the person who manages this installation to change it.';
|
||||
|
||||
test('the owner sees card 5: the config\'s model, that the config wins, the usable list, and no save', { timeout: 90000 }, async t => {
|
||||
for (const width of [1440, 390]) {
|
||||
@@ -48,7 +48,7 @@ test('the owner sees card 5: the config\'s model, that the config wins, the usab
|
||||
const c = await card(b);
|
||||
assert.equal(c.hidden, false); assert.equal(c.badge, 'Done');
|
||||
assert.equal(c.summary, 'Worker runs use zai/glm-5.3.');
|
||||
assert.equal(c.using, 'Worker runs use zai/glm-5.3. The config names it (execution.provider and execution.model), and the config always wins.');
|
||||
assert.equal(c.using, 'Worker runs use zai/glm-5.3. It is set for this installation and takes priority over a choice saved here.');
|
||||
assert.equal(c.standing, 'An account serves it for pi, and it is switched on.');
|
||||
assert.deepEqual(c.models, ['zai/glm-5.3 zai / glm-5.3', 'zai/glm-5.3-air zai / glm-5.3-air']);
|
||||
assert.equal(c.how, HOW);
|
||||
@@ -64,16 +64,19 @@ test('the owner sees card 5: the config\'s model, that the config wins, the usab
|
||||
|
||||
test('a stored choice the config overrides says it has no effect; a model switched off, not served or Claude needs the owner', { timeout: 90000 }, async t => {
|
||||
const cases = [
|
||||
[view({ using: { from: 'config', provider: 'zai', model: null, standing: '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.', null],
|
||||
[view({ using: { from: 'choice', provider: 'zai', model: 'glm-5.3', standing: 'usable' } }), 'done', null, null, null],
|
||||
[view({ choice: { state: 'set', provider: 'zai', model: 'glm-5.3-air', revision: 2, updatedAt: null, standing: 'usable' } }), 'done', null, null,
|
||||
'A choice saved earlier (zai/glm-5.3-air) has no effect while the config names a worker model.'],
|
||||
'A choice saved earlier (zai/glm-5.3-air) has no effect while this installation has its own model set for background work.'],
|
||||
[view({ using: { from: 'config', provider: 'zai', model: 'glm-5.3-flash', standing: '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.', null],
|
||||
'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.', null],
|
||||
[view({ using: { from: 'config', provider: 'zai', model: 'gone', standing: 'not-served' } }), 'bad', 'No account serves it for pi.', 'No account serves it for pi now, so worker runs refuse to start.', null],
|
||||
[view({ using: { from: 'config', provider: 'anthropic', model: 'claude-opus-5-5', standing: '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.', null],
|
||||
[view({ using: { from: 'config', provider: 'zai', model: 'glm-5.3', standing: 'unknown' }, catalogue: 'unavailable', models: [] }), 'off', 'Whether it can run is not known.',
|
||||
'No organization\'s model list could be read, so whether it can run now is not known.', null],
|
||||
[view({ choice: { state: 'unreadable' } }), 'done', null, null, 'A choice saved earlier cannot be read. It has no effect while the config names a worker model.'],
|
||||
[view({ choice: { state: 'unreadable' } }), 'done', null, null, 'A choice saved earlier cannot be read. It has no effect while this installation has its own model set for background work.'],
|
||||
[view({ using: { from: 'config', provider: 'zai', model: 'glm-5.3', standing: 'unknown' }, catalogue: 'none', models: [] }), 'off', 'Whether it can run is not known.',
|
||||
'No organization is active, so whether it can run now is not known.', null],
|
||||
[view({ using: { from: 'config', provider: 'zai', model: 'glm-5.3', standing: 'unknown' }, catalogue: 'disabled', models: [] }), 'off', 'Whether it can run is not known.',
|
||||
@@ -87,10 +90,12 @@ test('a stored choice the config overrides says it has no effect; a model switch
|
||||
const c = await card(b);
|
||||
if (standing) {
|
||||
assert.equal(c.standing, standing);
|
||||
assert.equal(c.summary, `Worker runs use ${worker.using.provider}/${worker.using.model}. ${short}`);
|
||||
assert.equal(c.summary, `Worker runs use ${worker.using.provider ?? '(none)'}/${worker.using.model ?? '(none)'}. ${short}`);
|
||||
}
|
||||
assert.equal(c.choice, choice);
|
||||
assert.equal(c.how, HOW);
|
||||
assert.doesNotMatch([c.using, c.standing, c.choice, c.how].join(' '), /execution\.|\bconfig\b|\.json/);
|
||||
if (worker.using.from === 'choice') assert.equal(c.using, 'Worker runs use zai/glm-5.3, the choice saved here. No model is set for background work in this installation.');
|
||||
const why = { none: 'No organization is active', disabled: 'No organization has the model service on' }[worker.catalogue] ?? 'No organization\'s model list could be read';
|
||||
if (worker.catalogue !== 'ready') assert.deepEqual(c.models, [`Not known. ${why}.`]);
|
||||
if (worker.using.standing === 'off') { await shot(b, 'worker-config-off', 1440); await b.viewport(390, 844); await shot(b, 'worker-config-off', 390); }
|
||||
@@ -103,7 +108,7 @@ test('a stored choice the config overrides says it has no effect; a model switch
|
||||
test('the mock adapter, no model at all, and a view that could not be read', { timeout: 90000 }, async t => {
|
||||
const cases = [
|
||||
[view({ harness: 'mock', takesModel: false, using: { from: 'config', provider: 'fixture', model: 'fixture-deterministic', standing: 'unused' }, models: [] }), 'done', 'Worker runs use the mock adapter, which takes no model.', ['None. This adapter takes no model.']],
|
||||
[view({ using: null }), 'bad', 'No worker model is set. Set execution.provider and execution.model in the config.', null],
|
||||
[view({ using: null }), 'bad', 'No model is set for background work. Ask the person who manages this installation to choose one.', null],
|
||||
[view({ models: [] }), 'done', 'Worker runs use zai/glm-5.3.', ['None. No account serves a model for pi that is switched on and is not a Claude model.']],
|
||||
[null, 'off', 'The worker model could not be read.', null],
|
||||
];
|
||||
|
||||
@@ -15,12 +15,12 @@ const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString()
|
||||
const ACME_DECISION = 'dec-acme-7f3c9a21-5b8e-4d1f-9c2a-0e6b7d8f9a10';
|
||||
const BETA_DECISION = 'dec-beta-1a2b3c4d-5e6f-4a1b-8c9d-0e1f2a3b4c5d';
|
||||
// messages: { org: rows } is what that organization's bus messages read answers.
|
||||
function fixture({ pollMs, fail = {}, down = [], messages = {} } = {}) {
|
||||
function fixture({ pollMs, fail = {}, down = [], messages = {}, count = 3 } = {}) {
|
||||
const LIST = [
|
||||
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
|
||||
{ id: 'beta', label: 'Beta Works', theme: 'grove', busHealthy: true },
|
||||
{ id: 'gamma', label: 'Gamma Home', theme: 'rosewood', busHealthy: false },
|
||||
];
|
||||
].slice(0, count);
|
||||
const DATA = {
|
||||
acme: {
|
||||
projects: [
|
||||
@@ -72,8 +72,8 @@ function fixture({ pollMs, fail = {}, down = [], messages = {} } = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
async function setup(t, { viewport = [1440, 900], hash = '/', workspaceTimeoutMs, fail, down, messages } = {}) {
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture({ fail, down, messages }), log: () => {}, ...(workspaceTimeoutMs ? { workspaceTimeoutMs } : {}) });
|
||||
async function setup(t, { viewport = [1440, 900], hash = '/', workspaceTimeoutMs, fail, down, messages, count } = {}) {
|
||||
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture({ fail, down, messages, count }), log: () => {}, ...(workspaceTimeoutMs ? { workspaceTimeoutMs } : {}) });
|
||||
t.after(() => close(server));
|
||||
const b = await browser({ machine: false }); t.after(() => b.close());
|
||||
await b.viewport(...viewport);
|
||||
@@ -406,3 +406,22 @@ test('Sessions now names each session\'s organization for a screen reader', asyn
|
||||
assert.ok(who.some(w => /Acme Studio: coder/.test(w)), who.join('|'));
|
||||
assert.ok(who.some(w => /Beta Works: pm/.test(w)), who.join('|'));
|
||||
});
|
||||
|
||||
for (const count of [1, 3]) test(`root aliases use the single-pane Dashboard with ${count} organizations`, async t => {
|
||||
const { b, wait, text } = await setup(t, { hash: '#/', count });
|
||||
const home = async () => {
|
||||
await wait(`location.hash === "#/dashboard" && document.querySelectorAll("[data-ws-orgrow]").length === ${count}`);
|
||||
assert.equal(await text('#bus-view h1'), 'Dashboard');
|
||||
assert.doesNotMatch(await b.evaluate('document.body.innerText'), /Business overview|Held roles/);
|
||||
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]")?.getAttribute("href")'), '#/dashboard');
|
||||
};
|
||||
await home();
|
||||
const expected = await b.evaluate('document.querySelector("[data-ws-home]").innerText.replace(/read \\d\\d:\\d\\d/g, "read TIME")');
|
||||
for (const alias of ['', '#', '#/']) {
|
||||
await b.evaluate('location.hash="#/settings/appearance"');
|
||||
await wait('document.querySelector(".settings-appearance")');
|
||||
await b.evaluate(`location.hash=${JSON.stringify(alias)}`);
|
||||
await home();
|
||||
assert.equal(await b.evaluate('document.querySelector("[data-ws-home]").innerText.replace(/read \\d\\d:\\d\\d/g, "read TIME")'), expected);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user