From 68fd66903bd14024db035cb7d8d13caebd4304f3 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Tue, 10 Nov 2026 13:03:45 -0600 Subject: [PATCH] feat(webui): U3 dashboard, projects and inbox across organizations (#1873) In organization mode #/ is the cross-organization dashboard (sample 02), #/projects lists every organization's projects with sort, filters and the shared By org / Flat grouping (sample 04), and #/inbox lists decisions across organizations with per-organization decide paths and terminal commands carrying --org and the full id (sample 05). The per-organization board moves to #/board and the organization's own project list to #/chat, which keeps the project surface. Reads go through workspace-data.js; a read an organization could not make says not read, never zero. Polling repaints in place and keeps focus, caret and scroll. --- packages/webui/src/public/bus.js | 43 ++- packages/webui/src/public/chat.js | 4 +- packages/webui/src/public/display.js | 2 +- packages/webui/src/public/org-create.js | 2 +- packages/webui/src/public/shell.css | 148 ++++++++ packages/webui/src/public/workspace-data.js | 14 +- packages/webui/src/public/workspace.js | 336 +++++++++++++++++- .../webui/tests/org-lan-bind-browser.test.mjs | 2 +- .../tests/org-list-refresh-browser.test.mjs | 4 +- packages/webui/tests/org-release-browser.mjs | 2 +- .../tests/org-request-status-browser.test.mjs | 2 +- .../webui/tests/org-switch-browser.test.mjs | 4 +- .../tests/unified-workspace-browser.test.mjs | 3 +- .../tests/workspace-pages-browser.test.mjs | 310 ++++++++++++++++ 14 files changed, 850 insertions(+), 26 deletions(-) create mode 100644 packages/webui/tests/workspace-pages-browser.test.mjs diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index a1e5b4bf9..38be6611f 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -717,7 +717,7 @@

Held roles ${claims.length}

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.

${claims.length ? `
${['Role', 'State', 'Attention', 'Holder', 'Harness', 'Held since'].map(h => ``).join('')}${rows}
${h}
` : empty('No role is held right now.', 'A role shows here while a run holds its claim on the bus.')}
${threadSection} -

Board seats stay on the control board. This view is about roles.

`; +

Board seats stay on the control board. This view is about roles.

`; } // ---------------------------------------------------------------- queue, business, settings @@ -1391,7 +1391,7 @@ }); // Not found and states - function notFound(why) { return `${head('Not found')}
${why || 'No page at this address.'}

Nothing is at ${txt(location.hash || '#/')}. Go to the Board or press Ctrl K to search.

`; } + function notFound(why) { return `${head('Not found')}
${why || 'No page at this address.'}

Nothing is at ${txt(location.hash || '#/')}. Go to the ${window.MosaicOrg ? 'Dashboard' : 'Board'} or press Ctrl K to search.

`; } const loadingView = (source = null) => `${head('Reading…')}
${source ? `Reading the ${esc(source.toLowerCase())}.` : 'Reading from the bus.'}
`; const retry = '
'; // Why a read failed, in words, with the bus code as given. Never a path or a guess. @@ -1452,9 +1452,11 @@ const parts = path.split('/').filter(Boolean).map(p => { try { return decodeURIComponent(p); } catch { return null; } }); if (parts.includes(null)) return notFound(); const [a, b, c] = parts, n = parts.length; + if (n === 0 && window.MosaicOrg) return window.MosaicWorkspace.home(); + if (a === 'projects' && n === 1 && window.MosaicOrg) return window.MosaicWorkspace.projectsPage(q); if (a === 'organization' && n === 1 && window.MosaicOrg) return window.MosaicWorkspace.dashboard(); if (a === 'side-by-side' && n === 1 && window.MosaicOrg) return `${head('Side by side', 'Not built yet.')}${empty('Side by side is not built yet.', 'It arrives with a later unified workspace update. Projects and Agents work today.')}`; - if (a === 'inbox' && n === 1 && window.MosaicOrg) return inboxView(get).then(html => afterHead(html, 'The inbox across all organizations is not built yet. This is the selected organization\'s inbox.')); + if (a === 'inbox' && n === 1 && window.MosaicOrg) return window.MosaicWorkspace.inboxPage(q); if (a === 'tasks' && n === 1 && window.MosaicOrg) return tasksView(get).then(html => afterHead(html, 'Tasks across all organizations are not built yet. These are the selected organization\'s tasks.')); if (a === 'inbox' && n === 1) return inboxView(get); if (a === 'inbox' && n === 2) return SAFE.test(b) ? decisionView(get, b, current) : notFound(`${txt(b)} is not a decision id.`); @@ -1475,7 +1477,9 @@ let gen = 0, shown = null, timer, proxyCleanup=null, orgCleanup=null; const paused = () => $('pause')?.getAttribute('aria-pressed') === 'true'; // A file open in the editor is never refreshed from under its draft; Reload is the person's to press. - function schedule() { clearTimeout(timer); if (!paused() && !out() && !routeOf().startsWith('/docs/')) timer = setTimeout(() => render(false), 10000); } + // The cross-organization pages (U3) poll at the workspace read's pollMs. + const wsPage = path => !!window.MosaicOrg && (path === '/' || path === '' || path === '/projects' || path === '/inbox'); + function schedule() { clearTimeout(timer); if (!paused() && !out() && !routeOf().startsWith('/docs/')) timer = setTimeout(() => render(false), wsPage(routeOf().split('?')[0]) ? window.MosaicWorkspace?.pollMs || 10000 : 10000); } // Keep focus, open
and the copy status across a refresh of the same page. // In the send form, the focused field and its caret too (its values come from `draft`). function keep() { @@ -1489,6 +1493,7 @@ field: view.contains(a) ? a.dataset?.field : null, caret: view.contains(a) && typeof a.selectionStart === 'number' ? [a.selectionStart, a.selectionEnd, a.scrollTop] : null, send: view.contains(a) && a.hasAttribute?.('data-send'), decide: view.contains(a) ? a.dataset?.decide ?? (a.id === 'decide-status' ? 'status' : null) : null, open: [...view.querySelectorAll('details[id]')].filter(d => d.open).map(d => d.id), status: $('copy-status')?.textContent || '', + scroll: [document.scrollingElement?.scrollTop ?? 0, $('main').scrollTop, [...view.querySelectorAll('.ws-tbl, .ws-insp')].map(e => [e.scrollLeft, e.scrollTop])], }; } function restore(k) { @@ -1502,7 +1507,7 @@ const setting=k.settingsField && [...$('bus-view').querySelectorAll('[data-instance-field],[data-assistant-field],[data-route],[data-setting]')].find(e=>e.dataset[k.settingsField.key]===k.settingsField.value && (!k.settingsField.form || e.closest('form')?.id===k.settingsField.form) && (!k.settingsField.instance || e.closest('[data-instance]')?.dataset.instance===k.settingsField.instance)); // The workspace screens mark their controls with data-focus-key: several Open links share an href. const keyed = k.focusKey ? $('bus-view').querySelector(k.focusKey === 'bus-restart' ? '[data-bus-restart]' : `[data-focus-key="${CSS.escape(k.focusKey)}"]`) : null; - if (keyed) keyed.focus({ preventScroll: true }); + if (keyed) { keyed.focus({ preventScroll: true }); if (k.caret && keyed.tagName === 'INPUT' && typeof keyed.setSelectionRange === 'function') try { keyed.setSelectionRange(k.caret[0], k.caret[1]); } catch {} } else if (setting) { setting.focus({preventScroll:true}); if(k.caret && typeof setting.setSelectionRange==='function'){setting.setSelectionRange(k.caret[0],k.caret[1]);setting.scrollTop=k.caret[2];} } else if (choice) choice.focus({preventScroll:true}); else if (dec) dec.focus({ preventScroll: true }); @@ -1511,23 +1516,35 @@ if (k.caret && el.tagName === 'TEXTAREA') { el.setSelectionRange(k.caret[0], k.caret[1]); el.scrollTop = k.caret[2]; } } else if (k.h1) $('bus-view').querySelector('h1')?.focus({ preventScroll: true }); + // A repaint replaces the tables: put their horizontal scroll and the page's back. + if (k.scroll) { + const [top, main, inner] = k.scroll; + [...$('bus-view').querySelectorAll('.ws-tbl, .ws-insp')].forEach((e, i) => { if (inner[i]) { e.scrollLeft = inner[i][0]; e.scrollTop = inner[i][1]; } }); + if (document.scrollingElement && document.scrollingElement.scrollTop !== top) document.scrollingElement.scrollTop = top; + if ($('main').scrollTop !== main) $('main').scrollTop = main; + } } async function render(navigated, opts = {}) { // A refresh due while this render reads would replace it: a navigation would lose its heading focus. clearTimeout(timer); if (out()) return; - const route = routeOf(), [path, query = ''] = route.split('?'), board = path === '/' || path === '' || path === '/board'; + const route = routeOf(), [path, query = ''] = route.split('?'), board = window.MosaicOrg ? path === '/board' : path === '/' || path === '' || path === '/board'; + // On the cross-organization pages a filter or selection changes only the query: that is a + // repaint of the same page, not a navigation (no loading view, focus and scroll kept). + const samePage = wsPage(path) && typeof shown === 'string' && shown.split('?')[0] === path; if (path !== '/settings/model-proxy' && proxyCleanup) {proxyCleanup();proxyCleanup=null;} if ((navigated || path !== '/settings/organizations') && orgCleanup) {orgCleanup();orgCleanup=null;} // Leaving a decision discards its confirmation immediately, including a preview in flight. if (answer && (navigated || path !== `/inbox/${answer.id}`)) answer = null; const g = ++gen, routeVersion = routesEditVersion; const current = () => g === gen && route === routeOf() && !out(); + // In organization mode #/ is the cross-organization dashboard; the processing controls stay on the board. + if (window.MosaicOrg) for (const id of ['processing-link', 'mobile-processing-link']) if ($(id) && $(id).getAttribute('href') !== '#/board') $(id).setAttribute('href', '#/board'); document.body.classList.toggle('on-bus', !board); $('bus-view').hidden = board; sections(path); document.querySelectorAll('.rail a').forEach(a => { const target = a.getAttribute('href').slice(1); const active = target === '/projects' ? /^\/(projects|chat)(\/|$)/.test(path) : target === '/' ? path === '/' : path === target; if (active) a.setAttribute('aria-current', 'page'); else a.removeAttribute('aria-current'); }); - const chatPath = path === '/projects' ? '/chat' : /^\/projects\/(threads|rooms)\//.test(path) ? '/chat' + path.slice('/projects'.length) : /^\/projects\/[^/]+$/.test(path) ? '/chat/projects/' + path.slice('/projects/'.length) : path; + const chatPath = path === '/projects' && !window.MosaicOrg ? '/chat' : /^\/projects\/(threads|rooms)\//.test(path) ? '/chat' + path.slice('/projects'.length) : /^\/projects\/[^/]+$/.test(path) ? '/chat/projects/' + path.slice('/projects/'.length) : path; window.MosaicChat?.leave(chatPath); if (path === '/business') { location.replace('#/settings/business'); return; } if (path === '/settings/display') { location.replace('#/settings/appearance'); return; } @@ -1597,11 +1614,11 @@ if (path === '/settings/model-proxy' && shown === route && !navigated) return; if (path === '/settings/organizations' && shown?.split('?')[0] === path && !navigated) return; if (($('agent-dialog')?.open || document.querySelector('.agent-more[aria-expanded=true]')) && !navigated) { schedule(); return; } - if (navigated || shown !== route) { unmountEditor(); $('bus-view').innerHTML = loadingView(SOURCES[path.split('/')[1]]); } + if (navigated || (shown !== route && !samePage)) { unmountEditor(); $('bus-view').innerHTML = loadingView(SOURCES[path.split('/')[1]]); } let html, state = 'fresh'; const live = reader(true); try { - if (path !== '/organization' && !(path === '/agents' && window.MosaicOrg) && path !== '/messages' && !['/settings','/settings/appearance','/settings/model-proxy','/settings/organizations'].includes(path)) { + if (path !== '/organization' && !wsPage(path) && !(path === '/agents' && window.MosaicOrg) && path !== '/messages' && !['/settings','/settings/appearance','/settings/model-proxy','/settings/organizations'].includes(path)) { try { await live('messages'); } catch (err) { messageCount = null; if (err.status === 403 || err.code === 'signed-out') throw err; } } @@ -1617,7 +1634,7 @@ freshBus(state, SOURCES[path.split('/')[1]]); // A route edit after the markup was prepared must win over that pending redraw. if(path==='/settings/routing' && routeVersion!==routesEditVersion){render(false);return;} - const k = !navigated && shown === route ? keep() : null; + const k = !navigated && (shown === route || samePage) ? keep() : null; unmountEditor(); $('bus-view').innerHTML = html; shown = route; syncAppearance(true); @@ -1800,10 +1817,14 @@ } if (!canSend && !isTester && !ssoOn) return; const path = routeOf().split('?')[0]; - if (path.startsWith('/chat')||path.startsWith('/projects')||path.startsWith('/inbox')||path.startsWith('/settings')||path.startsWith('/docs/')) render(false); else if (path === '/' || path === '') paintHeld(heldErr); + if (path.startsWith('/chat')||path.startsWith('/projects')||path.startsWith('/inbox')||path.startsWith('/settings')||path.startsWith('/docs/')||wsPage(path)) render(false); else if (window.MosaicOrg ? path === '/board' : path === '/' || path === '') paintHeld(heldErr); }; configRead = fetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => { if (r.type === 'opaqueredirect') { signOut(); return null; } return r.json(); }).then(applyConfig).catch(() => {}); document.addEventListener('mosaic-config', e => { if (e.detail && typeof e.detail === 'object') applyConfig(e.detail); }); + // The cross-organization pages ask for a repaint after a filter, sort or selection change, + // and report the inbox count across organizations for the sidebar. + document.addEventListener('mosaic-workspace-render', () => { if (wsPage(routeOf().split('?')[0])) render(false); }); + document.addEventListener('mosaic-workspace-inbox', e => { const d = e.detail; if (d && Number.isFinite(d.open)) { inboxCount = { open: d.open, blocking: Number.isFinite(d.blocking) ? d.blocking : 0 }; sections(routeOf().split('?')[0]); } }); // This context comes from the conversations renderer after its authorized read. let projectContext = null; document.addEventListener('mosaic-project-context', event => { diff --git a/packages/webui/src/public/chat.js b/packages/webui/src/public/chat.js index 3c6816221..6acbe74a6 100644 --- a/packages/webui/src/public/chat.js +++ b/packages/webui/src/public/chat.js @@ -99,7 +99,9 @@ } return data; } - const legacyRoute = () => (window.MosaicOrg?.route() ?? location.hash.slice(1)).startsWith('/chat'); + // In organization mode #/projects is the cross-organization page, so the organization's own + // project list lives at #/chat. That list keeps the project surface and its #/projects links. + const legacyRoute = () => { const r = window.MosaicOrg?.route() ?? location.hash.slice(1); return r.startsWith('/chat') && !(window.MosaicOrg && r.split('?')[0] === '/chat'); }; const projectPath = id => legacyRoute() ? `#/chat/projects/${id}` : `#/projects/${id}`; const threadPath = id => legacyRoute() ? `#/chat/threads/${id}` : `#/projects/threads/${id}`; const roomPath = id => legacyRoute() ? `#/chat/rooms/${id}` : `#/projects/rooms/${id}`; diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index 691346f0f..97e382c49 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -34,7 +34,7 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( } const route = () => location.hash.replace(/^#\/orgs\/[^/]+/, '') || '/'; window.fetch = (input, init) => { - if (typeof input === 'string' && input.startsWith('/api/') && !/^\/api\/(?:orgs(?:\/|$)|themes(?:\?|$)|org-template(?:\?|$)|org-presets(?:\?|$)|org-admin(?:\?|$)|org-validate(?:\?|$)|agents\/levels(?:\?|$))/.test(input)) + if (typeof input === 'string' && input.startsWith('/api/') && !/^\/api\/(?:orgs(?:\/|$)|themes(?:\?|$)|org-template(?:\?|$)|org-presets(?:\?|$)|org-admin(?:\?|$)|org-validate(?:\?|$)|workspace(?:\?|$)|agents\/levels(?:\?|$))/.test(input)) input = `/api/orgs/${id}/${input.slice('/api/'.length)}`; return nativeFetch(input, init); }; diff --git a/packages/webui/src/public/org-create.js b/packages/webui/src/public/org-create.js index d3554f4e2..bd454aecb 100644 --- a/packages/webui/src/public/org-create.js +++ b/packages/webui/src/public/org-create.js @@ -628,7 +628,7 @@ [$('org-quick-run'), 'click', quickRun], // F2: the interview opens a conversation with the assistant; Open organization skips it. [$('org-quick-interview'), 'click', async () => { const b = $('org-quick-interview'); b.disabled = true; if (!await window.MosaicOnboarding?.start({ ...quickDone, status })) b.disabled = false; }], - [$('org-quick-open-org'), 'click', () => { history.replaceState(null, '', `#/orgs/${encodeURIComponent(st.id)}/projects`); location.reload(); }], + [$('org-quick-open-org'), 'click', () => { history.replaceState(null, '', `#/orgs/${encodeURIComponent(st.id)}/chat`); location.reload(); }], [$('org-open-form'), 'submit', e => { e.preventDefault(); const id = $('org-open-id').value; if (id) openExisting(id); }], [$('org-form'), 'submit', save], [$('org-form'), 'input', onFormInput], diff --git a/packages/webui/src/public/shell.css b/packages/webui/src/public/shell.css index 9c15d445b..25df2cb58 100644 --- a/packages/webui/src/public/shell.css +++ b/packages/webui/src/public/shell.css @@ -538,6 +538,139 @@ html[data-organizations] .ws-off{display:block;margin-top:4px} html[data-organizations] .ws-rules .ws-lvl{margin-right:0} html[data-organizations] .ws-scope{margin:-8px 0 14px} +/* Across organizations (U3): the main dashboard, projects and inbox, samples 02, 04 and 05. */ +body:has([data-ws-home]) #breadcrumbs,body:has([data-ws-projects]) #breadcrumbs,body:has([data-ws-inbox]) #breadcrumbs{display:none} +html[data-organizations] .ws-edge{box-shadow:inset 3px 0 0 var(--org)} +html[data-organizations] .ws-orgref{display:inline-flex;align-items:center;gap:6px;white-space:nowrap;color:var(--strong);font-weight:600} +html[data-organizations] .ws-chip{display:inline-flex;align-items:center;gap:5px;font-size:12px;font-weight:600;padding:1px 7px;border-radius:4px;background:var(--raised);color:var(--strong);white-space:nowrap;line-height:1.5} +html[data-organizations] .ws-chip.gated{background:color-mix(in srgb,var(--danger) 14%,var(--surface));color:var(--danger)} +html[data-organizations] .ws-chip.block{background:var(--danger);color:var(--surface)} +html[data-organizations] .ws-chip.outline{background:none;box-shadow:inset 0 0 0 1px var(--line);color:var(--text);font-family:var(--mono);font-weight:500;font-size:11.5px} +html[data-organizations] .ws-dot.s-ok{color:var(--success)} +html[data-organizations] .ws-tbl .ws-dot,html[data-organizations] .ws-sess .ws-dot{color:var(--text)} +html[data-organizations] .ws-tbl .ws-dot.s-working b,html[data-organizations] .ws-tbl .ws-dot.s-ok b{color:var(--success)} +html[data-organizations] .ws-tbl .ws-dot.s-waiting b{color:var(--warning)} +html[data-organizations] .ws-tbl .ws-dot.s-error b{color:var(--danger)} +html[data-organizations] .ws-tbl .ws-dot.s-idle b,html[data-organizations] .ws-tbl .ws-dot.s-offline b{color:var(--muted)} +html[data-organizations] .ws-g5{display:grid;gap:10px;grid-template-columns:repeat(5,minmax(0,1fr))} +html[data-organizations] .ws-tile .ws-big{font-size:24px;font-weight:800;color:var(--strong);letter-spacing:-.02em;font-variant-numeric:tabular-nums;line-height:1.1} +html[data-organizations] .ws-tile .ws-big small{font-size:13px;font-weight:600;color:var(--muted);letter-spacing:0;margin-left:4px} +html[data-organizations] .ws-tile .ws-delta{font-size:12px;color:var(--muted)} +html[data-organizations] .ws-tile .ws-delta b{color:var(--success);font-weight:600} +html[data-organizations] .ws-tile.quiet{border-style:dashed;background:transparent} +html[data-organizations] .ws-bar{display:flex;height:6px;border-radius:3px;overflow:hidden;background:var(--raised);gap:2px} +html[data-organizations] .ws-bar i{display:block;background:var(--org,var(--action))} +html[data-organizations] .ws-by{display:flex;flex-wrap:wrap;gap:4px 10px;font-size:12px;color:var(--text)} +html[data-organizations] .ws-by>span{display:inline-flex;align-items:center;gap:4px;white-space:nowrap;font-variant-numeric:tabular-nums} +html[data-organizations] .ws-by .ws-av{width:14px;height:14px;border-radius:3px;font-size:7px} +html[data-organizations] .ws-orgcards{list-style:none;margin:0;padding:0;display:grid;gap:8px;grid-template-columns:repeat(auto-fill,minmax(220px,1fr))} +html[data-organizations] .ws-orgcard a{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:2px 10px;align-items:center;padding:9px 12px;border:1px solid var(--line);border-radius:8px;background:var(--surface);box-shadow:inset 3px 0 0 var(--org);color:var(--text);text-decoration:none;font-size:13px;height:100%} +html[data-organizations] .ws-orgcard a:hover{background:var(--raised)} +html[data-organizations] .ws-orgcard .ws-av{grid-row:1/3} +html[data-organizations] .ws-orgcard .nm{font-weight:700;color:var(--strong);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +html[data-organizations] .ws-orgcard .ws-dot{grid-column:2;grid-row:2;font-size:12.5px;color:var(--text)} +html[data-organizations] .ws-orgcard .ws-dot.s-working b{color:var(--success)} +html[data-organizations] .ws-orgcard .ws-dot.s-waiting b{color:var(--warning)} +html[data-organizations] .ws-orgcard .ws-dot.s-error b{color:var(--danger)} +html[data-organizations] .ws-orgcard .at{grid-column:3;grid-row:1;font:500 11.5px var(--mono);color:var(--muted)} +html[data-organizations] .ws-orgcard .why{grid-column:1/-1;font-size:12px;color:var(--muted)} +html[data-organizations] .ws-orgcard.off a{border-style:dashed} +html[data-organizations] .ws-home-split{margin-top:4px} +html[data-organizations] .ws-trail{list-style:none;margin:0;padding:0;border:1px solid var(--line);border-radius:8px;background:var(--surface)} +html[data-organizations] .ws-trail li{display:grid;grid-template-columns:48px 20px minmax(0,1fr);gap:10px;padding:7px 12px;border-bottom:1px solid color-mix(in srgb,var(--line) 60%,transparent);font-size:13px;align-items:center} +html[data-organizations] .ws-trail li:last-child{border-bottom:0} +html[data-organizations] .ws-trail time{font-family:var(--mono);font-size:12px;color:var(--muted)} +html[data-organizations] .ws-trail .what{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +html[data-organizations] .ws-trail .what a{color:var(--strong);text-decoration:none} +html[data-organizations] .ws-trail .what a:hover{text-decoration:underline} +html[data-organizations] .ws-trail .what b{font-weight:600} +html[data-organizations] .ws-trail .src{color:var(--muted)} +html[data-organizations] .ws-states{display:grid;gap:8px} +html[data-organizations] .ws-srow{display:grid;grid-template-columns:112px 24px minmax(0,1fr) auto;gap:10px;align-items:center;font-size:13px} +html[data-organizations] .ws-srow .sl{color:var(--strong);font-weight:600} +html[data-organizations] .ws-srow .sn{font:700 13px var(--mono);color:var(--strong);text-align:right} +html[data-organizations] .ws-srow .ws-bar{height:8px;max-width:100%} +html[data-organizations] .ws-needs{list-style:none;margin:0;padding:0;display:grid;gap:8px} +html[data-organizations] .ws-needs li{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:4px 10px;align-items:center;background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:9px 12px} +html[data-organizations] .ws-needs li>.ws-av{grid-row:1/3} +html[data-organizations] .ws-needs .q{color:var(--strong);font-weight:600;font-size:13.5px;text-decoration:none} +html[data-organizations] .ws-needs .q:hover{text-decoration:underline} +html[data-organizations] .ws-needs .src{grid-column:2;font-size:12px;color:var(--muted)} +html[data-organizations] .ws-needs .ws-chip{grid-row:1/3;grid-column:3} +html[data-organizations] .ws-more-line{margin:6px 0 0} +html[data-organizations] .ws-sess td.who{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:0;width:100%} +html[data-organizations] .ws-sess td.who .ws-orgref{vertical-align:middle} +html[data-organizations] .ws-sess td.st{white-space:nowrap} +/* Filters and tables on Projects and Inbox. */ +html[data-organizations] .ws-toolbar{display:flex;flex-wrap:wrap;gap:8px 10px;align-items:center;margin-bottom:12px} +html[data-organizations] .ws-toolbar .ws-right{align-items:center} +html[data-organizations] .ws-toolbar .ws-seg{margin-left:0} +html[data-organizations] .ws-fchips{display:flex;gap:6px;flex-wrap:wrap;align-items:center} +html[data-organizations] .ws-fchips .f{display:inline-flex;align-items:center;gap:6px;min-height:0;border:1px solid var(--line);background:var(--surface);border-radius:999px;padding:2px 10px 2px 4px;font:600 12.5px/1.5 var(--font);color:var(--text);white-space:nowrap;cursor:pointer;box-shadow:none} +html[data-organizations] .ws-fchips .f.plain{padding-left:10px} +html[data-organizations] .ws-fchips .f:hover{background:var(--raised)} +html[data-organizations] .ws-fchips .f[aria-pressed="true"]{background:var(--strong);color:var(--surface);border-color:var(--strong)} +html[data-organizations] .ws-fchips .f .ws-av{width:18px;height:18px;border-radius:999px;font-size:8.5px;letter-spacing:0} +html[data-organizations] .ws-fchips .f .n{margin-left:2px;font:600 11px var(--mono);opacity:.8} +html[data-organizations] .ws-sel{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);background:var(--surface);border-radius:var(--r);padding:0 0 0 8px;font-size:13px;color:var(--strong);white-space:nowrap} +html[data-organizations] .ws-sel .ws-label{font-size:10px} +html[data-organizations] .ws-sel select{border:0;background:transparent;color:var(--strong);font:500 13px/1.5 var(--font);padding:3px 6px 3px 2px;min-height:0;box-shadow:none;width:auto} +html[data-organizations] .ws-search{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);background:var(--surface);border-radius:var(--r);padding:0 8px;color:var(--muted);font-size:13px;min-width:180px} +html[data-organizations] .ws-search svg.i{width:14px;height:14px;flex:none} +html[data-organizations] .ws-search input{border:0;background:transparent;color:var(--strong);font:500 13px/1.5 var(--font);padding:3px 0;min-height:0;box-shadow:none;width:100%;min-width:0} +html[data-organizations] .ws-search:focus-within,html[data-organizations] .ws-sel:focus-within{outline:2px solid var(--focus,var(--action));outline-offset:1px} +html[data-organizations] .ws-search input:focus,html[data-organizations] .ws-sel select:focus{outline:none} +html[data-organizations] .ws-tbl th.sorted{color:var(--strong)} +html[data-organizations] .ws-tbl th .ar{font-family:var(--mono);margin-left:3px;color:var(--action)} +html[data-organizations] .ws-tbl td.num,html[data-organizations] .ws-tbl th.num{text-align:right;font-variant-numeric:tabular-nums} +html[data-organizations] .ws-tbl tr.ws-edge td:first-child{box-shadow:inset 3px 0 0 var(--org)} +html[data-organizations] .ws-tbl tr.ws-edge{box-shadow:none} +html[data-organizations] .ws-tbl .nm{color:var(--strong);font-weight:600;text-decoration:none} +html[data-organizations] .ws-tbl a.nm:hover{text-decoration:underline} +html[data-organizations] .ws-tbl .ws-n{margin-left:0} +html[data-organizations] .ws-grp-row th{padding:8px 10px 6px;background:color-mix(in srgb,var(--raised) 45%,var(--surface));text-transform:none;letter-spacing:0;font-size:12.5px;color:var(--strong);box-shadow:inset 3px 0 0 var(--org)} +html[data-organizations] .ws-grp-row th>*{vertical-align:middle} +html[data-organizations] .ws-grp-row th>span{margin-left:8px} +html[data-organizations] .ws-tbl .ws-grp-row th>.ws-n{margin-left:8px} +html[data-organizations] .ws-unread td{font-size:12.5px} +html[data-organizations] .ws-unread-note{margin:-4px 0 10px} +html[data-organizations] .ws-av.mob{display:none} +html[data-organizations] .ws .show-m{display:none} +/* Inbox. */ +html[data-organizations] .ws-ibx-grid{display:grid;gap:16px;grid-template-columns:minmax(0,1fr)} +html[data-organizations] .ws-ibx-grid.with-insp{grid-template-columns:minmax(0,1fr) minmax(300px,360px);align-items:start} +html[data-organizations] .ws-ibx-list>.ws-sec-h{margin-top:22px} +html[data-organizations] .ws-ibx td.src{white-space:nowrap} +html[data-organizations] .ws-ibx .q{color:var(--strong);font-weight:600;text-decoration:none} +html[data-organizations] .ws-ibx .q:hover{text-decoration:underline} +html[data-organizations] .ws-ibx .via{display:block;font-size:12px;color:var(--muted)} +html[data-organizations] .ws-ibx tr.on{background:color-mix(in srgb,var(--action) 10%,var(--surface))} +html[data-organizations] .ws-ibx tr.on td:first-child{box-shadow:inset 3px 0 0 var(--action)} +html[data-organizations] .ws-msrc{align-items:center;gap:5px;font-size:12px;color:var(--muted);margin-bottom:2px} +html[data-organizations] .ws-insp{border:1px solid var(--line);border-radius:10px;background:var(--surface);display:flex;flex-direction:column;min-width:0;position:sticky;top:12px;max-height:calc(100vh - 80px);overflow:auto} +html[data-organizations] .ws-insp header{display:flex;align-items:center;gap:8px;padding:10px 14px;border-bottom:1px solid var(--line);background:var(--surface);position:sticky;top:0;z-index:1;box-shadow:inset 3px 0 0 var(--org)} +html[data-organizations] .ws-insp header .x{margin-left:auto;color:var(--muted);display:inline-flex} +html[data-organizations] .ws-insp header .x svg.i{width:18px;height:18px} +html[data-organizations] .ws-insp .body{padding:14px;display:grid;gap:14px} +html[data-organizations] .ws-insp h3{margin:0;font-size:16px;font-weight:700;color:var(--strong)} +html[data-organizations] .ws-insp .note{margin:0} +html[data-organizations] .ws-auth{border:1px solid var(--line);border-left:3px solid var(--org,var(--action));border-radius:0 6px 6px 0;padding:8px 10px;background:var(--canvas);font-size:13px;color:var(--strong)} +html[data-organizations] .ws-opts{list-style:none;margin:0;padding:0;display:grid;gap:8px} +html[data-organizations] .ws-opts li{border:1px solid var(--line);border-radius:8px;padding:9px 10px;display:grid;gap:6px;background:var(--canvas)} +html[data-organizations] .ws-opts .k{font:700 13px var(--mono);color:var(--strong)} +html[data-organizations] .ws-opts .row{display:flex;gap:8px;align-items:center;flex-wrap:wrap} +html[data-organizations] .ws-opts b{font-weight:600;color:var(--strong)} +html[data-organizations] [data-ws-cmds]{display:grid;gap:6px} +html[data-organizations] .ws-cmd{display:flex;gap:6px;align-items:center;min-width:0} +html[data-organizations] .ws-cmd code{flex:1;min-width:0;overflow-x:auto;white-space:nowrap;background:var(--surface);border:1px solid var(--line);border-radius:4px;padding:3px 6px;font-size:12px;color:var(--strong)} +html[data-organizations] .ws-cmd .ws-btn{padding:4px 6px} +html[data-organizations] #copy-status:empty{display:none} +@media (max-width:1100px){ + html[data-organizations] .ws-g5{grid-template-columns:repeat(3,minmax(0,1fr))} + html[data-organizations] .ws-ibx-grid.with-insp{grid-template-columns:minmax(0,1fr)} + html[data-organizations] .ws-insp{position:static;max-height:none} +} + @media (pointer:coarse){html[data-organizations] .ws-nav,html[data-organizations] .s1-section.ws-nav{min-height:40px}} @media (max-width:759px){ html[data-organizations] .content:has(.ws){padding:14px 16px 24px} @@ -559,4 +692,19 @@ html[data-organizations] .ws-scope{margin:-8px 0 14px} html[data-organizations] .ws-levels>.span{grid-column:auto} html[data-organizations] .ws-levels>.last.lh{border-bottom:1px solid color-mix(in srgb,var(--line) 60%,transparent)} html[data-organizations] .ws-levels .mlabel{display:flex} + html[data-organizations] .ws-g5{grid-template-columns:minmax(0,1fr)} + html[data-organizations] .ws-g5.keep2{grid-template-columns:repeat(2,minmax(0,1fr))} + html[data-organizations] .ws-g5.keep2>:last-child:nth-child(odd){grid-column:1/-1} + html[data-organizations] .ws-orgcards{grid-template-columns:minmax(0,1fr)} + html[data-organizations] .ws-srow{grid-template-columns:92px 20px minmax(0,1fr)} + html[data-organizations] .ws-srow .ws-by{grid-column:1/-1} + html[data-organizations] .ws-trail li{grid-template-columns:42px 18px minmax(0,1fr);gap:8px} + html[data-organizations] .ws-trail .what{white-space:normal} + html[data-organizations] .ws-toolbar .ws-right{margin-left:0} + html[data-organizations] .ws-search{min-width:0;flex:1 1 100%} + html[data-organizations] .ws .show-m,html[data-organizations] .ws-tbl .t2.show-m{display:block} + html[data-organizations] .ws span.show-m{display:inline-flex} + html[data-organizations] .ws span.ws-msrc.show-m{display:flex} + html[data-organizations] .ws-av.mob{display:inline-grid;margin-right:6px;vertical-align:-3px} + html[data-organizations] .ws-tbl .t2.mono.hide-m{display:none} } diff --git a/packages/webui/src/public/workspace-data.js b/packages/webui/src/public/workspace-data.js index 845fee6d5..418a18350 100644 --- a/packages/webui/src/public/workspace-data.js +++ b/packages/webui/src/public/workspace-data.js @@ -4,7 +4,8 @@ (() => { const read = async path => { const response = await fetch(path, { cache: 'no-store', redirect: 'manual' }); - if (!response.ok || response.type === 'opaqueredirect') throw new Error('Read unavailable'); + // The status travels with the failure, so a caller can tell a refusal (403) from a bus that is down. + if (!response.ok || response.type === 'opaqueredirect') { const error = new Error('Read unavailable'); error.status = response.type === 'opaqueredirect' ? 0 : response.status; throw error; } return response.json(); }; const orgPath = (id, path) => `/api/orgs/${encodeURIComponent(id)}/${path}`; @@ -20,7 +21,16 @@ const business = id => read(orgPath(id, 'business')); const settings = id => read(orgPath(id, 'settings')); const projectFiles = (id, project) => read(orgPath(id, `project-files?project=${encodeURIComponent(project)}`)); + // U1's cross-organization read (GET /api/workspace). Only the keys it accepts are sent, each once: + // an unknown or repeated key is a 400 there. + const WORKSPACE_KEYS = ['sections', 'org', 'status', 'state', 'name', 'sort', 'order', 'project']; + const workspace = (params = {}) => { + const q = new URLSearchParams(); + for (const key of WORKSPACE_KEYS) { const v = params[key]; if (v !== undefined && v !== null && v !== '') q.set(key, Array.isArray(v) ? v.join(',') : String(v)); } + const qs = q.toString(); + return read(`/api/workspace${qs ? `?${qs}` : ''}`); + }; // The three agent levels (root, organization, project) for every organization on the list, owner only. const agentLevels = () => read('/api/agents/levels'); - window.MosaicWorkspaceData = Object.freeze({ organizations, themes, projects, threads, instances, agents, claims, queue, business, settings, projectFiles, agentLevels }); + window.MosaicWorkspaceData = Object.freeze({ organizations, themes, projects, threads, instances, agents, claims, queue, business, settings, projectFiles, workspace, agentLevels }); })(); diff --git a/packages/webui/src/public/workspace.js b/packages/webui/src/public/workspace.js index e9968c4f9..6f81ad2d7 100644 --- a/packages/webui/src/public/workspace.js +++ b/packages/webui/src/public/workspace.js @@ -128,7 +128,7 @@ if (toggle) { expanded = !expanded; save(ORGS_OPEN, expanded ? 'open' : 'closed'); paint(); document.querySelector('[data-org-toggle]')?.focus(); return; } if (e.target.closest?.('[data-projects-toggle]')) { projectsOpen = !projectsOpen; save(PROJECTS_OPEN, projectsOpen ? 'open' : 'closed'); paint(); document.querySelector('[data-projects-toggle]')?.focus(); return; } const group = e.target.closest?.('#workspace-nav [data-group]'); - if (group) { grouping = group.dataset.group === 'flat' ? 'flat' : 'org'; save(GROUPING, grouping); paint(); document.querySelector(`#workspace-nav [data-group="${grouping}"]`)?.focus(); } + if (group) { grouping = group.dataset.group === 'flat' ? 'flat' : 'org'; save(GROUPING, grouping); paint(); document.querySelector(`#workspace-nav [data-group="${grouping}"]`)?.focus(); if (route().split('?')[0] === '/projects') document.dispatchEvent(new CustomEvent('mosaic-workspace-render')); } }); window.addEventListener('hashchange', () => { if (orgs) paint(); }); document.addEventListener('mosaic-org-list', e => refresh(e.detail?.rows)); @@ -389,6 +389,338 @@ box.innerHTML = agentsAvailable(select.value); }); - window.MosaicWorkspace = Object.freeze({ dashboard, agentGrid, icon, refresh: () => refresh() }); + // ---------- across organizations (U3: samples 02, 04 and 05) ---------- + // One read, GET /api/workspace (U1), backs the three pages. Each organization carries a state and + // the time it was read: one that is down, starting or slow is named with that state, and the rest + // still render. Filters live in the page's hash query, so a poll repaints the same view and a + // link reproduces it. Numbers come only from the read; a field no read gives is one honest line. + let pollMs = 10000; + const took = body => { const n = Number(body?.pollMs); if (Number.isFinite(n) && n >= 1000) pollMs = n; return body; }; + const selHref = path => `#/orgs/${enc(window.MosaicOrg?.id || '')}${path}`; + const ORG_STATE = { ok: ['s-working', '●', 'running'], starting: ['s-waiting', '◐', 'starting'], down: ['s-offline', '○', 'down'], timeout: ['s-error', '▲', 'not answering'], invalid: ['s-error', '▲', 'invalid'] }; + const orgState = o => ORG_STATE[o?.state] || ['s-unknown', '?', 'not reported']; + const msOf = iso => { const t = Date.parse(iso || ''); return Number.isFinite(t) ? t : null; }; + const hm = iso => { const t = msOf(iso); return t === null ? '' : new Date(t).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); }; + // Today's times as HH:MM, older ones as a short date. + const when = iso => { const t = msOf(iso); if (t === null) return ''; const d = new Date(t); return d.toDateString() === new Date().toDateString() ? hm(iso) : d.toLocaleDateString([], { month: 'short', day: 'numeric' }); }; + const span = iso => { const t = msOf(iso); if (t === null) return ''; const m = Math.max(0, Math.floor((Date.now() - t) / 60000)); return m < 1 ? 'under a minute' : m < 60 ? `${m} min` : m < 2880 ? `${Math.floor(m / 60)} h` : `${Math.floor(m / 1440)} days`; }; + const ago = iso => { const s = span(iso); return !s ? '' : s === 'under a minute' ? 'just now' : `${s} ago`; }; + const num = v => (Number.isFinite(v) ? v : 0); + const arr = v => (Array.isArray(v) ? v : []); + // The organizations the read names, with their colours, marks and states. + function orgsOf(body) { + const rows = arr(body?.orgs).filter(o => o && typeof o.org === 'string'); + // The read names an organization by id; the sidebar's list carries its display label. + const known = id => (Array.isArray(orgs) ? orgs.find(x => x?.id === id) : null); + const byId = new Map(rows.map(o => [o.org, { id: o.org, label: known(o.org)?.label || o.label || o.org, theme: o.theme ?? known(o.org)?.theme ?? null }])); + const meta = id => byId.get(id) || { id, label: id }; + return { + rows, meta, name: id => label(meta(id)), style: id => colours(meta(id)), + ref: (id, cls = '') => `${av(meta(id))}${esc(label(meta(id)))}`, + unread: rows.filter(o => o.state !== 'ok'), + }; + } + const stateWords = o => `${esc((Array.isArray(orgs) ? orgs.find(x => x?.id === o.org)?.label : null) || o.label || o.org)} ${orgState(o)[2]}${o.at ? `, read ${hm(o.at)}` : ''}`; + const andList = items => (items.length < 2 ? items.join('') : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`); + // An organization that answered can still fail one read (errors in GET /api/workspace). The page + // names that organization and the reason rather than count the read as zero. + const READ_WHY = { 'channel-disabled': 'the chat channel is off', 'outcome-unknown': 'no answer', timeout: 'no answer in time' }; + const missOf = (r, names) => { const n = r?.state === 'ok' && r.errors ? names.find(x => r.errors[x]) : null; return n ? READ_WHY[r.errors[n]] || String(r.errors[n]) : null; }; + const missed = (o, names) => o.rows.filter(r => missOf(r, names)).map(r => `${esc(o.name(r.org))} (${esc(missOf(r, names))})`); + const missLine = (o, names, key) => { const m = missed(o, names); return m.length ? `

Not read in ${andList(m)}.

` : ''; }; + function failedPage(cls, attr, title, err) { + const why = err?.status === 403 ? 'This Console refused the read across organizations.' : err?.status === 0 ? 'You are signed out. Reload the page to sign in again.' : err?.status === 400 ? 'The read refused these filters. Clear them and try again.' : 'The read across organizations did not answer. The page tries again on its next refresh.'; + return `

${title}

${why}

`; + } + // The Inbox count in the navigation follows the cross-organization read wherever it was made. + const tellInbox = rows => { if (Array.isArray(rows)) document.dispatchEvent(new CustomEvent('mosaic-workspace-inbox', { detail: { open: rows.length, blocking: rows.filter(d => d?.blocking).length } })); }; + // A stacked bar and its per-organization figures, one segment per organization. + const bar = (o, parts, style = '') => ``; + const by = (o, parts, fmt = n => n) => `
${parts.map(p => `${av(o.meta(p.id))}${esc(o.name(p.id))}${esc(fmt(p.n))}`).join('')}
`; + const CLASS_CHIP = { gated: 'gated', 'within-role': 'within', routine: 'routine', 'cross-role': 'cross' }; + const classChip = c => (c ? `${esc(c)}` : ''); + const itemKey = d => `${d.org}:${d.id}`; + const roleOf = d => d.session?.role || d.raisedBy || ''; + const fromWords = (o, d, withOrg = true) => [withOrg ? o.name(d.org) : '', d.project?.name || 'No project', roleOf(d)].filter(Boolean).map(esc).join(' · '); + + // ---- main dashboard (sample 02) ---- + async function home() { + let body; + try { [body] = await Promise.all([data.workspace({ sections: ['projects', 'sessions', 'inbox', 'tasks', 'metrics'] }), ensureThemes()]); took(body); } + catch (err) { return failedPage('ws-home', 'data-ws-home', 'Dashboard', err); } + const o = orgsOf(body), m = body.metrics, t = m?.totals, per = arr(m?.orgs); + const inbox = arr(body.inbox), sessions = arr(body.sessions), projectRows = arr(body.projects), tasks = arr(body.tasks); + tellInbox(body.inbox); + const parts = f => per.map(x => ({ id: x.org, n: num(f(x)) })); + const sessN = s => num(s?.working) + num(s?.waiting) + num(s?.idle) + num(s?.live); + const SRC = { needs: ['inbox'], sessions: ['agents', 'claims', 'threads'], tasks: ['tasks'], projects: ['projects'] }; + const answered = o.rows.filter(r => r.state === 'ok').length; + const tile = (key, name, big, small, ps, delta) => { + const m = missed(o, SRC[key]); + if (m.length && m.length === answered) return `
${name}Not read${andList(m)}
`; + return `
${name}${big}${small ? `${small}` : ''}${ps ? bar(o, ps) + by(o, ps) : ''}${delta}${m.length ? `Not read in ${andList(m)}` : ''}
`; + }; + const tiles = t ? `
+ ${tile('needs', 'Needs you', num(t.needsYou), t.needsYou === 1 ? 'item' : 'items', parts(x => x.needsYou), t.oldestNeedsYouAt ? `oldest ${span(t.oldestNeedsYouAt)}` : 'nothing waiting')} + ${tile('sessions', 'Sessions', sessN(t.sessions), `${num(t.sessions?.working)} working`, parts(x => sessN(x.sessions)), `${num(t.sessions?.waiting)} waiting on you · ${num(t.sessions?.idle)} idle${num(t.sessions?.live) ? ` · ${num(t.sessions.live)} live ${t.sessions.live === 1 ? 'thread' : 'threads'}` : ''}`)} + ${tile('tasks', 'Open tasks', num(t.openTasks), '', parts(x => x.openTasks), `${num(t.doneThisWeek)} done this week`)} + ${tile('projects', 'Projects', num(t.projects?.active) + num(t.projects?.archived), `${num(t.projects?.active)} active`, parts(x => num(x.projects?.active) + num(x.projects?.archived)), `${num(t.projects?.archived)} archived`)} +
Model spendNo spend figures yetNo read prices model use today.
+
` : '

No organization answered, so there are no totals yet.

'; + + const cards = o.rows.map(r => { + const [cls, glyph, word] = orgState(r), id = r.org; + const extra = r.state === 'ok' ? '' : `${esc(r.reason || '')}${r.boot?.at ? `${r.reason ? ' · ' : ''}last start ${esc(when(r.boot.at))}` : ''}`; + return `
  • ${av(o.meta(id), 'md')}${esc(o.name(id))}${dot(cls, glyph, word, true)}read ${esc(hm(r.at))}${extra}
  • `; + }).join(''); + + const recent = projectRows.filter(p => p.lastActivity).slice(0, 6); + const STATE_WORD = { working: 'has a session working', waiting: 'is waiting on you', idle: 'has an idle session', none: 'no live session' }; + const trail = recent.length ? `
      ${recent.map(p => `
    1. ${av(o.meta(p.org))}${esc(p.name || p.key || p.id)} ${STATE_WORD[p.state] || ''}${p.needsYou ? `, ${plural(p.needsYou, 'item')} for you` : ''} · ${esc(o.name(p.org))}
    2. `).join('')}
    ` : '

    No project activity yet

    '; + + const open = tasks.filter(x => !x.done); + const buckets = new Map(); + for (const x of open) { const b = typeof x.bucket === 'string' && x.bucket ? x.bucket : ''; if (!buckets.has(b)) buckets.set(b, new Map()); const g = buckets.get(b); g.set(x.org, (g.get(x.org) || 0) + 1); } + const srows = [...buckets.entries()].map(([b, g]) => ({ name: b ? titleCase(b) : 'No bucket', g, n: [...g.values()].reduce((a, c) => a + c, 0) })).sort((a, b) => b.n - a.n); + if (t) srows.push({ name: 'Done this week', g: new Map(per.map(x => [x.org, num(x.doneThisWeek)])), n: num(t.doneThisWeek) }); + const max = Math.max(1, ...srows.map(s => s.n)); + const states = srows.length ? `
    ${srows.map(s => { const ps = [...s.g.entries()].filter(([, n]) => n > 0).map(([id, n]) => ({ id, n })); return `
    ${esc(s.name)}${s.n}${bar(o, ps, `width:${Math.max(4, Math.round((s.n / max) * 90))}%`)}${by(o, ps)}
    `; }).join('')}
    ` : '

    No open tasks

    '; + + const needs = inbox.slice(0, 5); + const needsList = needs.length ? `${inbox.length > needs.length ? `

    ${inbox.length - needs.length} more in the inbox

    ` : ''}` : '

    Nothing needs you

    '; + + const now = sessions.filter(s => s.kind === 'thread' || s.state === 'working' || s.state === 'waiting'); + const idle = sessions.length - now.length; + const who = s => (s.kind === 'thread' ? s.instance || s.thread || 'thread' : s.role || 'agent'); + const what = s => s.project?.name || s.task?.title || ''; + const st = s => { const [cls, glyph, word] = s.kind === 'thread' ? ['s-working', '●', 'live'] : ACTIVITY[s.state] || ['s-unknown', '?', s.state || 'not reported']; return `${dot(cls, glyph, word === 'waiting on you' ? 'waiting' : word, true)}${s.state === 'waiting' ? ' on you' : s.since ? ` ${esc(span(s.since))}` : ''}`; }; + const sessTable = now.length ? `
    ${now.slice(0, 8).map(s => ``).join('')}
    Agent and projectStatus
    ${av(o.meta(s.org), 'xs')}${esc(who(s))}${what(s) ? ` · ${esc(what(s))}` : ''}${st(s)}
    ${now.length > 8 ? `

    ${now.length - 8} more on Agents

    ` : ''}` : `

    No session working right now${idle ? `; ${plural(idle, 'idle session')}` : ''}

    `; + + const total = t ? num(t.projects?.active) + num(t.projects?.archived) : null; + const allRead = !o.unread.length; + const sub = !o.rows.length ? 'You belong to no organization yet.' + : allRead ? `All ${plural(o.rows.length, 'organization')}${missed(o, ['projects']).length ? '' : ` and ${plural(total ?? 0, 'project')}`}. Totals add up every organization you belong to; each tile breaks them down by organization.` + : `${body.summary?.read ?? o.rows.length - o.unread.length} of ${plural(o.rows.length, 'organization')} answered. Totals add up the ones that answered; ${andList(o.unread.map(stateWords))}.`; + return `
    +

    Dashboard

    ${sub}

    + ${tiles} + ${secH('Organizations', `read ${esc(hm(body.readAt))}`)} +
      ${cards || '
    • No organizations yet
    • '}
    +
    +
    + ${secH('Recent project activity', 'latest change per project; there is no activity feed yet', `All projects`)} + ${trail}${missLine(o, ['projects'], 'recent')} + ${secH('Tasks by state', 'open tasks, every tracker', `Open tasks`)} + ${states}${missLine(o, ['tasks'], 'states')} +
    +
    + ${secH('Needs you', '', `Inbox`)} + ${needsList}${missLine(o, ['inbox'], 'needs')} + ${secH('Sessions now', '', `Agents`)} + ${sessTable}${missLine(o, ['agents', 'claims', 'threads'], 'sessions')} +
    +
    +
    `; + } + + // ---- projects across organizations (sample 04, REQ-WS-5) ---- + const ORG_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/; + const listParam = (q, key, ok) => { const v = [...new Set(String(q?.get?.(key) || '').split(',').map(s => s.trim()).filter(ok))]; return v.length ? v : null; }; + // The hash query, cleaned to what the API accepts, so a hand-edited link never reads as "all". + function projectQuery(q) { + const sort = ['activity', 'name', 'org', 'status'].includes(q?.get?.('sort')) ? q.get('sort') : 'activity'; + const order = ['asc', 'desc'].includes(q?.get?.('order')) ? q.get('order') : sort === 'activity' ? 'desc' : 'asc'; + const name = String(q?.get?.('name') || '').trim().slice(0, 200); + return { + org: listParam(q, 'org', id => ORG_ID.test(id)), status: listParam(q, 'status', s => ['active', 'archived'].includes(s)) || ['active'], + state: listParam(q, 'state', s => ['working', 'waiting', 'idle', 'none'].includes(s)), name: name || null, sort, order, + }; + } + const SORT_WORD = { activity: 'latest activity', name: 'name', org: 'organization', status: 'status' }; + const STATUS_OPTS = [['active', 'Active'], ['archived', 'Archived'], ['active,archived', 'Active and archived']]; + const STATE_OPTS = [['', 'Any session state'], ['working', 'Working'], ['waiting', 'Waiting on you'], ['idle', 'Idle'], ['none', 'No session']]; + function orgChips(o, counts, chosen, total, src = []) { + const all = !chosen; + return `
    ${o.rows.map(r => ``).join('')}
    `; + } + async function projectsPage(q) { + const f = projectQuery(q); + const params = { sections: ['projects'], org: f.org, status: f.status, state: f.state, name: f.name, sort: f.sort, order: f.order }; + let body, all; + try { + [body, all] = await Promise.all([data.workspace(params), f.org ? data.workspace({ ...params, org: null }) : null, ensureThemes()]); + took(body); + } catch (err) { return failedPage('ws-projects', 'data-ws-projects', 'Projects', err); } + const every = orgsOf(all || body), o = orgsOf(body); + const counts = new Map(); + for (const p of arr((all || body).projects)) counts.set(p.org, (counts.get(p.org) || 0) + 1); + const rows = arr(body.projects); + const flat = grouping === 'flat'; + const cols = flat ? 8 : 7; + const aria = key => (f.sort === key ? ` aria-sort="${f.order === 'desc' ? 'descending' : 'ascending'}" class="sorted` : ' class="'); + const ar = key => (f.sort === key ? `` : ''); + const head = `${flat ? `Organization${ar('org')}` : ''}Project${ar('name')}Status${ar('status')}SessionsOpen tasksNeeds youLast activity${ar('activity')}Git`; + const SESS = [['working', 's-working', '●', 'working'], ['waiting', 's-waiting', '◐', 'waiting'], ['idle', 's-idle', '–', 'idle']]; + const sessCell = p => { const s = p.sessions || {}, have = SESS.filter(([k]) => num(s[k]) > 0); if (!have.length) return 'none'; const [k, cls, glyph, word] = have[0]; return `${dot(cls, glyph, `${num(s[k])} ${word}`, true)}${have.length > 1 ? `${have.slice(1).map(([k2, , , w2]) => `${num(s[k2])} ${w2}`).join(' · ')}` : ''}`; }; + const row = p => { + const href = `${orgHref(p.org)}/projects/${enc(p.id)}`, active = p.status === 'active'; + return ` + ${flat ? `${o.ref(p.org)}` : ''} + ${av(o.meta(p.org), 'xs mob')}${esc(p.name || p.key || p.id)} in ${esc(o.name(p.org))}${p.key ? `${esc(p.key)}` : ''}${p.lastActivity ? esc(ago(p.lastActivity)) : 'No activity yet'} + ${active ? dot('s-ok', '●', 'active', true) : dot('s-idle', '–', 'archived', true)} + ${sessCell(p)} + ${num(p.openTasks)} + ${p.needsYou ? `${num(p.needsYou)}` : '0'} + ${p.lastActivity ? `` : 'none yet'} + ${p.git ? `${esc(p.git)}` : 'none'} + `; + }; + const unreadRow = r => `${dot(...orgState(r), true)} Not read${r.at ? ` at ${esc(hm(r.at))}` : ''}${r.reason ? `: ${esc(r.reason)}` : ''}`; + let tbody; + if (flat) tbody = rows.length ? rows.map(row).join('') : `${f.org || f.state || f.name || f.status.join() !== 'active' ? 'No projects match these filters' : 'No projects yet'}`; + else { + const groups = (f.sort === 'org' && f.order === 'desc' ? [...o.rows].reverse() : o.rows); + tbody = groups.map(r => { + const mine = rows.filter(p => p.org === r.org); + const h = `${av(o.meta(r.org))}${esc(o.name(r.org))}${r.state === 'ok' && !missOf(r, ['projects']) ? `${mine.length}` : ''}`; + const why = missOf(r, ['projects']); + return h + (r.state !== 'ok' ? unreadRow(r) : why ? `${dot('s-unknown', '?', 'not read', true)} Projects not read: ${esc(why)}` : mine.length ? mine.map(row).join('') : `No projects match`); + }).join('') || `No organizations yet`; + } + const unreadNote = flat && o.unread.length ? `

    Not in this list: ${andList(o.unread.map(stateWords))}.

    ` : ''; + const missNote = flat ? missLine(o, ['projects'], 'projects') : ''; + const shown = new Set(rows.map(p => p.org)).size; + const sub = `${plural(rows.length, 'project')} in ${plural(shown, 'organization')}, sorted by ${SORT_WORD[f.sort]}${f.sort === 'activity' ? (f.order === 'desc' ? ', newest first' : ', oldest first') : f.order === 'desc' ? ', descending' : ''}. Each row names its organization by mark and colour edge.`; + const statusVal = f.status.join(','); + const stateVal = f.state?.length === 1 ? f.state[0] : ''; + return `
    + +
    + + ${orgChips(every, counts, f.org, arr((all || body).projects).length, ['projects'])} + + +
    Sort${['activity', 'name', 'org', 'status'].map(s => ``).join('')} +
    +
    + ${unreadNote}${missNote} +
    ${head}${tbody}
    Projects across organizations
    +
    `; + } + + // ---- inbox across organizations (sample 05) ---- + async function inboxPage(q) { + const org = listParam(q, 'org', id => ORG_ID.test(id)); + const want = String(q?.get?.('d') || ''); + let body, all; + try { + [body, all] = await Promise.all([data.workspace({ sections: ['inbox'], org }), org ? data.workspace({ sections: ['inbox'] }) : null, ensureThemes()]); + took(body); + } catch (err) { return failedPage('ws-inbox', 'data-ws-inbox', 'Inbox', err); } + const every = orgsOf(all || body), o = orgsOf(body); + const everyRows = arr((all || body).inbox); + tellInbox(everyRows); + const counts = new Map(); + for (const d of everyRows) counts.set(d.org, (counts.get(d.org) || 0) + 1); + const rows = arr(body.inbox); + const picked = want === 'none' ? null : rows.find(d => itemKey(d) === want) || (want ? null : rows[0] || null); + const qs = d => { const p = new URLSearchParams(); if (org) p.set('org', org.join(',')); p.set('d', d ? itemKey(d) : 'none'); return `/inbox?${p}`; }; + const row = d => { + const on = picked && itemKey(d) === itemKey(picked); + return ` + ${o.ref(d.org)}${fromWords(o, d, false)} + ${av(o.meta(d.org), 'xs')}${fromWords(o, d)}${esc(d.question || `Decision ${d.id}`)}decision ${esc(d.id)}${d.taskRef ? ` · task ${esc(d.taskRef)}` : ''}${classChip(d.class)}${d.blocking ? ' blocking' : ''} + ${classChip(d.class)}${d.blocking ? ' blocking' : ''} + ${d.at ? `` : 'not reported'} + `; + }; + const unread = (o.unread.length ? `

    Not in this list: ${andList(o.unread.map(stateWords))}.

    ` : '') + missLine(o, ['inbox'], 'inbox'); + const table = rows.length ? `
    ${rows.map(row).join('')}
    Items that need you
    SourceNeedsClassWaiting
    ` : `

    ${org ? 'Nothing needs you in these organizations' : 'Nothing needs you'}

    `; + let insp = ''; + if (picked) { + const d = picked, id = esc(d.id); + const decideHref = `${orgHref(d.org)}/inbox/${enc(d.id)}`; + const opts = arr(d.options); + const optList = opts.length ? `` : `

    No options were given. Open the decision

    `; + const cmds = arr(d.decide).filter(c => typeof c?.command === 'string' && c.command); + const term = cmds.length ? `
    Answer from a terminal${cmds.map(c => `
    ${esc(c.command)}
    `).join('')}

    The inbox mixes organizations, so the copied command always names the organization's bus.

    ` : '

    No terminal command for this item: its id or options cannot be passed to a shell safely.

    '; + const by = roleOf(d); + insp = ``; + } + const orgsWith = new Set(rows.map(d => d.org)).size; + const sub = rows.length ? `${plural(rows.length, 'item')} need${rows.length === 1 ? 's' : ''} you, from ${plural(orgsWith, 'organization')}. Each row names where it came from. An item leaves only when it is answered.` : `${missed(o, ['inbox']).length || o.unread.length ? 'Nothing needs you in the organizations that were read.' : 'Nothing needs you right now.'} An item leaves only when it is answered.`; + return `
    +

    Inbox

    ${sub}

    +
    + ${orgChips(every, counts, org, everyRows.length, ['inbox'])} +
    Seen and Answered are not built yet.
    +
    + ${unread} +
    ${table} + ${secH('Answered today', 'kept for 24 hours, then in the trail')} +

    Answered and expired items are not built yet.

    + ${insp} +
    +
    `; + } + + // ---- controls: filters write the hash query and repaint in place ---- + const pathOf = () => route().split('?')[0]; + const queryOf = () => new URLSearchParams(route().split('?')[1] || ''); + function setQuery(change, render = true) { + const q = queryOf(); + for (const [k, v] of Object.entries(change)) { if (v === null || v === undefined || v === '' || (Array.isArray(v) && !v.length)) q.delete(k); else q.set(k, Array.isArray(v) ? v.join(',') : String(v)); } + const s = q.toString(); + history.replaceState(history.state, '', `${selHref(pathOf())}${s ? `?${s}` : ''}`); + if (render) document.dispatchEvent(new CustomEvent('mosaic-workspace-render')); + } + function setGrouping(g) { + grouping = g === 'flat' ? 'flat' : 'org'; save(GROUPING, grouping); paint(); + if (pathOf() === '/projects') document.dispatchEvent(new CustomEvent('mosaic-workspace-render')); + } + document.addEventListener('click', e => { + const page = e.target.closest?.('[data-ws-projects],[data-ws-inbox]'); + if (!page) return; + const chip = e.target.closest('[data-ws-org]'); + if (chip) { + const id = chip.dataset.wsOrg, now = listParam(queryOf(), 'org', x => ORG_ID.test(x)) || []; + const next = !id ? [] : now.includes(id) ? now.filter(x => x !== id) : [...now, id]; + setQuery(page.hasAttribute('data-ws-inbox') ? { org: next, d: null } : { org: next }); + return; + } + const sort = e.target.closest('[data-ws-sort]'); + if (sort) { + const f = projectQuery(queryOf()), s = sort.dataset.wsSort; + setQuery(s === f.sort ? { sort: s, order: f.order === 'desc' ? 'asc' : 'desc' } : { sort: s, order: null }); + return; + } + const grp = e.target.closest('[data-ws-group]'); + if (grp) { setGrouping(grp.dataset.wsGroup); return; } + const pick = e.target.closest('[data-ws-select]'); + if (pick && !e.metaKey && !e.ctrlKey && !e.shiftKey && e.button === 0) { e.preventDefault(); setQuery({ d: pick.dataset.wsSelect }); } + }); + document.addEventListener('change', e => { + if (e.target.matches?.('[data-ws-projects] [data-ws-status]')) setQuery({ status: e.target.value === 'active' ? null : e.target.value }); + else if (e.target.matches?.('[data-ws-projects] [data-ws-state]')) setQuery({ state: e.target.value || null }); + }); + // Typing writes the hash at once, so a poll repaint keeps what was typed; the read waits a beat. + let typing; + document.addEventListener('input', e => { + if (!e.target.matches?.('[data-ws-projects] [data-ws-name]')) return; + setQuery({ name: e.target.value.slice(0, 200) || null }, false); + clearTimeout(typing); typing = setTimeout(() => document.dispatchEvent(new CustomEvent('mosaic-workspace-render')), 250); + }); + + window.MosaicWorkspace = Object.freeze({ dashboard, agentGrid, icon, refresh: () => refresh(), home, projectsPage, inboxPage, setGrouping, get pollMs() { return pollMs; } }); refresh(); })(); diff --git a/packages/webui/tests/org-lan-bind-browser.test.mjs b/packages/webui/tests/org-lan-bind-browser.test.mjs index 5d3304a55..b0c27088a 100644 --- a/packages/webui/tests/org-lan-bind-browser.test.mjs +++ b/packages/webui/tests/org-lan-bind-browser.test.mjs @@ -31,7 +31,7 @@ test('an allowed LAN name loads the org page and creates a project', { timeout: const wait = expression => b.evaluate(`(async()=>{for(let i=0;i<300;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`); const input = (selector, value) => b.evaluate(`(()=>{const e=document.querySelector(${JSON.stringify(selector)});e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('input',{bubbles:true}));e.dispatchEvent(new Event('change',{bubbles:true}));})()`); const click = selector => b.evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`); - await b.navigate(`http://lan.test:${port}/#/orgs/alpha/projects`); + await b.navigate(`http://lan.test:${port}/#/orgs/alpha/chat`); assert.deepEqual(await b.evaluate('({ host: location.host, secure: isSecureContext, uuid: typeof crypto.randomUUID })'), { host: `lan.test:${port}`, secure: false, uuid: 'undefined' }); await wait('window.MosaicOrg?.id === "alpha" && !!document.querySelector("#chat-repo option[value=work]")'); await click('.project-create summary'); diff --git a/packages/webui/tests/org-list-refresh-browser.test.mjs b/packages/webui/tests/org-list-refresh-browser.test.mjs index 466347416..4394cca39 100644 --- a/packages/webui/tests/org-list-refresh-browser.test.mjs +++ b/packages/webui/tests/org-list-refresh-browser.test.mjs @@ -31,7 +31,7 @@ const bannerText = "document.getElementById('org-list-banner')?.textContent || ' test('a registry error shows on a selected org page and Retry recovers', async t => { const f = await setup(t), file = join(f.ctx.configDir, 'org-runtime.json'); const original = await fs.readFile(file, 'utf8'); await fs.writeFile(file, '{'); - await f.b.navigate(`${f.base}/#/orgs/alpha/`); + await f.b.navigate(`${f.base}/#/orgs/alpha/board`); await wait(f.b, `(${bannerText}).includes('Organization registry could not be read') && document.querySelector('#held [data-retry]')`); const before = f.requests(); await fs.writeFile(file, original); await f.b.evaluate("document.querySelector('#held [data-retry]').click()"); @@ -44,7 +44,7 @@ test('a broken org banner is replaced, not stacked, and clears after repair', as const f = await setup(t), file = join(f.ctx.configDir, 'org-runtime.json'); const original = await fs.readFile(file, 'utf8'), reg = JSON.parse(original); reg.orgs.beta.digest = '0'.repeat(64); await fs.writeFile(file, JSON.stringify(reg)); - await f.b.navigate(`${f.base}/#/orgs/alpha/`); + await f.b.navigate(`${f.base}/#/orgs/alpha/board`); await wait(f.b, `(${bannerText}).includes('beta: invalid') && document.querySelector('#held [data-retry]')`); await f.b.evaluate('window.MosaicRefreshOrganizations()'); await wait(f.b, `(${bannerText}).includes('beta: invalid')`); diff --git a/packages/webui/tests/org-release-browser.mjs b/packages/webui/tests/org-release-browser.mjs index eb72d71dd..5ce2207f4 100644 --- a/packages/webui/tests/org-release-browser.mjs +++ b/packages/webui/tests/org-release-browser.mjs @@ -49,7 +49,7 @@ try { await wait('document.querySelector("#org-setup") && !document.querySelector("#org-setup").hidden'); assert.match(await b.evaluate('location.hash'), /^#\/orgs\/alpha\/settings\/organizations\?org=alpha&step=setup$/); await b.screenshot(join(shots, '03-resume.png')); - await b.evaluate(`location.hash='#/orgs/alpha/projects'`); + await b.evaluate(`location.hash='#/orgs/alpha/chat'`); await wait('!!document.querySelector("#chat-repo option[value=work]")'); await click('.project-create summary'); await input('#chat-project-name', 'Work'); await input('#chat-repo', 'work'); diff --git a/packages/webui/tests/org-request-status-browser.test.mjs b/packages/webui/tests/org-request-status-browser.test.mjs index c34fa23cb..0f225c56c 100644 --- a/packages/webui/tests/org-request-status-browser.test.mjs +++ b/packages/webui/tests/org-request-status-browser.test.mjs @@ -118,7 +118,7 @@ test('an organization offers its request status, and a conversation whose messag test('an organization project overview reports no active request instead of unavailable', { timeout: 60000 }, async t => { const { base, diagnostics } = await consoleFor(t); const { b, wait } = await page(t, base, diagnostics); - await b.navigate(`${base}#/orgs/alpha/projects`); + await b.navigate(`${base}#/orgs/alpha/chat`); await wait(`document.querySelector('[data-project-status="${P}"] .project-card-status-line')`); assert.match(await b.evaluate(`document.querySelector('[data-project-status="${P}"]').textContent`), /^No active requests · 1 conversation/); // The overview renders after its reads settle, so the metrics are final once they exist. diff --git a/packages/webui/tests/org-switch-browser.test.mjs b/packages/webui/tests/org-switch-browser.test.mjs index 426a82eac..addb69335 100644 --- a/packages/webui/tests/org-switch-browser.test.mjs +++ b/packages/webui/tests/org-switch-browser.test.mjs @@ -123,7 +123,7 @@ test('project creation offers repositories from the scoped business read', async }; const server = await startServer({ port: 0, sso: createDevOwner(), organizations, 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.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/alpha/chat`); await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('#chat-repo option[value=work]'))return;await new Promise(r=>setTimeout(r,30))}throw Error('repository choice missing')})()`); assert.equal(await b.evaluate(`document.querySelector('#chat-repo option[value=work]').value`), 'work'); }); @@ -269,7 +269,7 @@ test('a stopped organization bus has truthful chat guidance', async t => { }; 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.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/alpha/chat`); 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); diff --git a/packages/webui/tests/unified-workspace-browser.test.mjs b/packages/webui/tests/unified-workspace-browser.test.mjs index 10c71e97d..fba81f7fa 100644 --- a/packages/webui/tests/unified-workspace-browser.test.mjs +++ b/packages/webui/tests/unified-workspace-browser.test.mjs @@ -111,7 +111,8 @@ test('sidebar follows sample 01 and Queue opens from the organization dashboard, await b.evaluate('document.querySelector("[data-org-queue]").click()'); await wait('location.hash === "#/orgs/ddigital/queue" && [...document.querySelectorAll("#bus-view h1")].some(h => h.textContent.trim() === "Queue")'); // Views not built yet open and say so. - for (const [route, title] of [['inbox', 'Inbox'], ['tasks', 'Tasks'], ['side-by-side', 'Side by side']]) { + // Inbox is built (U3, workspace-pages-browser.test.mjs). + for (const [route, title] of [['tasks', 'Tasks'], ['side-by-side', 'Side by side']]) { await b.evaluate(`location.hash = "#/orgs/ddigital/${route}"`); await wait(`document.getElementById("bus-view").innerText.includes("not built yet") && [...document.querySelectorAll("#bus-view h1")].some(h => h.textContent.trim() === ${JSON.stringify(title)})`); assert.doesNotMatch(await b.evaluate('document.getElementById("bus-view").innerText'), /error|failed/i, route); diff --git a/packages/webui/tests/workspace-pages-browser.test.mjs b/packages/webui/tests/workspace-pages-browser.test.mjs new file mode 100644 index 000000000..28cf3f143 --- /dev/null +++ b/packages/webui/tests/workspace-pages-browser.test.mjs @@ -0,0 +1,310 @@ +// U3 (#1873, PRD 1.20 REQ-WS-1..6): the cross-organization Dashboard, Projects and Inbox pages +// (samples 02, 04 and 05). Every bus here is a fake: two running organizations and one stopped, +// read through the real GET /api/workspace (workspace-read.mjs) and the real page code. +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 { browser } from './browser.mjs'; +import { close } from './fixture.mjs'; + +const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`); +const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString(); + +// acme and beta answer; gamma's bus is stopped. Decision ids are long so a shortened id would show. +const ACME_DECISION = 'dec-acme-7f3c9a21-5b8e-4d1f-9c2a-0e6b7d8f9a10'; +const BETA_DECISION = 'dec-beta-1a2b3c4d-5e6f-4a1b-8c9d-0e1f2a3b4c5d'; +function fixture({ pollMs, fail = {} } = {}) { + 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 }, + ]; + const DATA = { + acme: { + projects: [ + { id: 'p-site', repo: 'site', name: 'Website', archived: false, at: at(30) }, + { id: 'p-zeta', repo: 'zeta', name: 'Zeta API', archived: false, at: at(300) }, + { id: 'p-old', repo: 'old', name: 'Old brochure', archived: true, at: at(60 * 24 * 20) }, + ], + tasks: [{ task_ref: 'local:1', project_key: 'site', at: at(20), fields: { title: 'Hero copy', done: false, bucket: 'Doing' } }], + agents: [{ role: 'coder', holder_run: 'run-1', harness: 'claude', state: 'working', at: at(40), working: { since: at(40) } }], + claims: [], threads: [], + inbox: [{ id: ACME_DECISION, question: 'Ship the hero?', class: 'gated', blocking: true, raised_by_role: 'coder', task_ref: 'local:1', at: at(10), options: [{ key: 'yes', text: 'Ship it' }, { key: 'no', text: 'Hold' }] }], + decisions: [], + }, + beta: { + projects: [{ id: 'p-shop', repo: 'shop', name: 'Shop', archived: false, at: at(120) }], + tasks: [], agents: [{ role: 'pm', holder_run: 'run-9', harness: 'claude', state: 'waiting', at: at(15) }], claims: [], threads: [], + inbox: [{ id: BETA_DECISION, question: 'Pick a launch price', class: 'within-role', blocking: false, raised_by_role: 'pm', at: at(5), options: [{ key: 'low', text: 'Low' }] }], + decisions: [], + }, + }; + // fail: { org: [read names] } makes those reads refuse the way a disabled chat channel does. + const value = (id, name) => fail[id]?.includes(name) ? Promise.reject(Object.assign(new Error('off'), { code: 'channel-disabled' })) : Promise.resolve(DATA[id]?.[name] ?? (['usage', 'limits'].includes(name) ? {} : [])); + const opts = id => ({ + bus: { inbox: () => value(id, 'inbox'), agents: () => value(id, 'agents'), 'thread.claims': () => value(id, 'claims'), tasks: () => value(id, 'tasks'), usage: () => value(id, 'usage'), limits: () => value(id, 'limits'), decisions: () => value(id, 'decisions') }, + chat: { threads: () => value(id, 'threads'), projects: () => value(id, 'projects') }, + }); + const member = org => ({ + id: org.id, doc: { appearance: { theme: org.theme } }, + status: async () => (org.busHealthy ? { healthy: true, pid: 4242, boot: null } : { healthy: false, boot: { ok: false, at: at(90), lastGood: null, reason: 'stopped by the owner' } }), + options: () => opts(org.id), + }); + return { + list: async () => LIST, + members: async () => LIST.map(member), + resolve: async id => { + const org = LIST.find(o => o.id === id); if (!org) return null; + if (!org.busHealthy) return { busHealthy: false, reads: null, bus: {}, chat: { projects: async () => [], threads: async () => [] } }; + return { + busHealthy: true, + reads: { business: async () => ({ business: { id, human: 'jason', projects: DATA[id].projects.map(p => p.repo) } }), settings: async () => ({}), queue: async () => ({ rows: [] }), busStatus: async () => ({}) }, + bus: { messages: async () => ({ messages: [], unread: 0 }), agents: async () => [], 'thread.claims': async () => [], inbox: async () => DATA[id].inbox.map(d => ({ ...d, business: id, raised_by_run: 'run', routed_to: 'human' })), tasks: async () => [], instances: async () => ({ business: id, instances: {} }) }, + chat: { projects: async () => DATA[id].projects, threads: async () => [] }, + }; + }, + ...(pollMs ? { pollMs } : {}), + }; +} + +async function setup(t, { viewport = [1440, 900], hash = '/', workspaceTimeoutMs, fail } = {}) { + const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture({ fail }), log: () => {}, ...(workspaceTimeoutMs ? { workspaceTimeoutMs } : {}) }); + t.after(() => close(server)); + const b = await browser({ machine: false }); t.after(() => b.close()); + await b.viewport(...viewport); + const base = `http://127.0.0.1:${server.address().port}`; + await b.navigate(`${base}/#/orgs/acme${hash}`); + return { b, base, wait: waitFor(b), text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.innerText ?? null`) }; +} + +test('Dashboard renders every section across organizations, and a stopped one shows its state while the others render', async t => { + const { b, wait, text } = await setup(t); + await wait('document.querySelector("[data-ws-home] [data-ws-tiles]") && document.querySelectorAll("[data-ws-orgcard]").length === 3'); + // The Dashboard nav item is this page. + assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page] .t")?.textContent'), 'Dashboard'); + assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]").getAttribute("href")'), '#/'); + assert.equal(await text('#bus-view h1'), 'Dashboard'); + // Tiles: needs you, sessions, open tasks, projects, and an honest line for spend. + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-tile]")].map(e => e.dataset.wsTile)'), ['needs', 'sessions', 'tasks', 'projects', 'spend']); + assert.match(await text('[data-ws-tile=needs]'), /Needs you\s*2\s*items/i); + assert.match(await text('[data-ws-tile=projects]'), /Projects\s*4\s*3 active/i); + assert.match(await text('[data-ws-tile=spend]'), /No spend figures yet/); + assert.doesNotMatch(await text('[data-ws-tile=spend]'), /\$|\d/); + // Organization cards: two running with their read, the stopped one with its state and the time it was read. + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-orgcard]")].map(e => [e.dataset.wsOrgcard, e.dataset.state])'), [['acme', 'ok'], ['beta', 'ok'], ['gamma', 'down']]); + assert.match(await text('[data-ws-orgcard=gamma]'), /Gamma Home/); + assert.match(await text('[data-ws-orgcard=gamma]'), /down/); + assert.match(await text('[data-ws-orgcard=gamma]'), /stopped by the owner/); + assert.equal(await b.evaluate('document.querySelector("[data-ws-orgcard=beta] a").getAttribute("href")'), '#/orgs/beta/organization'); + assert.match(await text('[data-ws-home] .sub'), /2 of 3 organizations answered/); + assert.match(await text('[data-ws-home] .sub'), /Gamma Home down, read \d\d:\d\d/); + // Recent project activity across both running organizations, newest first, each linking into its org. + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-recent] a")].map(a => a.getAttribute("href"))'), ['#/orgs/acme/projects/p-site', '#/orgs/beta/projects/p-shop', '#/orgs/acme/projects/p-zeta']); + assert.match(await text('[data-ws-states]'), /Doing\s*1/); + assert.match(await text('[data-ws-states]'), /Done this week\s*0/); + // Needs you lists both organizations' decisions, newest raised first as the read orders them. + const needs = await b.evaluate('[...document.querySelectorAll("[data-ws-needs] a.q")].map(a => [a.textContent, a.getAttribute("href")])'); + assert.equal(needs.length, 2); + assert.ok(needs.some(([q, h]) => q === 'Ship the hero?' && h === `#/orgs/acme/inbox?d=${encodeURIComponent(`acme:${ACME_DECISION}`)}`), JSON.stringify(needs)); + assert.ok(needs.some(([q]) => q === 'Pick a launch price')); + // Sessions now: the working and the waiting role, each with its organization. + assert.match(await text('[data-ws-sessions]'), /coder/); + assert.match(await text('[data-ws-sessions]'), /pm/); + // The sidebar Inbox count follows the read across organizations. + assert.equal(await b.evaluate('document.querySelector("#sections a[href=\'#/inbox\'] .ws-n")?.textContent'), '2'); + // The per-organization board moved to #/board; the processing link goes there. + assert.equal(await b.evaluate('document.getElementById("processing-link").getAttribute("href")'), '#/board'); +}); + +test('Projects sorts and filters by each key, remembers the grouping, and rows open the project in its organization', async t => { + const { b, wait, text } = await setup(t, { hash: '/projects' }); + const names = 'JSON.stringify([...document.querySelectorAll("[data-ws-project]")].map(r => r.dataset.wsProject))'; + const settle = async (hash, expected) => { await wait(`location.hash === ${JSON.stringify(hash)} && ${names} === ${JSON.stringify(JSON.stringify(expected))}`); }; + await wait('document.querySelector("[data-ws-projects] [data-ws-table]")'); + assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page] .t")?.textContent'), 'Projects'); + // Default: active only, newest activity first, grouped by organization with the stopped one marked. + assert.equal(await b.evaluate(names), JSON.stringify(['acme:p-site', 'acme:p-zeta', 'beta:p-shop'])); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-group-org]")].map(r => r.dataset.wsGroupOrg)'), ['acme', 'beta', 'gamma']); + assert.match(await text('[data-ws-table] tr.ws-unread'), /Not read.*the bus/); + // Rows open the existing project page in their own organization. + assert.equal(await b.evaluate('document.querySelector("[data-ws-project=\'beta:p-shop\'] a.nm").getAttribute("href")'), '#/orgs/beta/projects/p-shop'); + // Sort by name (ascending), then again to reverse it. + await b.evaluate('document.querySelector("[data-ws-sort=name]").click()'); + await b.evaluate('document.querySelector("[data-ws-group=flat]").click()'); + await settle('#/orgs/acme/projects?sort=name', ['beta:p-shop', 'acme:p-site', 'acme:p-zeta']); + assert.equal(await b.evaluate('document.querySelector("[data-ws-table] th[aria-sort]").textContent.trim()'), 'Project↑'); + await b.evaluate('document.querySelector("[data-ws-sort=name]").click()'); + await settle('#/orgs/acme/projects?sort=name&order=desc', ['acme:p-zeta', 'acme:p-site', 'beta:p-shop']); + // Sort by organization and by status. + await b.evaluate('document.querySelector("[data-ws-sort=org]").click()'); + await wait('location.hash === "#/orgs/acme/projects?sort=org" && document.querySelector("[data-ws-sort=org]").getAttribute("aria-pressed") === "true"'); + assert.deepEqual(JSON.parse(await b.evaluate(names)).map(k => k.split(':')[0]), ['acme', 'acme', 'beta']); + await b.evaluate('document.querySelector("[data-ws-sort=status]").click()'); + await wait('location.hash === "#/orgs/acme/projects?sort=status" && document.querySelector("[data-ws-sort=status]").getAttribute("aria-pressed") === "true"'); + // Filter by status: archived and both. + await b.evaluate('(() => { const s = document.querySelector("[data-ws-status]"); s.value = "archived"; s.dispatchEvent(new Event("change", { bubbles: true })); })()'); + await settle('#/orgs/acme/projects?sort=status&status=archived', ['acme:p-old']); + await b.evaluate('(() => { const s = document.querySelector("[data-ws-status]"); s.value = "active,archived"; s.dispatchEvent(new Event("change", { bubbles: true })); })()'); + await wait('document.querySelectorAll("[data-ws-project]").length === 4'); + // Filter by session state: only Website has a decision waiting. + await b.evaluate('(() => { const s = document.querySelector("[data-ws-state]"); s.value = "waiting"; s.dispatchEvent(new Event("change", { bubbles: true })); })()'); + await wait(`${names} === ${JSON.stringify(JSON.stringify(['acme:p-site']))}`); + await b.evaluate('(() => { const s = document.querySelector("[data-ws-state]"); s.value = ""; s.dispatchEvent(new Event("change", { bubbles: true })); })()'); + await wait('document.querySelectorAll("[data-ws-project]").length === 4'); + // Filter by organization chip, then back to all. + await b.evaluate('document.querySelector("[data-ws-org=beta]").click()'); + await wait(`${names} === ${JSON.stringify(JSON.stringify(['beta:p-shop']))} && document.querySelector("[data-ws-org=beta]").getAttribute("aria-pressed") === "true"`); + assert.match(location(await b.evaluate('location.hash')), /org=beta/); + await b.evaluate('document.querySelector("[data-ws-org=\'\']").click()'); + await wait('document.querySelectorAll("[data-ws-project]").length === 4'); + // Filter by name: typing keeps focus and the caret in the box while the list narrows. + await b.evaluate('(() => { const i = document.querySelector("[data-ws-name]"); i.focus(); i.value = "zet"; i.dispatchEvent(new Event("input", { bubbles: true })); })()'); + await wait(`${names} === ${JSON.stringify(JSON.stringify(['acme:p-zeta']))}`); + assert.deepEqual(await b.evaluate('[document.activeElement?.dataset.focusKey, document.activeElement.value, document.activeElement.selectionStart]'), ['proj-name', 'zet', 3]); + // Flat mode shows an Organization column and names the stopped organization; the choice is the + // sidebar's remembered one and survives a reload. + assert.equal(await b.evaluate('document.querySelector("[data-ws-table]").dataset.grouping'), 'flat'); + assert.match(await text('[data-ws-unread]'), /Gamma Home down/); + assert.equal(await b.evaluate('document.querySelector("#workspace-nav [data-group=flat]").getAttribute("aria-pressed")'), 'true'); + assert.equal(await b.evaluate('localStorage.getItem("mosaic-workspace-project-grouping-v1")'), 'flat'); + await b.evaluate('location.reload()'); + await wait('document.querySelector("[data-ws-table]")?.dataset.grouping === "flat" && document.querySelectorAll("[data-ws-project]").length === 1 && document.querySelector("#workspace-nav [data-group=flat]")?.getAttribute("aria-pressed") === "true"'); + // The sidebar's toggle switches this page back. + await b.evaluate('document.querySelector("#workspace-nav [data-group=org]").click()'); + await wait('document.querySelector("[data-ws-table]")?.dataset.grouping === "org" && document.querySelector("[data-ws-group=org]").getAttribute("aria-pressed") === "true"'); +}); +const location = hash => decodeURIComponent(hash); + +test('Inbox lists both organizations, copies a command with --org and the full id, and deciding needs human proof', async t => { + const { b, base, wait, text } = await setup(t, { hash: '/inbox' }); + await wait('document.querySelectorAll("[data-ws-item]").length === 2 && document.querySelector("[data-ws-insp]")'); + assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page] .t")?.textContent'), 'Inbox'); + assert.equal(await b.evaluate('document.querySelector("[data-not-built]")'), null); + const items = await b.evaluate('[...document.querySelectorAll("[data-ws-item]")].map(r => [r.dataset.wsItem, r.innerText])'); + assert.deepEqual(items.map(([k]) => k).sort(), [`acme:${ACME_DECISION}`, `beta:${BETA_DECISION}`]); + // Each row names its organization, project and session. + const acme = items.find(([k]) => k.startsWith('acme'))[1]; + assert.match(acme, /Acme Studio/); assert.match(acme, /Website/); assert.match(acme, /coder/); assert.match(acme, /gated/); + const beta = items.find(([k]) => k.startsWith('beta'))[1]; + assert.match(beta, /Beta Works/); assert.match(beta, /No project/); assert.match(beta, /pm/); + assert.match(await text('[data-ws-unread]'), /Gamma Home down/); + // Tabs the data can't back say so. + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-inbox] .ws-seg button")].map(x => [x.textContent, x.disabled])'), [['Needs you', false], ['Seen', true], ['Answered', true]]); + assert.match(await text('[data-ws-inbox]'), /not built yet/); + // Select the acme decision; the inspector shows it, and the selection stays in the hash. + // A pointer click focuses the link before it activates; .click() alone does not. + await b.evaluate(`(() => { const a = document.querySelector('[data-ws-select="acme:${ACME_DECISION}"]'); a.focus(); a.click(); })()`); + await wait(`document.querySelector("[data-ws-insp]")?.dataset.wsInsp === ${JSON.stringify(`acme:${ACME_DECISION}`)}`); + assert.equal(await b.evaluate('document.activeElement?.dataset.focusKey'), `item:acme:${ACME_DECISION}`); + const cmds = await b.evaluate('[...document.querySelectorAll("[data-ws-cmds] [data-copy]")].map(x => [x.dataset.copy, x.previousElementSibling.tagName, x.previousElementSibling.textContent])'); + assert.deepEqual(cmds, [[`mosaic decide ${ACME_DECISION} yes --org acme`, 'CODE', `mosaic decide ${ACME_DECISION} yes --org acme`], [`mosaic decide ${ACME_DECISION} no --org acme`, 'CODE', `mosaic decide ${ACME_DECISION} no --org acme`]]); + // Copy puts the full command on the clipboard (or selects it when there is none) and says so. + await b.evaluate('document.querySelector("[data-ws-cmds] [data-copy]").click()'); + await wait('document.getElementById("copy-status")?.textContent.length > 0'); + const status = await text('#copy-status'); + assert.ok(status.includes(`mosaic decide ${ACME_DECISION} yes --org acme`) || /clipboard is unavailable/.test(status), status); + // An answer opens the existing per-organization decision page. + assert.equal(await b.evaluate('document.querySelector("[data-ws-insp] .ws-opts a").getAttribute("href")'), `#/orgs/acme/inbox/${ACME_DECISION}`); + // Without a signed-in human session and its proof, the per-organization decide path refuses. + const refused = await b.evaluate(`(async () => { const r = await fetch('/api/orgs/acme/decisions/${ACME_DECISION}/confirmation', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ choice: 'yes' }) }); return [r.status, (await r.json().catch(() => ({}))).error ?? null]; })()`); + assert.ok(refused[0] >= 400 && refused[0] < 500, JSON.stringify(refused)); + // The decision page itself offers no answer controls without that proof. + await b.navigate(`${base}/#/orgs/acme/inbox/${ACME_DECISION}`); + await wait('[...document.querySelectorAll("#bus-view h1")].length > 0 && !document.querySelector("#bus-view .loading")'); + assert.equal(await b.evaluate('document.querySelector("#decide-section [data-decide]")'), null); + // Filter to one organization. + await b.navigate(`${base}/#/orgs/acme/inbox`); + await wait('document.querySelectorAll("[data-ws-item]").length === 2'); + await b.evaluate('document.querySelector("[data-ws-org=beta]").click()'); + await wait(`document.querySelectorAll("[data-ws-item]").length === 1 && document.querySelector("[data-ws-item]").dataset.wsItem === ${JSON.stringify(`beta:${BETA_DECISION}`)}`); +}); + +test('A poll repaints in place: focus, caret and scroll stay where they were', async t => { + const { b, wait } = await setup(t, { hash: '/projects', viewport: [1000, 420] }); + await wait('document.querySelector("[data-ws-table]") && document.querySelectorAll("[data-ws-project]").length === 3'); + assert.ok(await b.evaluate('window.MosaicWorkspace.pollMs') >= 1000); + // Focus a row link, scroll the page, and repaint as a poll does. + await b.evaluate('document.querySelector("[data-ws-project=\'beta:p-shop\'] a.nm").focus({ preventScroll: true }); (document.scrollingElement.scrollTop = 120); document.getElementById("main").scrollTop = 120;'); + const before = await b.evaluate('[document.scrollingElement.scrollTop, document.getElementById("main").scrollTop]'); + assert.ok(before.some(v => v > 0), `nothing scrolled: ${before}`); + await b.evaluate('window.__marker = document.querySelector("[data-ws-table]"); document.dispatchEvent(new CustomEvent("mosaic-workspace-render"))'); + await wait('document.querySelector("[data-ws-table]") !== window.__marker'); + assert.equal(await b.evaluate('document.activeElement?.dataset.focusKey'), 'prow:beta:p-shop'); + assert.deepEqual(await b.evaluate('[document.scrollingElement.scrollTop, document.getElementById("main").scrollTop]'), before); + // The search box keeps its caret across a repaint. + await b.evaluate('(() => { const i = document.querySelector("[data-ws-name]"); i.focus(); i.value = "shop"; i.dispatchEvent(new Event("input", { bubbles: true })); })()'); + await wait('location.hash.includes("name=shop") && document.querySelectorAll("[data-ws-project]").length === 1 && document.activeElement?.dataset.focusKey === "proj-name"'); + await b.evaluate('document.activeElement.setSelectionRange(2, 2)'); + await b.evaluate('window.__marker = document.querySelector("[data-ws-table]"); document.dispatchEvent(new CustomEvent("mosaic-workspace-render"))'); + await wait('document.querySelector("[data-ws-table]") !== window.__marker'); + assert.deepEqual(await b.evaluate('[document.activeElement?.dataset.focusKey, document.activeElement.selectionStart]'), ['proj-name', 2]); + // The Dashboard and the Inbox repaint the same way. + await b.evaluate('location.hash = "#/orgs/acme/"'); + await wait('document.querySelectorAll("[data-ws-orgcard]").length === 3'); + await b.evaluate('document.querySelector("[data-ws-orgcard=beta] a").focus()'); + await b.evaluate('window.__marker = document.querySelector("[data-ws-orgs]"); document.dispatchEvent(new CustomEvent("mosaic-workspace-render"))'); + await wait('document.querySelector("[data-ws-orgs]") !== window.__marker'); + assert.equal(await b.evaluate('document.activeElement?.dataset.focusKey'), 'orgcard:beta'); + // No loading view replaced the page during that repaint. + assert.equal(await b.evaluate('document.querySelector("#bus-view .loading")'), null); +}); + +test('Phone width: no horizontal scroll on any of the three pages, and the drawer opens and closes', async t => { + const { b, wait } = await setup(t, { viewport: [390, 844] }); + for (const [hash, ready] of [['/', '[data-ws-orgcard]'], ['/projects', '[data-ws-project]'], ['/inbox', '[data-ws-item]']]) { + await b.evaluate(`location.hash = "#/orgs/acme${hash}"`); + await wait(`document.querySelector(${JSON.stringify(ready)})`); + assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, hash); + } + await b.evaluate('document.getElementById("nav-open").click()'); + await wait('document.getElementById("nav-open").getAttribute("aria-expanded") === "true"'); + assert.equal(await b.evaluate('getComputedStyle(document.getElementById("console-nav")).visibility !== "hidden" && document.getElementById("console-nav").getBoundingClientRect().right > 0'), true); + await b.evaluate('document.getElementById("nav-close").click()'); + await wait('document.getElementById("nav-open").getAttribute("aria-expanded") === "false"'); + // A sidebar link closes the drawer and opens its page. + await b.evaluate('document.getElementById("nav-open").click()'); + await wait('document.getElementById("nav-open").getAttribute("aria-expanded") === "true"'); + await b.evaluate('document.querySelector("#sections a[href=\'#/projects\']").click()'); + await wait('location.hash === "#/orgs/acme/projects" && document.querySelector("[data-ws-project]")'); + assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true); + // An inbox row at phone width puts its source on its own line above the question. + await b.evaluate('location.hash = "#/orgs/acme/inbox"'); + await wait('document.querySelector("[data-ws-item] .ws-msrc")'); + assert.equal(await b.evaluate(`(() => { const r = document.querySelector('[data-ws-item]'), s = r.querySelector('.ws-msrc').getBoundingClientRect(), q = r.querySelector('a.q').getBoundingClientRect(); return s.height > 0 && s.bottom <= q.top + 1; })()`), true, 'source above question'); +}); + +test('A read that an answering organization could not make says not read, never zero', async t => { + // beta answers, but its project and inbox reads refuse. + const { b, wait, text } = await setup(t, { fail: { beta: ['projects', 'inbox'] } }); + await wait('document.querySelector("[data-ws-tiles]")'); + assert.match(await text('[data-ws-tile=projects] [data-ws-miss=projects]'), /Not read in Beta Works \(the chat channel is off\)/); + assert.match(await text('[data-ws-tile=needs] [data-ws-miss=needs]'), /Not read in Beta Works/); + assert.match(await text('[data-ws-miss=recent]'), /Not read in Beta Works/); + assert.match(await text('[data-ws-miss=needs]:not([data-ws-tile] *)'), /Not read in Beta Works/); + assert.doesNotMatch(await text('.ws-home .sub'), /and \d+ projects?/, 'no project total when a project read failed'); + // Projects, grouped: beta's group says why and shows no count or "No projects match". + await b.evaluate('location.hash = "#/orgs/acme/projects"'); + await wait('document.querySelector("[data-ws-group-org=beta]")'); + assert.equal(await b.evaluate(`document.querySelector('[data-ws-group-org=beta] .ws-n')`), null); + const betaRow = await b.evaluate(`document.querySelector('[data-ws-group-org=beta]').nextElementSibling.innerText`); + assert.match(betaRow, /Projects not read: the chat channel is off/); + assert.match(await text('[data-ws-org=beta] .n'), /not read/i); + // Flat: the note names it. + await b.evaluate('document.querySelector("[data-ws-group=flat]").click()'); + await wait('document.querySelector("[data-ws-miss=projects]")'); + assert.match(await text('[data-ws-miss=projects]'), /Not read in Beta Works/); + // Inbox: the note names it, and the chip carries no count. + await b.evaluate('location.hash = "#/orgs/acme/inbox"'); + await wait('document.querySelector("[data-ws-miss=inbox]")'); + assert.match(await text('[data-ws-miss=inbox]'), /Not read in Beta Works \(the chat channel is off\)/); + assert.match(await text('[data-ws-org=beta] .n'), /not read/i); + assert.equal(await b.evaluate('document.querySelectorAll("[data-ws-item]").length'), 1); +}); + +test('When every answering organization failed a read, its tile says Not read instead of a number', async t => { + const { wait, text } = await setup(t, { fail: { acme: ['projects'], beta: ['projects'] } }); + await wait('document.querySelector("[data-ws-tiles]")'); + assert.match(await text('[data-ws-tile=projects]'), /Not read/i); + assert.equal(await text('[data-ws-tile=projects] .ws-big'), null); +});