From 61e4e7652035c4272a73fb77d8067fe3fbaea524 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Sun, 8 Nov 2026 22:55:55 -0600 Subject: [PATCH] Fix organization setup records and console regressions --- docs/TOOLS.md | 6 +- packages/bus/src/runtime.mjs | 15 ++--- packages/cli/src/project.mjs | 20 ++++++- packages/cli/tests/project.test.mjs | 27 ++++++++- packages/project/src/index.mjs | 1 + packages/project/src/paths.mjs | 16 +++++ packages/project/tests/project.test.mjs | 11 ++++ packages/webui/src/org-admin.mjs | 30 +++++++++- packages/webui/src/public/bus.css | 6 ++ packages/webui/src/public/bus.js | 57 +++++++++++++++--- packages/webui/src/public/chat.js | 15 +++-- packages/webui/src/public/org-create.js | 4 +- packages/webui/src/public/projects.css | 3 + packages/webui/src/public/projects.js | 6 +- packages/webui/src/serve.mjs | 2 +- packages/webui/tests/org-admin.test.mjs | 2 +- .../webui/tests/org-quick-browser.test.mjs | 10 +++- packages/webui/tests/org-quick-live.test.mjs | 31 ++++++++-- .../tests/org-request-status-browser.test.mjs | 11 ++++ .../webui/tests/org-switch-browser.test.mjs | 14 +++++ .../webui/tests/s7-fidelity-browser.test.mjs | 60 ++++++++++++++++++- 21 files changed, 308 insertions(+), 39 deletions(-) diff --git a/docs/TOOLS.md b/docs/TOOLS.md index aa5a0009a..3e8b8b5a3 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -1320,7 +1320,11 @@ refuses `project-no-commit` if the layout has no readable HEAD commit. It exits 0 when valid, 2 for project/record problems (including an undeclared project), 3 for configuration loading problems and 4 for usage. The optional business project `repo` is a normalized absolute record-repository path; the default is -`/projects///`. `root` remains the code checkout. +`/projects///`. For a registered organization, +`` is that organization's data root for both the CLI and its bus. +If an instance-root records repository already exists, initialization and reads +refuse and name both locations for inspection; they never move or copy it. +`root` remains the code checkout. The package README describes schemas and the shared agent record writer; agent writes never enter `spec/`, never absorb pending edits and refuse remotes. diff --git a/packages/bus/src/runtime.mjs b/packages/bus/src/runtime.mjs index 67c186c15..542de0b2e 100644 --- a/packages/bus/src/runtime.mjs +++ b/packages/bus/src/runtime.mjs @@ -491,6 +491,7 @@ export async function startBroker({ const withTokens = (id, result) => ({ ...result, tokens: limits.report(id) }); // Row 210 (#1707, design D7 step 6) and row 234 (#1740, r6 E2): the run dir and the host enrollment half. const runRoot = organization ? join(organization.dir, 'secrets', 'run') : null; + const recordArgs = context => ({ ...context, ...projectModule.recordContext({ ...context, dataRoot: instanceDataRoot ?? dataRoot, orgRoot: org ? dataRoot : null }) }); let broker; processing = createProcessing({ dataRoot, ...discordProcessingHooks(dataRoot), containerStop: createContainerStopper({ dataRoot }), onTransition: () => broker.reconcileProcessing(), @@ -656,9 +657,9 @@ export async function startBroker({ requirement_ids: candidate.requirement_ids ?? candidate.requirements.map(r => r.id) }); }; const catalog = createRequirementCatalog({ journal: { ...requestJournal, readCandidate, authority: services.prdAuthority, approval: services.prdApproval }, - readSpec: ({ business, project }) => projectModule.readSpec({ business: services.prdBusiness(business), project, dataRoot }), + readSpec: ({ business, project }) => projectModule.readSpec(recordArgs({ business: services.prdBusiness(business), project })), builtinBinding: services.builtinBinding, projectArchived: services.projectArchived, threadProject: services.threadProject }); - return (requestLifecycle = createRequestLifecycle({ journal: requestJournal, services: { catalog, readCandidate, readReviewedArtifact: (state, commit, path) => readReviewedArtifact({ repo: workingRepo(dataRoot, state.business, state.project), commit, path }), readVerification: (state, record) => projectModule.readProjectFile({ business: services.prdBusiness(state.business), project: state.project, dataRoot, path: record.path, commit: record.commit }), requestAdmission: state => admission({ business: state.business, project: state.project }), ...(writer ? hostPreparation({ dataRoot, organization: writer, trackers, journal: requestJournal, catalog, admission, work: fn => processing.work(fn), readSpec: ({ business, project }) => projectModule.readSpec({ business: services.prdBusiness(business), project, dataRoot }) }) : {}), ...requestServices, ...services, + return (requestLifecycle = createRequestLifecycle({ journal: requestJournal, services: { catalog, readCandidate, readReviewedArtifact: (state, commit, path) => readReviewedArtifact({ repo: workingRepo(dataRoot, state.business, state.project), commit, path }), readVerification: (state, record) => projectModule.readProjectFile(recordArgs({ business: services.prdBusiness(state.business), project: state.project, path: record.path, commit: record.commit })), requestAdmission: state => admission({ business: state.business, project: state.project }), ...(writer ? hostPreparation({ dataRoot, organization: writer, trackers, journal: requestJournal, catalog, admission, work: fn => processing.work(fn), readSpec: ({ business, project }) => projectModule.readSpec(recordArgs({ business: services.prdBusiness(business), project })) }) : {}), ...requestServices, ...services, // The new-project executor needs the organization writer; without one a confirmed selection stays at its setup wait. ...(writer ? { bootstrap: ({ binding, state }) => processing.work(() => executeBootstrap({ binding, owner: state.owner, journal: requestJournal, services: { dataRoot, organization: writer, activate: activateManagedProject, barrier: requestServices.barrier, projectArchived: services.projectArchived, threadProject: services.threadProject, @@ -717,11 +718,11 @@ export async function startBroker({ GuardError: libraryModule.GuardError, }, project: { - readSpec: context => projectModule.readSpec({ ...context, dataRoot }), - writeRecord: context => processing.work(() => projectModule.writeRecord({ ...context, dataRoot })), - listFiles: context => projectModule.listProjectFiles({ ...context, dataRoot }), - readFile: context => projectModule.readProjectFile({ ...context, dataRoot }), - writeFile: context => projectModule.writeHumanFile({ ...context, dataRoot }), + readSpec: context => projectModule.readSpec(recordArgs(context)), + writeRecord: context => processing.work(() => projectModule.writeRecord(recordArgs(context))), + listFiles: context => projectModule.listProjectFiles(recordArgs(context)), + readFile: context => projectModule.readProjectFile(recordArgs(context)), + writeFile: context => projectModule.writeHumanFile(recordArgs(context)), ProjectError: projectModule.ProjectError, }, // limits and limits.set (organization.set is limits.set) carry each token limit's count; a diff --git a/packages/cli/src/project.mjs b/packages/cli/src/project.mjs index 6c3293973..0884820a5 100644 --- a/packages/cli/src/project.mjs +++ b/packages/cli/src/project.mjs @@ -1,9 +1,12 @@ import { configDir, loadBusiness } from '../../business/src/index.mjs'; -import { checkProject, initProject, ProjectError, testerProjectArea } from '../../project/src/index.mjs'; +import { checkProject, initProject, ProjectError, testerProjectArea, recordContext } from '../../project/src/index.mjs'; import { loadSystem, rolesDir } from './config.mjs'; import { CliError } from './errors.mjs'; import { shortId } from './format.mjs'; import { parseArgs } from './thread.mjs'; +import { basename, join } from 'node:path'; +import { lstatSync } from 'node:fs'; +import { readRegistry, resolveOrg } from '../../business/src/org-registry.mjs'; import { refuseInsideAgent } from './transport.mjs'; export const PROJECT_USAGE = 'mosaic project init [--tester] | check '; @@ -77,7 +80,20 @@ export async function projectCommand(args, io, deps = {}, callFor) { try { const system = deps.system ?? loadSystem({ env: io.env }); const business = loadBusiness(id, { dir: configDir(io.env), rolesDir: rolesDir(io.env) }); - const context = { business, project, dataRoot: system.dataRoot }; + const dir = configDir(io.env), named = /^mosaic-([a-z][a-z0-9]{1,15})$/.exec(basename(dir)); + let orgRoot = null; + let registryPresent = false; + if (named) { try { lstatSync(join(dir, 'org-runtime.json')); registryPresent = true; } catch (e) { if (e.code !== 'ENOENT') throw e; } } + if (named && registryPresent) { + const registry = await readRegistry({ configDir: dir }); + if (registry?.orgs?.[id]) { + const org = await resolveOrg({ configDir: dir, dataRoot: system.dataRoot, instance: named[1] }, id); + if (org.state !== 'active') throw new CliError('organization is not active', 3); + orgRoot = org.root; + } + } + if (tester && orgRoot) throw new CliError('organization project init --tester is unavailable', 3); + const context = recordContext({ business, project, dataRoot: system.dataRoot, orgRoot }); if (tester) { testerProjectArea(context); await callFor({ positional: [], flags: new Set(['--tester']), values: { '--business': id } })('agents', {}); diff --git a/packages/cli/tests/project.test.mjs b/packages/cli/tests/project.test.mjs index fe6f45064..7ba93ba00 100644 --- a/packages/cli/tests/project.test.mjs +++ b/packages/cli/tests/project.test.mjs @@ -1,10 +1,10 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { readFileSync, writeFileSync, existsSync } from 'node:fs'; +import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; import { spawnSync } from 'node:child_process'; import { main, run } from '../src/cli.mjs'; -import { fixture, humanEnv, io, tmp } from './helpers.mjs'; +import { fixture, humanEnv, io, tmp, orgFixture } from './helpers.mjs'; import { writeJson } from '../../business/tests/helpers.mjs'; test('project init/check use declared business repo and never contact the bus', async t => { @@ -125,3 +125,26 @@ test('project list --archived includes and marks archived projects', async t => assert.deepEqual(calls.at(-1), ['project.list', { includeArchived: true }]); assert.equal(archived.out.text, `live - ${A.slice(0, 8)}\nshelved archived - ${B.slice(0, 8)}\n`); }); + + +test('organization project init and check use the organization data root', async t => { + const { f, org } = await orgFixture(t); + const out = io(humanEnv(f.env)); + assert.equal(await run(['project', 'init', 'acme', 'stack'], out, {}), 0, out.err.text); + assert.ok(existsSync(join(org.root, 'projects/acme/stack/spec/north-star.md'))); + assert.equal(existsSync(join(f.dataRoot, 'projects/acme/stack')), false); + const checked = io(humanEnv(f.env)); + assert.equal(await run(['project', 'check', 'acme', 'stack'], checked, {}), 0, checked.err.text); +}); + +test('organization project init refuses existing instance-root records without changing them', async t => { + const { f, org } = await orgFixture(t); + const old = join(f.dataRoot, 'projects/acme/stack'), expected = join(org.root, 'projects/acme/stack'); + mkdirSync(old, { recursive: true }); + writeFileSync(join(old, 'keep'), 'preserve'); + const out = io(humanEnv(f.env)); + assert.notEqual(await run(['project', 'init', 'acme', 'stack'], out, {}), 0); + assert.ok(out.err.text.includes(old)); assert.ok(out.err.text.includes(expected)); + assert.equal(readFileSync(join(old, 'keep'), 'utf8'), 'preserve'); + assert.equal(existsSync(expected), false); +}); diff --git a/packages/project/src/index.mjs b/packages/project/src/index.mjs index 7a330477d..1f2c3664d 100644 --- a/packages/project/src/index.mjs +++ b/packages/project/src/index.mjs @@ -8,6 +8,7 @@ import { ProjectError, checkedId, documentPath, noLinks, projectRepo, testerProj import { git, identity, inspectGit, requireClean } from './git.mjs'; import { validateRecord } from './validate.mjs'; export { ProjectError, projectRepo, testerProjectArea, validateRecord }; +export { recordContext } from './paths.mjs'; const DIRECTORIES = ['spec', 'docs', 'requirements', 'decisions', 'templates']; const TEMPLATES = ['project.json', 'requirement.json', 'decision.json', 'document.md', 'north-star.md']; diff --git a/packages/project/src/paths.mjs b/packages/project/src/paths.mjs index 0ef7cca63..0c9ce4369 100644 --- a/packages/project/src/paths.mjs +++ b/packages/project/src/paths.mjs @@ -31,6 +31,22 @@ const contains = (base, child) => { const rel = relative(base, child); return rel === '' || (rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel)); }; +// Resolve organization record storage once for CLI, Console and bus. An old instance-root +// repository is never silently hidden by selecting the organization root. +export function recordContext({ business, project, dataRoot, orgRoot = null }) { + if (orgRoot === null) return { business, project, dataRoot }; + checkedId(business?.id); checkedId(project); absolute(dataRoot); absolute(orgRoot); + const entry = business.projects?.[project]; + if (entry) { + const old = join(dataRoot, 'projects', business.id, project); + const target = join(orgRoot, 'projects', business.id, project); + if (old !== target) { + try { lstatSync(old); throw new ProjectError('project-records-conflict', `instance-root records exist at ${old}; organization records belong at ${target}. Inspect both before continuing`); } + catch (e) { if (e.code !== 'ENOENT') throw e; } + } + } + return { business, project, dataRoot: orgRoot }; +} export function projectRepo({ business, project, dataRoot }, { allowLibrary = false } = {}) { checkedId(business?.id); checkedId(project); if (!Object.hasOwn(business?.projects ?? {}, project)) diff --git a/packages/project/tests/project.test.mjs b/packages/project/tests/project.test.mjs index 789934f85..bea2ca30a 100644 --- a/packages/project/tests/project.test.mjs +++ b/packages/project/tests/project.test.mjs @@ -24,6 +24,17 @@ async function ready(t, custom) { return { c, repo: initialized.repo, commit: initialized.commit }; } +test('organization records refuse instance-root conflicts even with an explicit repository', t => { + const c = context(t, 'records'), orgRoot = join(c.root, 'org'); + const old = join(c.dataRoot, 'projects/acme/stack'), target = join(orgRoot, 'projects/acme/stack'); + mkdirSync(old, { recursive: true }); mkdirSync(target, { recursive: true }); + writeFileSync(join(old, 'keep'), 'old'); writeFileSync(join(target, 'keep'), 'org'); + assert.throws(() => api.recordContext({ ...c, orgRoot }), e => + e.code === 'project-records-conflict' && e.message.includes(old) && e.message.includes(target)); + assert.equal(readFileSync(join(old, 'keep'), 'utf8'), 'old'); + assert.equal(readFileSync(join(target, 'keep'), 'utf8'), 'org'); +}); + test('C2-04: record APIs refuse a library before creating a repository', async t => { const c = context(t); c.business.projects = { books: { kind: 'library' }, ...c.business.projects }; diff --git a/packages/webui/src/org-admin.mjs b/packages/webui/src/org-admin.mjs index a0a4b33d3..e60aa7d2f 100644 --- a/packages/webui/src/org-admin.mjs +++ b/packages/webui/src/org-admin.mjs @@ -21,13 +21,16 @@ // handler returns false for them. import { open } from 'node:fs/promises'; +import { lstatSync } from 'node:fs'; +import { checkProject, initProject, projectRepo, recordContext } from '../../project/src/index.mjs'; +import { refuseInsideAgent } from '../../cli/src/transport.mjs'; import { join } from 'node:path'; const ID = /^[a-z0-9][a-z0-9._-]{0,63}$/; const KEY = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; const ENV_NAME = /^[A-Z][A-Z0-9_]{0,63}$/; const MAX_BODY = 64 * 1024; -const ROUTE = /^\/api\/orgs\/([^/]+)\/(admin|setup|delete|archive|restore)(?:\/(queue|bus|project\/([^/]+)))?$/; +const ROUTE = /^\/api\/orgs\/([^/]+)\/(admin|setup|delete|archive|restore)(?:\/(queue|bus|project\/([^/]+)|records\/([^/]+)))?$/; // The org-template placeholder (packages/business/src/org-service.mjs templateRender). export const placeholderRoot = (id, project) => `/__mosaic_org__/${id}/projects/${project}`; // Project fields the server owns. The browser never sees or sends them. @@ -42,6 +45,7 @@ export function verbFor(step, id, opts = {}) { if (step === 'project') return `mosaic org project repo init ${id} ${opts.project} ${tail}`; if (step === 'archive' || step === 'restore') return `mosaic org ${step} ${id} --if-revision ${opts.revision}`; if (step === 'delete') return `mosaic org delete ${id} --confirm ${id} --if-revision ${opts.revision}`; + if (step === 'records') return `mosaic project init ${id} ${opts.project}`; if (step === 'bus') return `mosaic bus start ${id} --dev-local-owner --detach`; throw new Error(`unknown step ${step}`); } @@ -428,7 +432,8 @@ async function route(req, res, { path, search, org, admin, principal, write, log return json(res, 201, { outcome: 'done', step: 'create', receipt: forReceipt(ctx, receipt), verb: verbFor('create', body.id) }); } if (!org) return json(res, 404, { error: 'not found' }); - const [, id, kind, sub, project] = org; + const [, id, kind, sub, repoProject, recordsProject] = org; + const project = repoProject ?? recordsProject; if (!ID.test(id)) return json(res, 404, { error: 'org-unavailable' }); const service = await need(admin, 'service', res, kind); if (!service) return; const ctx = await ctxOf(admin, principal); @@ -479,6 +484,27 @@ async function route(req, res, { path, search, org, admin, principal, write, log try { receipt = await service.updateOrg(ctx, id, doc, { ifRevision: body.ifRevision }); } catch (e) { return refusal(res, e, { step: 'update', id, unknownOk: true }); } return json(res, 200, { outcome: 'done', step: 'update', receipt: forReceipt(ctx, receipt), verb: verbFor('update', id, { revision: body.ifRevision }) }); } + if (kind === 'setup' && sub?.startsWith('records/')) { + let name; + try { name = decodeURIComponent(project); } catch { return json(res, 404, { error: 'not found' }); } + if (!ID.test(name)) return json(res, 404, { error: 'not found' }); + if (write) { const body = await readBody(req); strictKeys(body, []); } + try { + const shown = await service.showOrg(ctx, id); + if (!Object.hasOwn(shown.doc?.projects ?? {}, name)) return json(res, 404, { error: 'project-unknown', step: 'records' }); + const context = recordContext({ business: shown.doc, project: name, dataRoot: ctx.dataRoot, orgRoot: shown.root }); + const repo = projectRepo(context); + let exists = true; + try { lstatSync(repo); } catch (e) { if (e.code === 'ENOENT') exists = false; else throw e; } + if (!exists && write) { refuseInsideAgent(); await initProject(context); } + if (!exists && !write) return json(res, 200, { state: 'missing', step: 'records', verb: verbFor('records', id, { project: name }) }); + const checked = await checkProject(context); + if (!checked.ok) return json(res, 409, { error: 'readback-failed', step: 'records', message: 'Project records could not be verified; inspect them before retrying.' }); + return json(res, 200, { state: 'done', outcome: 'done', step: 'records', verb: verbFor('records', id, { project: name }) }); + } catch (e) { + return json(res, 409, { error: e.code ?? 'readback-failed', step: 'records', message: plainMessage(ctx, e.message ?? 'Project records could not be verified.') }); + } + } if (kind === 'setup' && !sub && !write) { try { return json(res, 200, await readSetup(admin, ctx, id)); } catch (e) { return refusal(res, e, { step: 'setup', id }); } } diff --git a/packages/webui/src/public/bus.css b/packages/webui/src/public/bus.css index d6d7acc68..72f6a85c4 100644 --- a/packages/webui/src/public/bus.css +++ b/packages/webui/src/public/bus.css @@ -54,3 +54,9 @@ table.s1-table tbody th{font-weight:600;text-transform:none;letter-spacing:0;col /* Role names stay whole; the wrapper scrolls if they need more room. */ table.s1-roles { min-width:480px; } table.s1-roles td,table.s1-roles th { overflow-wrap:normal; word-break:normal; } + +/* Role names remain readable without making the organization panel wider on phones. */ +@media (max-width: 699px) { + table.s1-roles { min-width: 0; width: 100%; table-layout: fixed; } + table.s1-roles td, table.s1-roles th { overflow-wrap: anywhere; } +} diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index 83bb295ea..6a8a60561 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -22,6 +22,18 @@ // ---------------------------------------------------------------- reads // One GET per Q1 read. The last good answer for each read is kept, so a failed read // can show what was read before, labelled as such. + let spriteRetry = false, spriteVersion = 0; + window.MosaicIcons = { + failed() { spriteRetry = true; }, + succeeded() { + if (!spriteRetry) return; + spriteRetry = false; spriteVersion++; + for (const use of document.querySelectorAll('use[href^="/icons.svg"]')) { + const fragment = use.getAttribute('href').split('#')[1]; + if (fragment) use.setAttribute('href', `/icons.svg?retry=${spriteVersion}#${fragment}`); + } + }, + }; const last = new Map(); class ReadError extends Error { constructor(code, message, status) { super(message); this.code = code; this.status = status; } } // Row 95 (#1589): every Console fetch takes `redirect: 'manual'`. A redirect comes only from the @@ -39,11 +51,13 @@ if (out()) throw signedOut(); let res, body; try { res = await fetch(`/api/bus/${verb}${subject === undefined ? '' : `?${verb === 'replies' ? 'id' : verb === 'messages' ? 'after' : 'subject'}=${enc(subject)}`}`, { cache: 'no-store', redirect: 'manual' }); } - catch { throw new ReadError('unreachable', 'The Console server did not answer.', 0); } + catch { window.MosaicIcons.failed(); throw new ReadError('unreachable', 'The Console server did not answer.', 0); } if (res.type === 'opaqueredirect') { signOut(); throw signedOut(); } - try { body = await res.json(); } catch { throw new ReadError('unreachable', 'The Console server did not answer.', 0); } + try { body = await res.json(); } catch { window.MosaicIcons.failed(); throw new ReadError('unreachable', 'The Console server did not answer.', 0); } if (signInRequired(res, body)) { signOutSso(); throw signedOut(); } + if (!res.ok) window.MosaicIcons.failed(); if (!res.ok || !body || !Array.isArray(body.rows)) throw new ReadError(typeof body?.error === 'string' ? body.error : 'invalid-response', typeof body?.message === 'string' ? body.message : `HTTP ${res.status}`, res.status); + window.MosaicIcons.succeeded(); return { ...body, rows: body.rows, at: body.at }; } // Row 54 (#1543): the queue, business and settings reads (src/reads.mjs), GET only. Their @@ -52,11 +66,13 @@ if (out()) throw signedOut(); const unreachable = () => Object.assign(new ReadError('unreachable', 'The Console server did not answer.', 0), { module: true }); let res, body; - try { res = await fetch(`/api/${path}`, { cache: 'no-store', redirect: 'manual' }); } catch { throw unreachable(); } + try { res = await fetch(`/api/${path}`, { cache: 'no-store', redirect: 'manual' }); } catch { window.MosaicIcons.failed(); throw unreachable(); } if (res.type === 'opaqueredirect') { signOut(); throw signedOut(); } try { body = await res.json(); } catch { throw unreachable(); } if (signInRequired(res, body)) { signOutSso(); throw signedOut(); } + if (!res.ok) window.MosaicIcons.failed(); if (!res.ok || !body || typeof body !== 'object' || Array.isArray(body)) throw Object.assign(new ReadError(typeof body?.error === 'string' ? body.error : 'invalid-response', typeof body?.message === 'string' ? body.message : `HTTP ${res.status}`, res.status), { module: true }); + window.MosaicIcons.succeeded(); return body; } // A reader for one render. `live` asks the server; otherwise only kept answers are used. @@ -253,7 +269,7 @@ const items = [['/', 'Dashboard', '', 'board'], ['/projects', 'Projects', '', 'inbox'], ['/inbox', 'Inbox', inboxCount?.open > 0 ? `${inboxCount.open}${inboxCount.blocking ? ` ${blockChip(`${inboxCount.blocking} blocking`)}` : ''}` : '', 'inbox'], ['/messages', 'Messages', messageCount > 0 ? `${messageCount}` : '', '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 `
  • ${l}${extra ? ` ${extra}` : ''}${h === '/projects' ? '
    ' : ''}
  • `; + return `
  • ${l}${extra ? ` ${extra}` : ''}${h === '/projects' ? '
    ' : ''}
  • `; }).join(''); window.MosaicProjectTree?.mount?.({ container: $('project-tree'), path: route }); if (focused) [...$('sections').querySelectorAll('a[href]')].find(a => a.getAttribute('href') === focused)?.focus({ preventScroll: true }); @@ -276,6 +292,32 @@ // reply to its own message, so a reply to a Console send stays unread in `mosaic inbox` until // the human marks it read with `mosaic inbox --read`. let isTester = false, orgSetup = false; + // Both Docs and project direction use the same owner-only records setup action. + window.MosaicRecords = { + markup(project) { + const org = window.MosaicOrg?.id; + if (!org) return 'This project has no records yet. Initialize its record repository to add documents.'; + const command = `mosaic project init ${org} ${project}`; + return `This project has no records yet. ${orgSetup ? ` ` : 'Run '}${txt(command)}`; + }, + }; + document.addEventListener('click', async e => { + const button = e.target.closest?.('[data-record-init]'); + if (!button || button.disabled || !orgSetup || !window.MosaicOrg) return; + button.disabled = true; + const status = button.parentElement.querySelector('[data-record-receipt]'); + const url = `/api/orgs/${encodeURIComponent(window.MosaicOrg.id)}/setup/records/${encodeURIComponent(button.dataset.recordInit)}`; + try { + const response = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' }); + const body = await response.json(); + if (!response.ok || body.outcome !== 'done' || body.step !== 'records') throw Error(body.message || 'Initialization was refused. Inspect the project before retrying.'); + const readback = await fetch(url, { cache: 'no-store' }); + const checked = await readback.json(); + if (!readback.ok || checked.state !== 'done') throw Error('Read-back failed. Inspect the project before retrying.'); + document.getElementById('refresh')?.click(); + } catch (error) { if (status) status.textContent = ` ${error.message || 'Outcome unknown. Inspect the project before retrying.'}`; } + }); + let configRead = Promise.resolve(); let canSend = false, chatSend = false, sendRoles = null, sending = false, receipt = null, replies = []; const REPLIES = 50; // the broker's cap @@ -1207,7 +1249,7 @@ try { files = (await get.api(`project-files?project=${enc(p)}`)).files; } catch (err) { if (err.code === 'signed-out' || refusal(err)) throw err; code = err.code; } files = Array.isArray(files) ? files.filter(f => typeof f?.path === 'string' && DOC_PATH.test(f.path)) : []; - blocks.push(`

    ${txt(p)} ${files.length}

    ${code === 'project-records-missing' ? '

    This project has no records yet. Initialize its record repository to add documents.

    ' : code ? `

    These files could not be read. Read again to retry. ${txt(code)}

    ${retry}` : files.length ? `` : '

    No spec or docs files.

    '}
    `); + blocks.push(`

    ${txt(p)} ${files.length}

    ${code === 'project-records-missing' ? `

    ${window.MosaicRecords.markup(p)}

    ` : code ? `

    These files could not be read. Read again to retry. ${txt(code)}

    ${retry}` : files.length ? `` : '

    No spec or docs files.

    '}
    `); } return `${head('Docs', `${readLine()} The spec and the files under docs/ of each project. ${canEdit ? 'Open one to edit it; a save makes one commit in the project with you as the author.' : 'Saving needs a Console started with --send behind the sign-in proxy; this one only reads.'}`)} ${blocks.join('') || empty('This business declares no projects.', 'A project shows here when the business file names it.')}`; @@ -1338,7 +1380,7 @@ const refusal = err => err.status === 403 || ['not-configured', 'no-bus-host', 'queue-refused'].includes(err.code); // After a refusal nothing read before is shown anywhere: not in a view, the palette or the Inbox count. function forget() { window.MosaicChat?.forget(); last.clear(); inboxCount = null; messageCount = null; } - const failedView = err => `${head(failTitle(err))}${empty('Nothing to show.', refusal(err) ? 'The view stays empty until the problem above is fixed.' : err.module ? 'Read again.' : 'Read again, or come back when the bus answers.')}`; + const failedView = (err, path) => `${head(path === '/queue' ? 'Queue' : failTitle(err))}${empty('Nothing to show.', refusal(err) ? 'The view stays empty until the problem above is fixed.' : err.module ? 'Read again.' : 'Read again, or come back when the bus answers.')}`; const staleBanner = err => ``; // Freshness line in the command bar for bus pages. const stamp = iso => { const t = Date.parse(iso); return Number.isFinite(t) ? `${new Date(t).toISOString().slice(11, 19)} UTC` : 'unknown'; }; @@ -1487,7 +1529,7 @@ if (err.code === 'signed-out') return; const kept = reader(false); try { if (refusal(err)) throw err; html = await view(kept, path, new URLSearchParams(query), opts, current); readAt = kept.oldest(); html = staleBanner(err) + html; state = 'stale'; } - catch { html = failedView(err) + (path === '/settings' ? appearance() : ''); state = refusal(err) ? 'refused' : 'failed'; } + catch { html = failedView(err, path) + (path === '/settings' ? appearance() : ''); state = refusal(err) ? 'refused' : 'failed'; } if (refusal(err)) forget(); } if (!current()) return; @@ -1660,6 +1702,7 @@ canSend = !isTester && c?.send === true; chatSend = !isTester && c?.chatSend === true; orgSetup = !isTester && c?.orgSetup === true; + window.MosaicOrgBusStopped = !!window.MosaicOrg && c?.devOwner === true && orgSetup && c?.chatSend === false; // The header menu offers "New organization" to the owner of a Console with organizations; nobody else can create one. if (orgSetup && !$('org-new-link')) { const a = document.createElement('a'); a.id = 'org-new-link'; a.href = NEW_ORG; a.setAttribute('role', 'menuitem'); a.textContent = 'New organization'; document.querySelector('#avatar-menu > a[href="#/settings"]')?.after(a); } ssoOn = c?.sso === true; diff --git a/packages/webui/src/public/chat.js b/packages/webui/src/public/chat.js index 9606d677e..5bb01b617 100644 --- a/packages/webui/src/public/chat.js +++ b/packages/webui/src/public/chat.js @@ -85,13 +85,15 @@ }); } catch (err) { if (err.name === 'AbortError') throw err; + window.MosaicIcons?.failed(); throw new ChatError(value === undefined ? 'unreachable' : 'outcome-unknown'); } if (res.type === 'opaqueredirect' || res.status === 401) { signOut(); throw new ChatError('signed-out'); } let data; try { data = await res.json(); } catch { throw new ChatError(value === undefined ? 'invalid-response' : 'outcome-unknown'); } - if (!res.ok) throw new ChatError(typeof data?.error === 'string' ? data.error : 'invalid-response', res.status, data?.sent); + if (!res.ok) { window.MosaicIcons?.failed(); throw new ChatError(typeof data?.error === 'string' ? data.error : 'invalid-response', res.status, data?.sent); } + window.MosaicIcons?.succeeded(); if (!data || typeof data !== 'object' || (value === undefined && !path.includes('/operation?') && !Array.isArray(data.rows))) { throw new ChatError(value === undefined ? 'invalid-response' : 'outcome-unknown'); } @@ -105,7 +107,7 @@ const heading = text => `

    ${txt(text)}

    `; const selectedInactive = () => { const s = current?.sessions?.find(r => r.id === current.session); return !!s?.state && s.state !== 'active'; }; const disabledSession = pending => disabled(pending || selectedInactive()); - const disabled = pending => !current.canSend || out() || pending ? ' disabled' : ''; + const disabled = pending => !current.canSend || current.orgArchived || out() || pending ? ' disabled' : ''; const stamp = at => { const date=new Date(at); const projectSurface=window.MosaicProjects && !current?.user && !current?.tester && (!legacyRoute() || current.path?.startsWith('/projects')); return projectSurface && Number.isFinite(date.getTime()) ? `` : ``; }; // Per-grant UI hints; all writes still use the caller's bus principal. const scopeWrites = (project, instance) => !current.user || current.chatGrants.some(g => @@ -498,6 +500,7 @@ const keep = capture(), c = current; const redesigned = (!legacyRoute() || c.path?.startsWith('/projects')) && !!window.MosaicProjects && !c.user && !c.tester; let html = '

    Projects

    '; + if (c.orgArchived) html += `

    ${c.orgArchived === 'room-not-open' ? 'This room is not open.' : 'This organization is archived.'} Sending is unavailable; your draft is kept.

    `; if (c.error && !(c.kind === 'room' && c.error === ROOM_LINES['room-not-open'] && redesigned)) html += ``; if (c.archiveUnknown && !c.loading) html += '

    Archive status unavailable. Some changes are unavailable; sending may be refused; refresh to check.

    '; else if (c.kind === 'thread' && c.projectArchived) html += '

    This project is archived; its conversation stays readable.

    '; @@ -526,7 +529,7 @@ } else { html += heading('Projects') + '

    Projects and their conversations.

    ' + c.projects.map(p => `

    ${link('projects', p.id, p.name)}

    ${p.repo ? `

    Repository: ${txt(p.repo)}

    ` : ''}${threads(c.threads.filter(t => t.project === p.id && !t.shared))}
    `).join('') + (c.projects.length ? '' : c.readFailed ? '

    Projects unavailable.

    ' : '

    No projects yet.

    ') + '

    Shared with me

    ' + threads(c.threads.filter(t => t.shared)) + creation('project', 'projects'); } - if (!c.canSend) html += '

    Creating and sending require signed-in send mode. This Console only reads.

    '; + if (!c.canSend) html += window.MosaicOrgBusStopped ? '

    The bus is stopped. Use Start the bus to send messages.

    ' : '

    Creating and sending require signed-in send mode. This Console only reads.

    '; transcriptObserver?.disconnect(); transcriptResize?.disconnect(); c.container.innerHTML = html + '
    '; const observedLog = c.container.querySelector('.project-chat .chat-log'); @@ -639,7 +642,7 @@ paint(); return; } const old = current; - current = { container, kind, id, loading: true, archiveUnknown: kind === 'thread' && !user && !tester, settings: !!settings, section, path: originalPath, canSend, user, tester, chatGrants: [], thread: old && old.id === id ? old.thread : null, shared: old && old.id === id ? old.shared : false, projects: old?.projects ?? [], threads: old?.threads ?? [], repos: old?.repos ?? [], instances: old?.instances ?? [], instanceError: kind === 'project' ? 'Reading thread instances…' : '', error: '', readFailed: false, channelDisabled: old?.channelDisabled ?? false, refused: false, legacyDefault: old && old.id === id ? old.legacyDefault : false, sessions: old && old.id === id ? old.sessions ?? [] : [], session: match[3] ?? (old && old.id === id ? old.session : null), key: match[3] ? id + '/' + match[3] : old && old.id === id ? old.key : id }; + current = { container, kind, id, orgArchived: old?.orgArchived ?? false, loading: true, archiveUnknown: kind === 'thread' && !user && !tester, settings: !!settings, section, path: originalPath, canSend, user, tester, chatGrants: [], thread: old && old.id === id ? old.thread : null, shared: old && old.id === id ? old.shared : false, projects: old?.projects ?? [], threads: old?.threads ?? [], repos: old?.repos ?? [], instances: old?.instances ?? [], instanceError: kind === 'project' ? 'Reading thread instances…' : '', error: '', readFailed: false, channelDisabled: old?.channelDisabled ?? false, refused: false, legacyDefault: old && old.id === id ? old.legacyDefault : false, sessions: old && old.id === id ? old.sessions ?? [] : [], session: match[3] ?? (old && old.id === id ? old.session : null), key: match[3] ? id + '/' + match[3] : old && old.id === id ? old.key : id }; current.projectArchived = current.projects.some(p => p.id === (kind === 'project' ? id : current.thread?.project) && p.archived); if (kind === 'thread' && old?.kind === 'thread' && old.id === id && !navigated && old.archiveUnknown === false && old.projects.some(p => p.id === old.thread?.project)) current.archiveUnknown = false; if (current.projectArchived) current.archiveUnknown = false; @@ -681,6 +684,7 @@ ]); if (g !== generation || out()) return; current.channelDisabled = false; + current.orgArchived = false; current.projects = projects.rows; const own = new Set(listed.rows.map(t => t.id)); current.threads = [...listed.rows, ...shared.rows.filter(t => !own.has(t.id)).map(t => ({ ...t, shared: true }))]; @@ -840,6 +844,7 @@ if (g !== generation || out() || err.name === 'AbortError' || err.code === 'signed-out') return; current.loading = false; current.error = readError(err); + if (err.code === 'org-archived' || err.code === 'room-not-open') current.orgArchived = err.code; current.readFailed = true; if (err.code === 'channel-disabled') current.channelDisabled = true; // A bad session selector is local to that read. Only a thread-level refusal @@ -936,7 +941,7 @@ s.follow = transcriptAtTail(log); }, true); async function write(action, key, value, path) { - if (!current || !current.canSend || out() || current.channelDisabled) return; + if (!current || !current.canSend || current.orgArchived || out() || current.channelDisabled) return; const isThread = action === 'send' || action === 'open'; if ((isThread || action === 'createSession') && !threadWrites()) return; if (action === 'createSession' && current.archiveUnknown) return; diff --git a/packages/webui/src/public/org-create.js b/packages/webui/src/public/org-create.js index 4bb7d0ea8..a41258340 100644 --- a/packages/webui/src/public/org-create.js +++ b/packages/webui/src/public/org-create.js @@ -309,6 +309,7 @@ { title: `Initialize project repository: ${project}`, verb: `mosaic org project repo init ${id} ${project} ${remote ? `--remote ${remote}` : '--local-only --accept-local-loss-risk'}` }, { title: 'Start the bus', verb: `mosaic bus start ${id} --dev-local-owner --detach` }, { title: `Create project: ${project}`, verb: `mosaic project create ${project} --repo ${project} --business ${id}` }, + { title: 'Initialize project records', verb: `mosaic project init ${id} ${project}` }, ]; const list = $('org-quick-steps'); list.innerHTML = steps.map((s, i) => `
  • ${txt(s.title)}

    Not started

    Same as ${txt(s.verb)}

  • `).join(''); @@ -325,6 +326,7 @@ [`/api/orgs/${enc(id)}/setup/project/${enc(project)}`, remote ? { mode: 'remote', remote } : local, 'project'], [`/api/orgs/${enc(id)}/setup/bus`, {}, 'bus'], [`/api/orgs/${enc(id)}/chat/projects`, { name: project, repo: project }, 'chat-project'], + [`/api/orgs/${enc(id)}/setup/records/${enc(project)}`, {}, 'records'], ]; for (current = 0; current < requests.length; current++) { const card = list.children[current]; card.querySelector('.org-pill').textContent = 'In progress'; @@ -343,7 +345,7 @@ card.querySelector('.org-pill').textContent = 'Stopped'; card.querySelector('.org-field-err').textContent = current === 4 ? `${e.message} Open the organization and check Projects before creating the project; its outcome may be unknown.` : `${e.message} Open the organization to inspect and continue; do not repeat a step whose outcome is unknown.`; - if (current === 4) { editorDirty = false; $('org-new-id').value = ''; $('org-quick-open-org').hidden = false; } + if (current >= 4) { editorDirty = false; $('org-new-id').value = ''; $('org-quick-open-org').hidden = false; } card.classList.add('org-step-warn'); card.focus(); status('Setup stopped.'); await refreshList(); } diff --git a/packages/webui/src/public/projects.css b/packages/webui/src/public/projects.css index f1e907cd1..d1a045906 100644 --- a/packages/webui/src/public/projects.css +++ b/packages/webui/src/public/projects.css @@ -500,3 +500,6 @@ body:has(.chat-area .project-header):has(.project-chat) .breadcrumbs { margin-bo } /* A long Conversation title wraps beside Details instead of squeezing it. */ .project-header[data-project-conversation="true"] .project-actions { flex:none; } + +/* Keep the action in flow when a read error occupies the top of the page. */ +@media (min-width:700px) { .chat-area:has(.chat-error) .project-create:not([open]) { position:static; margin:12px 0; } } diff --git a/packages/webui/src/public/projects.js b/packages/webui/src/public/projects.js index c9b94d38b..fcf9b2a0c 100644 --- a/packages/webui/src/public/projects.js +++ b/packages/webui/src/public/projects.js @@ -177,7 +177,7 @@ } function filesView(data,project) { const f=filesData(data), docs=f.docs; - return `

    Reviewed deliveries ${f.reviewed.length}

    ${f.reviewed.length?f.reviewed.map(({r,file})=>`
    ${clean(file.name)} Reviewed

    Request ${clean(r.id)} · from ${clean(r.thread.name)} · Reviewed delivery. Not landed or deployed.

    Open shows plain text in a new tab. Downloaded HTML can be opened locally after saving.

    `).join(''):`

    ${data.disabled?'Files are unavailable.':data.failed?'Reviewed files are unavailable.':data.requests.length?'No reviewed file is available.':'No request files yet. Files appear when a request in this project produces them.'}

    `}

    Draft workspace ${f.drafts.length}

    Names only. Draft files may change and are not reviewed deliveries.

    ${f.drafts.length?f.drafts.map(({r,name})=>`
    ${clean(name)}Request ${clean(r.id)} · Draft
    `).join(''):data.failed || data.requests.some(r=>r.workspace?.available!==true || !Array.isArray(r.workspace.entries))?'

    Could not read draft workspace. Try again later.

    ':'

    No draft files found.

    '}${data.requests.some(r=>r.workspace?.truncated)?'

    The draft list was truncated.

    ':''}

    Project documents ${docs?`${docs.length}`:''}

    ${!project.repo?'No linked repository.':data.recordsMissing?'This project has no records yet. Initialize its record repository to add documents.':!docs?'Project documents unavailable. Docs could not read this project’s repository.':docs.length?docs.map(name=>`
    ${clean(name)}Open in Docs
    `).join(''):'No project documents found.'}
    `; + return `

    Reviewed deliveries ${f.reviewed.length}

    ${f.reviewed.length?f.reviewed.map(({r,file})=>`
    ${clean(file.name)} Reviewed

    Request ${clean(r.id)} · from ${clean(r.thread.name)} · Reviewed delivery. Not landed or deployed.

    Open shows plain text in a new tab. Downloaded HTML can be opened locally after saving.

    `).join(''):`

    ${data.disabled?'Files are unavailable.':data.failed?'Reviewed files are unavailable.':data.requests.length?'No reviewed file is available.':'No request files yet. Files appear when a request in this project produces them.'}

    `}

    Draft workspace ${f.drafts.length}

    Names only. Draft files may change and are not reviewed deliveries.

    ${f.drafts.length?f.drafts.map(({r,name})=>`
    ${clean(name)}Request ${clean(r.id)} · Draft
    `).join(''):data.failed || data.requests.some(r=>r.workspace?.available!==true || !Array.isArray(r.workspace.entries))?'

    Could not read draft workspace. Try again later.

    ':'

    No draft files found.

    '}${data.requests.some(r=>r.workspace?.truncated)?'

    The draft list was truncated.

    ':''}

    Project documents ${docs?`${docs.length}`:''}

    ${!project.repo?'No linked repository.':data.recordsMissing?window.MosaicRecords.markup(project.repo):!docs?'Project documents unavailable. Docs could not read this project’s repository.':docs.length?docs.map(name=>`
    ${clean(name)}Open in Docs
    `).join(''):'No project documents found.'}
    `; } const expandedPrds = new Set(); function requirementView(data,project,selected) { @@ -187,7 +187,7 @@ const candidate=d?.candidate, expanded=r && expandedPrds.has(project.id+':'+r.id); const docPath=candidate?.prd_path, docLink=project.repo && typeof docPath==='string' && /^docs\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.md$/.test(docPath) ? `#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent(docPath)}` : null; const rows=candidate ? [['PRD version',candidate.prd_version],['Approved snapshot',d.snapshot.id || 'None'],['PRD file',docPath],['PRD blob',candidate.prd_blob],['Records commit',candidate.records_commit],['Confirmed intent commit',candidate.spec_commit],['Mode revision',candidate.mode_revision]].map(([label,value])=>`
    ${label}${label==='PRD file' && docLink?`${clean(value)}`:`${clean(value)}`}
    `).join('') : '

    Unavailable until a PRD is read.

    '; - return `${r?`
    ${select || `Request ${clean(r.id)}`} · ${chip(r.state)} · from ${clean(r.thread.name)} Open conversation
    `:select}

    Project direction

    North star

    ${north!==null?`
    Open north star in Docs`:data.northRecordsMissing?'

    This project has no records yet. Initialize its record repository to add documents.

    ':data.northMissing?'

    No north star yet.

    ':project.repo?'

    North star unavailable. Docs could not read this project’s repository.

    ':`

    This project has no linked repository. The north star and project documents live in a repository. Linking one to an existing project isn't available yet.

    `}

    ${candidate?`PRD ${clean(candidate.prd_version)}`:'PRD'} ${candidate?`${d.snapshot.id?'Approved':'Draft'}`:''}

    ${d?`

    ${d.snapshot.id?'Approved snapshot '+clean(d.snapshot.id):'This candidate has no active approved snapshot.'}

    Requirements ${d.requirements.length}

    ${d.requirements.map((req,i)=>`
    ${clean(req.id)} · ${clean(req.title)}

    ${clean(req.text)}

    Requirement identity: ${clean(candidate.requirements[i]?.path)} · ${clean(candidate.requirements[i]?.blob)}

    `).join('')}
    `:`

    ${(data.failed || data.requests.some(x=>x.materialFailed))?'Request or PRD unavailable. Refresh to try again.':'No current PRD candidate or approved snapshot. Waiting for a PRD submission.'}

    `}${d && data.requests.some(x=>x.materialFailed)?'

    Some request PRDs could not be read. Refresh to try again.

    ':''}
    `; + return `${r?`
    ${select || `Request ${clean(r.id)}`} · ${chip(r.state)} · from ${clean(r.thread.name)} Open conversation
    `:select}

    Project direction

    North star

    ${north!==null?`
    Open north star in Docs`:data.northRecordsMissing?`

    ${window.MosaicRecords.markup(project.repo)}

    `:data.northMissing?'

    No north star yet.

    ':project.repo?'

    North star unavailable. Docs could not read this project’s repository.

    ':`

    This project has no linked repository. The north star and project documents live in a repository. Linking one to an existing project isn't available yet.

    `}

    ${candidate?`PRD ${clean(candidate.prd_version)}`:'PRD'} ${candidate?`${d.snapshot.id?'Approved':'Draft'}`:''}

    ${d?`

    ${d.snapshot.id?'Approved snapshot '+clean(d.snapshot.id):'This candidate has no active approved snapshot.'}

    Requirements ${d.requirements.length}

    ${d.requirements.map((req,i)=>`
    ${clean(req.id)} · ${clean(req.title)}

    ${clean(req.text)}

    Requirement identity: ${clean(candidate.requirements[i]?.path)} · ${clean(candidate.requirements[i]?.blob)}

    `).join('')}
    `:`

    ${(data.failed || data.requests.some(x=>x.materialFailed))?'Request or PRD unavailable. Refresh to try again.':'No current PRD candidate or approved snapshot. Waiting for a PRD submission.'}

    `}${d && data.requests.some(x=>x.materialFailed)?'

    Some request PRDs could not be read. Refresh to try again.

    ':''}
    `; } function overview(data,project,canSend,receipt='') { const active=data.requests.filter(r=>r.state && !ended(r.state)), waiting=active.filter(r=>needs(r.state)), ordered=[...data.requests].sort(requestOrder), first=ordered[0], threads=[...data.threads]; @@ -195,7 +195,7 @@ const f=filesData(data), filesKnown=!data.failed && !!f.docs && data.requests.every(r=>r.workspace?.available===true && Array.isArray(r.workspace.entries) && r.state), count=filesKnown?f.reviewed.length+f.drafts.length+f.docs.length:'–'; const n=typeof data.north?.content==='string'?data.north.content:null, candidate=ordered.find(r=>r.draft)?.draft; const metrics=[['Requests in progress',data.failed?'–':active.length,data.failed?'Not available yet':active[0]?label(active[0].state):'No active requests',first?conversationLink(first.thread):path(project.id,'conversations')],['Needs your input',data.failed?'–':waiting.length,data.failed?'Not available yet':waiting.length?label(waiting[0].state):'Nothing waiting',waiting[0]?conversationLink(waiting[0].thread):path(project.id,'conversations')],['Conversations',threads.length,'Project conversations',path(project.id,'conversations')],['Files',count,filesKnown?`${f.reviewed.length} reviewed · ${f.drafts.length} draft · ${f.docs.length} docs`:data.recordsMissing?'No project records yet':'Not available yet',path(project.id,'files')]]; - return `${waiting.length?`
    ${waiting.length} ${waiting.length===1?'decision needs':'decisions need'} your input. Review decision
    `:''}
    ${metrics.map(([title,value,caption,href])=>`${title}${value}${clean(caption)}`).join('')}

    Updated just now · Showing requests from recent messages.

    Current work

    ${canSend&&!project.archived?`${plusIcon}New conversation`:''}
    ${threads.length?threads.map((t,i)=>i===0?card(t,workFor(data,t),data.failed):`${clean(t.name)}With ${clean(t.instance)} · ${workFor(data,t) ? label(workFor(data,t).state) : data.failed ? 'Status unavailable' : 'No active request'}${workFor(data,t)?chip(workFor(data,t).state):''}`).join(''):'

    No conversations yet. Start one to begin work.

    '}

    Tasks ${taskRefs(data).length}

    ${taskRefs(data).length?taskRefs(data).slice(0,2).map(ref=>`
    ${taskLink(ref,data)}
    `).join(''):data.failed?'

    Request tasks unavailable. Refresh to try again.

    ':'

    No request tasks available.

    '}View all project tasks
    `; + return `${waiting.length?`
    ${waiting.length} ${waiting.length===1?'decision needs':'decisions need'} your input. Review decision
    `:''}
    ${metrics.map(([title,value,caption,href])=>`${title}${value}${clean(caption)}`).join('')}

    Updated just now · Showing requests from recent messages.

    Current work

    ${canSend&&!project.archived?`${plusIcon}New conversation`:''}
    ${threads.length?threads.map((t,i)=>i===0?card(t,workFor(data,t),data.failed):`${clean(t.name)}With ${clean(t.instance)} · ${workFor(data,t) ? label(workFor(data,t).state) : data.failed ? 'Status unavailable' : 'No active request'}${workFor(data,t)?chip(workFor(data,t).state):''}`).join(''):'

    No conversations yet. Start one to begin work.

    '}

    Tasks ${taskRefs(data).length}

    ${taskRefs(data).length?taskRefs(data).slice(0,2).map(ref=>`
    ${taskLink(ref,data)}
    `).join(''):data.failed?'

    Request tasks unavailable. Refresh to try again.

    ':'

    No request tasks available.

    '}View all project tasks
    `; } function tasksView(data) { const refs=taskRefs(data); diff --git a/packages/webui/src/serve.mjs b/packages/webui/src/serve.mjs index 9c2f1a714..897c89ead 100644 --- a/packages/webui/src/serve.mjs +++ b/packages/webui/src/serve.mjs @@ -720,7 +720,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF for (const registerRoutes of routes) registerRoutes(registered); registered.add('GET', '/api/themes', (req, res) => themesHTTP(req, res, { log }), { publicRead: true }); const adminRoute = (req, res, context) => orgAdminHTTP(req, res, { ...context, admin: orgAdmin ??= defaultOrgAdmin(), log }); - for (const path of ['/api/org-template', '/api/org-presets', '/api/org-validate', '/api/org-admin', /^\/api\/orgs\/[^/]+\/(?:admin|setup|delete|archive|restore)(?:\/(?:queue|bus|project\/[^/]+))?$/]) { + for (const path of ['/api/org-template', '/api/org-presets', '/api/org-validate', '/api/org-admin', /^\/api\/orgs\/[^/]+\/(?:admin|setup|delete|archive|restore)(?:\/(?:queue|bus|project\/[^/]+|records\/[^/]+))?$/]) { for (const method of ['GET', 'POST']) registered.add(method, path, adminRoute); } registered.add('POST', '/api/orgs', adminRoute); diff --git a/packages/webui/tests/org-admin.test.mjs b/packages/webui/tests/org-admin.test.mjs index b846a7138..5aa8ac772 100644 --- a/packages/webui/tests/org-admin.test.mjs +++ b/packages/webui/tests/org-admin.test.mjs @@ -150,7 +150,7 @@ test('writes keep the origin and CSRF fencing', async t => { const r = await c.call('POST', '/api/orgs', body, headers); assert.equal(r.status, status, JSON.stringify(headers)); } - for (const path of ['/api/orgs/acme/setup/queue', '/api/orgs/acme/setup/bus', '/api/orgs/acme/admin']) { + for (const path of ['/api/orgs/acme/setup/queue', '/api/orgs/acme/setup/bus', '/api/orgs/acme/setup/records/work', '/api/orgs/acme/admin']) { const r = await c.call('POST', path, {}, { 'sec-fetch-site': 'cross-site' }); assert.equal(r.status, 403); assert.equal(r.body.error, 'cross-site request refused'); } diff --git a/packages/webui/tests/org-quick-browser.test.mjs b/packages/webui/tests/org-quick-browser.test.mjs index 1937999f7..acbe43efc 100644 --- a/packages/webui/tests/org-quick-browser.test.mjs +++ b/packages/webui/tests/org-quick-browser.test.mjs @@ -52,9 +52,9 @@ for (const scenario of ['bus-refused', 'project-refused', 'project-unknown', 'su await wait('document.querySelector("#org-quick-open") && !document.querySelector("#org-paths").hidden'); if (scenario === 'project-refused' || scenario === 'project-unknown') await b.evaluate(`window.__projectPosts=0;const real=window.fetch;window.fetch=async(url,init={})=>{if(String(url)==='/api/orgs/alpha/chat/projects' && init.method==='POST'){window.__projectPosts++;${scenario === 'project-refused' ? "return new Response(JSON.stringify({error:'not-configured',message:'Project refused',sent:false}),{status:503,headers:{'content-type':'application/json'}});" : "await real(url,init);return new Response(JSON.stringify({error:'outcome-unknown',message:'Outcome unknown',sent:'unknown'}),{status:503,headers:{'content-type':'application/json'}});"}}return real(url,init)}`); await b.evaluate(`document.querySelector('#org-quick-open').click();document.querySelector('#org-risk-accept').click();document.querySelector('#org-quick-run').click()`); - const finalStep = scenario === 'bus-refused' ? 3 : 4, finalState = scenario === 'success' ? 'Done' : 'Stopped'; + const finalStep = scenario === 'bus-refused' ? 3 : scenario === 'success' ? 5 : 4, finalState = scenario === 'success' ? 'Done' : 'Stopped'; await wait(`document.querySelector('[data-quick-step="${finalStep}"] .org-pill')?.textContent === '${finalState}'`); - assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-quick-step] .org-pill")].map(e=>e.textContent)'), ['Done', 'Done', 'Done', scenario === 'bus-refused' ? 'Stopped' : 'Done', scenario === 'bus-refused' ? 'Not started' : finalState]); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-quick-step] .org-pill")].map(e=>e.textContent)'), ['Done', 'Done', 'Done', scenario === 'bus-refused' ? 'Stopped' : 'Done', scenario === 'bus-refused' ? 'Not started' : finalState, scenario === 'success' ? 'Done' : 'Not started']); if (scenario === 'bus-refused') { assert.match(await b.evaluate(`document.querySelector('[data-quick-step="3"]').textContent`), /bus refused/); assert.equal(await b.evaluate('document.activeElement.dataset.quickStep'), '3'); @@ -63,6 +63,12 @@ for (const scenario of ['bus-refused', 'project-refused', 'project-unknown', 'su 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.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'); if (scenario !== 'success') { diff --git a/packages/webui/tests/org-quick-live.test.mjs b/packages/webui/tests/org-quick-live.test.mjs index ce9275c2f..072435bd0 100644 --- a/packages/webui/tests/org-quick-live.test.mjs +++ b/packages/webui/tests/org-quick-live.test.mjs @@ -2,13 +2,15 @@ // instance whose fixture and Console are already running (see BUILD.md). import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { existsSync, readFileSync } from 'node:fs'; +import { existsSync, readFileSync, readdirSync } from 'node:fs'; +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; import { homedir } from 'node:os'; import { join } from 'node:path'; import { browser } from './browser.mjs'; const log = join(homedir(), 'orgdev-qconsole.log'); -test('Quick Setup starts the real fixture and a browser message gets its canned reply', { timeout: 150000, skip: !existsSync(log) && 'scratch fixture and Console are not running' }, async t => { +for (const scenario of ['fresh', 'recover', 'cli']) test(`Quick Setup real exchange and records: ${scenario}`, { timeout: 150000, skip: !existsSync(log) && 'scratch fixture and Console are not running' }, async t => { const url = /Mosaic Console: (http:\/\/127\.0\.0\.1:(\d+)\/)/.exec(readFileSync(log, 'utf8')); assert.ok(url, 'scratch Console advertised a URL'); assert.ok(![7332, 7340, 7341, 33223, 17450, 17443, 44307, 7350].includes(Number(url[2])), 'Console must use an allowed port'); @@ -31,17 +33,36 @@ test('Quick Setup starts the real fixture and a browser message gets its canned await click('#org-quick-open'); await wait('document.querySelector("#org-quick") && !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); + if (scenario !== 'fresh') await b.evaluate(`(() => { const real=window.fetch; let first=true; window.fetch=(url,opts={}) => { if(first && String(url).includes('/setup/records/') && opts.method==='POST') { first=false; return Promise.resolve(new Response(JSON.stringify({error:'test-stop',message:'Stopped for records recovery test'}),{status:409,headers:{'content-type':'application/json'}})); } return real(url,opts); }; })()`); await click('#org-risk-accept'); await click('#org-quick-run'); - await wait(`document.querySelector('[data-quick-step="4"] .org-pill')?.textContent === 'Done' || [...document.querySelectorAll('[data-quick-step] .org-pill')].some(e=>e.textContent==='Stopped')`, 90000); + await wait(`document.querySelector('[data-quick-step="5"] .org-pill')?.textContent === 'Done' || [...document.querySelectorAll('[data-quick-step] .org-pill')].some(e=>e.textContent==='Stopped')`, 90000); console.log('setup reached a terminal step'); const states = await b.evaluate('[...document.querySelectorAll("[data-quick-step] .org-pill")].map(e=>e.textContent)'); - assert.deepEqual(states, ['Done', 'Done', 'Done', 'Done', 'Done'], await b.evaluate('document.querySelector("#org-quick-steps").innerText')); + assert.deepEqual(states, ['Done', 'Done', 'Done', 'Done', 'Done', scenario === 'fresh' ? 'Done' : 'Stopped'], await b.evaluate('document.querySelector("#org-quick-steps").innerText')); assert.equal(await shown('#org-quick-open-org'), true, 'the finished organization can be opened'); await click('#org-quick-open-org'); console.log('opening organization'); await wait(`window.MosaicOrg?.id === ${JSON.stringify(id)} && document.querySelector('.project-card')?.textContent.includes('Repository: work')`, 30000); await click('.project-card'); await wait('location.hash.match(/\\/projects\\/[0-9a-f-]{36}/i)'); console.log('project created'); + if (scenario === 'recover') { + await wait(`document.querySelector('[data-record-init]')`); + await click('[data-record-init]'); + await wait(`!document.querySelector('[data-record-init]') && document.querySelector('[data-project-content]')?.textContent.includes('North star')`, 30000); + } else if (scenario === 'cli') { + const config = readdirSync(join(homedir(), '.config')).find(name => /^mosaic-[a-z][a-z0-9]{1,15}$/.test(name)); + assert.ok(config); + const uid = process.getuid(); + await promisify(execFile)('/mnt/storage/scratch/mosaic-lead/uidev/org-release/devstack.sh', ['exec', '--', 'scripts/mosaic', 'project', 'init', id, 'work'], { env: { + PATH: '/mnt/storage/scratch/tmp/q2KNlM/node-v26.12.1-linux-x64/bin:/opt/claude-code/bin:/usr/local/bin:/usr/bin:/bin', HOME: homedir(), TMPDIR: process.env.TMPDIR, LANG: 'C.UTF-8', MOSAIC_CONFIG: join(homedir(), '.config', config, 'config.json'), XDG_RUNTIME_DIR: `/run/user/${uid}`, DBUS_SESSION_BUS_ADDRESS: `unix:path=/run/user/${uid}/bus`, + } }); + await b.evaluate(`document.querySelector('#refresh').click()`); + } + await wait(`document.querySelector('[data-project-content]') && !document.querySelector('[data-project-content]').textContent.includes('Reading')`); + assert.doesNotMatch(await b.evaluate(`document.querySelector('[data-project-content]').textContent`), /no project records|no records yet/i); + const projectFiles = await b.evaluate(`fetch('/api/orgs/${id}/project-files?project=work').then(async r => ({ status:r.status, body:await r.json() }))`); + assert.equal(projectFiles.status, 200, JSON.stringify(projectFiles)); + assert.ok(projectFiles.body.files.some(f => f.path === 'spec/north-star.md')); const projectRoute = await b.evaluate('location.hash'); await b.evaluate(`location.hash=${JSON.stringify(projectRoute + '/conversations')}`); await wait('!!document.querySelector("#chat-thread-form")'); @@ -51,4 +72,6 @@ test('Quick Setup starts the real fixture and a browser message gets its canned await input('#chat-body', 'Reply with fixture word'); await click('#chat-send-form button[type=submit]'); await wait('document.querySelector(".chat-log")?.textContent.includes("PINEAPPLE")', 90000); assert.match(await b.evaluate('document.querySelector(".chat-log").textContent'), /PINEAPPLE/); console.log('fixture reply received'); + await wait(`document.querySelector('[data-conversation-request-status]') && (document.querySelector('.project-tabs a[href$="/tasks"] .project-count') || document.querySelector('[data-conversation-request-status]').textContent)`, 30000); + assert.doesNotMatch(await b.evaluate(`document.querySelector('[data-conversation-request-status]').textContent`), /unavailable/i); }); diff --git a/packages/webui/tests/org-request-status-browser.test.mjs b/packages/webui/tests/org-request-status-browser.test.mjs index fbfac55cb..33698e81d 100644 --- a/packages/webui/tests/org-request-status-browser.test.mjs +++ b/packages/webui/tests/org-request-status-browser.test.mjs @@ -128,3 +128,14 @@ test('an organization project overview reports no active request instead of unav assert.deepEqual(metrics, ['Requests in progress 0 No active requests', 'Needs your input 0 Nothing waiting']); assert.doesNotMatch(await b.evaluate(`document.querySelector('main').innerText`), /Status unavailable|Request status unavailable|Request tasks unavailable/); }); + +test('organization role instances reflow inside the viewport at 390 pixels', { timeout: 60000 }, async t => { + const { base, diagnostics } = await consoleFor(t); + const { b, wait } = await page(t, base, diagnostics); + await b.viewport(390, 844); + await b.navigate(`${base}#/orgs/alpha/settings/business`); + await wait(`document.querySelector('.s1-roles tbody tr')`, 'role instances'); + const box = await b.evaluate(`(()=>{const table=document.querySelector('.s1-roles'),wrap=table.closest('.table-wrap'),r=wrap.getBoundingClientRect();return {right:r.right,tableRight:table.getBoundingClientRect().right,document:document.documentElement.scrollWidth,viewport:innerWidth,overflow:getComputedStyle(wrap).overflowX,client:wrap.clientWidth,scroll:wrap.scrollWidth}})()`); + assert.ok(box.right <= box.viewport && box.document <= box.viewport, JSON.stringify(box)); + assert.ok(box.tableRight <= box.viewport, JSON.stringify(box)); assert.ok(box.scroll <= box.client, JSON.stringify(box)); +}); diff --git a/packages/webui/tests/org-switch-browser.test.mjs b/packages/webui/tests/org-switch-browser.test.mjs index 179977fc5..ab5d38ea2 100644 --- a/packages/webui/tests/org-switch-browser.test.mjs +++ b/packages/webui/tests/org-switch-browser.test.mjs @@ -252,3 +252,17 @@ test('organization creation draft survives Stay and is discarded on switch', asy await b.evaluate(`document.querySelector('[data-discard]').click()`).catch(() => {}); await wait('window.MosaicOrg?.id === "beta"'); }); + +test('a stopped organization bus has truthful chat guidance', async t => { + const organizations = { + list: async () => [{ id: 'alpha', label: 'Alpha', busHealthy: false }], + resolve: async () => ({ busHealthy: false, reads: { business: async () => ({ business: { id: 'alpha', projects: [] } }) }, bus: {}, chat: { projects: async () => [], threads: async () => [] } }), + }; + const server = await startServer({ port: 0, sso: createDevOwner(), organizations, send: async () => ({}), 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}/#/orgs/alpha/projects`); + await b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(document.querySelector('.chat-area')?.innerText.includes('The bus is stopped'))return;await new Promise(r=>setTimeout(r,30))}throw Error('stopped-bus guidance missing')})()`); + const text = await b.evaluate(`document.querySelector('.chat-area').innerText`); + assert.match(text, /bus is stopped.*Start the bus/i); + assert.doesNotMatch(text, /This Console only reads/); +}); diff --git a/packages/webui/tests/s7-fidelity-browser.test.mjs b/packages/webui/tests/s7-fidelity-browser.test.mjs index 38263be9b..830385bd3 100644 --- a/packages/webui/tests/s7-fidelity-browser.test.mjs +++ b/packages/webui/tests/s7-fidelity-browser.test.mjs @@ -72,7 +72,7 @@ test('sidebar child labels truncate and mobile business role names remain whole' await b.viewport(390,900); await b.evaluate(`window.fetch=((old)=>(url,init)=>String(url)==='/api/business'?Promise.resolve(new Response(JSON.stringify({business:{id:'demo',instances:[{instance:'assistant',definition:'assistant'}]}}),{headers:{'content-type':'application/json'}})):old(url,init))(window.fetch);location.hash='#/settings/business'`); await wait(`document.querySelector('.s1-roles tbody th')`); const role=await b.evaluate(`(()=>{const e=document.querySelector('.s1-roles tbody th'),s=getComputedStyle(e),r=e.getBoundingClientRect();return {wrap:s.overflowWrap,word:s.wordBreak,width:r.width,scroll:e.scrollWidth}})()`); - assert.equal(role.wrap,'normal'); assert.equal(role.word,'normal'); assert.ok(role.width>=role.scroll,JSON.stringify(role)); + assert.equal(role.wrap,'anywhere'); assert.equal(role.word,'normal'); assert.ok(role.width>=role.scroll,JSON.stringify(role)); }); const staleFixture = `;{const old=window.fetch;window.instancesFail=false;window.fetch=(url,init)=>{const p=String(url),json=(v,status=200)=>Promise.resolve(new Response(JSON.stringify(v),{status,headers:{'content-type':'application/json'}}));if(p==='/api/bus/agents')return json({rows:[{role:'chief',holder_run:'r-old-chief-123456',harness:'pi',at:'2026-01-01T00:00:00Z',state:'idle'}]});if(p==='/api/bus/thread.claims')return json({rows:[{thread:'${T}',holder_run:'r-old-chief-123456',harness:'pi',at:'2026-01-01T00:00:00Z'}]});if(p==='/api/bus/instances')return window.instancesFail?json({error:'unavailable'},503):json({rows:[{instances:{chief:{running:['r-new-chief-654321']}}}]});return old(url,init)}}`; @@ -105,3 +105,61 @@ test('desktop agent message matches avatar and card geometry',async t=>{ const x=await b.evaluate(`(()=>{const m=document.querySelector('.chat-message-agent'),a=m.querySelector('.chat-avatar'),name=m.querySelector('strong'),bubble=m.querySelector('.chat-body').getBoundingClientRect(),card=document.querySelector('.project-request-item .request-mount').getBoundingClientRect(),s=getComputedStyle(a);return {font:s.fontSize,weight:s.fontWeight,name:name.getBoundingClientRect().left,left:bubble.left,right:bubble.right,width:bubble.width,cardRight:card.right}})()`); assert.equal(x.font,'14px');assert.equal(x.weight,'700');assert.ok(Math.abs(x.name-296)<1,JSON.stringify(x));assert.ok(Math.abs(x.left-296)<1&&Math.abs(x.width-744)<1&&Math.abs(x.right-x.cardRight)<1,JSON.stringify(x)); }); + +test('role instances reflow within the mobile panel', async t => { + const {b,wait}=await setup(t,'/settings/business'); + await b.viewport(390,844); + await b.evaluate(`window.fetch=((old)=>(url,init)=>String(url)==='/api/business'?Promise.resolve(new Response(JSON.stringify({business:{id:'demo',instances:[{instance:'assistant',definition:'assistant'}]}}),{headers:{'content-type':'application/json'}})):old(url,init))(window.fetch);document.querySelector('#refresh').click()`); + await wait(`document.querySelector('.s1-roles tbody th')`); + const x=await b.evaluate(`(()=>{const t=document.querySelector('.s1-roles'),w=t.closest('.table-wrap'),r=w.getBoundingClientRect();return {right:r.right,tableRight:t.getBoundingClientRect().right,viewport:innerWidth,overflow:getComputedStyle(w).overflowX,scroll:w.scrollWidth,client:w.clientWidth,document:document.documentElement.scrollWidth}})()`); + assert.ok(x.right<=x.viewport,JSON.stringify(x)); + assert.match(x.overflow,/auto|scroll/); assert.ok(x.tableRight<=x.viewport && x.scroll<=x.client,JSON.stringify(x)); assert.ok(x.document<=x.viewport,JSON.stringify(x)); +}); + +test('an archived organization read disables a retained conversation draft', async t => { + const {b,wait}=await setup(t,'/projects/threads/'+T); + await wait(`document.querySelector('#chat-body') && !document.querySelector('#chat-body').disabled`); + await b.evaluate(`document.querySelector('#chat-body').value='Keep this draft';document.querySelector('#chat-body').dispatchEvent(new Event('input',{bubbles:true}));window.fetch=((old)=>(url,init)=>String(url)==='/api/chat/projects'?Promise.resolve(new Response(JSON.stringify({error:'org-archived'}),{status:409,headers:{'content-type':'application/json'}})):old(url,init))(window.fetch);document.querySelector('#refresh').click()`); + await wait(`document.querySelector('.chat-error')`); + assert.equal(await b.evaluate(`document.querySelector('#chat-body').disabled`),true); + assert.equal(await b.evaluate(`document.querySelector('#chat-body').value`),'Keep this draft'); + assert.match(await b.evaluate(`document.querySelector('.chat-area').innerText`),/organization.*archived/i); +}); + +test('a room-not-open read disables a retained draft with the room reason', async t => { + const {b,wait}=await setup(t,'/projects/threads/'+T); + await wait(`document.querySelector('#chat-body') && !document.querySelector('#chat-body').disabled`); + await b.evaluate(`document.querySelector('#chat-body').value='Keep this draft';document.querySelector('#chat-body').dispatchEvent(new Event('input',{bubbles:true}));window.fetch=((old)=>(url,init)=>String(url)==='/api/chat/projects'?Promise.resolve(new Response(JSON.stringify({error:'room-not-open'}),{status:409,headers:{'content-type':'application/json'}})):old(url,init))(window.fetch);document.querySelector('#refresh').click()`); + await wait(`document.querySelector('.chat-error')`); + assert.equal(await b.evaluate(`document.querySelector('#chat-body').disabled`),true); + assert.equal(await b.evaluate(`document.querySelector('#chat-body').value`),'Keep this draft'); + const text=await b.evaluate(`document.querySelector('.chat-area').innerText`); + assert.match(text,/room.*not open/i); assert.doesNotMatch(text,/organization is archived/i); +}); + +test('project read error banner does not overlap New project at desktop width', async t => { + const {b,wait}=await setup(t,'/projects',`;reviewFail['/api/chat/projects']=true;`); + await wait(`document.querySelector('.chat-error') && document.querySelector('.project-create summary')`); + const x=await b.evaluate(`(()=>{const a=document.querySelector('.chat-error').getBoundingClientRect(),b=document.querySelector('.project-create summary').getBoundingClientRect();return {overlap:a.leftb.left&&a.topb.top}})()`); + assert.equal(x.overlap,false); +}); + +test('a refused queue read keeps Queue as the page heading', async t => { + const extra=`;{const old=window.fetch;window.fetch=(url,init)=>String(url)==='/api/queue'?Promise.resolve(new Response(JSON.stringify({error:'queue-refused',message:'fixture refusal'}),{status:503,headers:{'content-type':'application/json'}})):old(url,init)}`; + const {b,wait}=await setup(t,'/queue',extra); + await wait(`document.querySelector('#bus-view [role=alert]')`); + assert.equal(await b.evaluate(`document.querySelector('#bus-view h1').textContent`),'Queue'); + assert.match(await b.evaluate(`document.querySelector('#bus-view [role=alert]').innerText`),/queue refused the read/i); +}); + +test('sidebar sprite is requested again after a failed read and recovery', async t => { + const {b,wait}=await setup(t,'/projects'); + await wait(`document.querySelector('#sections use[href*="icons.svg"]')`); + const before = await b.evaluate(`document.querySelector('#sections use[href*="icons.svg"]').getAttribute('href')`); + await b.evaluate(`reviewFail['/api/chat/projects']=true;document.querySelector('#refresh').click()`); + await wait(`document.querySelector('.chat-error')`); + await b.evaluate(`reviewFail['/api/chat/projects']=false;document.querySelector('#refresh').click()`); + await wait(`!document.querySelector('.chat-error') && document.querySelector('#sections use[href*="?retry="]')`); + const after = await b.evaluate(`document.querySelector('#sections use[href*="icons.svg"]').getAttribute('href')`); + assert.notEqual(after,before); +});