From 8710cc0e1ed4eaa5344028d82a673dc2ceaca968 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Mon, 9 Nov 2026 19:46:54 -0600 Subject: [PATCH] feat(webui): U2 unified workspace sidebar, org dashboard and agents grid (#1873) Finishes the U2 WIP (37b0891a3) to samples 01, 03 and 08 of the 2026-11-09 unified workspace set: - workspace.js: sidebar Organizations and Projects groups (collapsible, state remembered), the org dashboard, the Agents levels. - workspace-data.js: every read these screens make, GET no-store, redirect manual; a refused read shows unavailable for that part only. - shell.css: the html[data-organizations] .ws-* block from the sample. - bus.js: org-mode sidebar order, pinned Settings, no project tree under Projects, focus kept across repaint. - Honest empty states where the Console has no data (KPIs, metrics, kind). - Tests: unified-workspace-browser (10), picker/delete/switch browser tests follow the sidebar, browser.test script pin. --- packages/webui/src/public/bus.js | 61 +++- packages/webui/src/public/index.html | 4 +- packages/webui/src/public/shell.css | 203 ++++++++++++ packages/webui/src/public/workspace-data.js | 21 ++ packages/webui/src/public/workspace.js | 277 ++++++++++++++++ packages/webui/src/serve.mjs | 2 +- packages/webui/tests/browser.test.mjs | 4 +- .../webui/tests/org-delete-browser.test.mjs | 11 +- .../tests/org-new-entry-browser.test.mjs | 11 +- .../webui/tests/org-switch-browser.test.mjs | 27 +- .../tests/unified-workspace-browser.test.mjs | 311 ++++++++++++++++++ 11 files changed, 900 insertions(+), 32 deletions(-) create mode 100644 packages/webui/src/public/workspace-data.js create mode 100644 packages/webui/src/public/workspace.js create mode 100644 packages/webui/tests/unified-workspace-browser.test.mjs diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index 5d7e16edc..a1e5b4bf9 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -264,9 +264,32 @@ // ---------------------------------------------------------------- views let inboxCount = null, messageCount = null; + // Organization mode (sample 01): Dashboard, Inbox, Tasks, Projects, Side by side, Agents and + // Assistant, with Settings pinned to the foot of the sidebar. Queue opens from the organization + // dashboard and Docs from its Docs row, so neither is a sidebar item here. + function orgSections(route) { + const nav = $('console-nav'); + let foot = $('sections-foot'); + if (!foot) { foot = document.createElement('div'); foot.id = 'sections-foot'; foot.className = 'ws-foot'; nav.append(foot); } + const active = document.activeElement; + const focused = $('sections').contains(active) || foot.contains(active) ? active.getAttribute('href') : null; + const icon = id => window.MosaicWorkspace?.icon?.(id) ?? ``; + const n = (count, what) => count > 0 ? `${count}` : ''; + const items = [['/', 'Dashboard', '', 'board'], ['/inbox', 'Inbox', n(inboxCount?.open, 'open for you'), 'inbox'], ['/tasks', 'Tasks', '', 'tasks'], ['/projects', 'Projects', '', 'folder'], ['/side-by-side', 'Side by side', '', 'columns'], ['/agents', 'Agents', '', 'agents'], ['/messages', 'Assistant', n(messageCount, 'unread messages'), 'talk']]; + const link = ([h, l, extra, id]) => { + const cur = h === '/' ? (route === '/' || route === '/board') : route.startsWith(h) || (h === '/projects' && route.startsWith('/chat')) || (h === '/tasks' && route.startsWith('/trail/task')) || (h === '/inbox' && (route.startsWith('/trail/decision') || route.startsWith('/trail/message'))); + return `${icon(id)}${l}${extra}`; + }; + // No project tree under Projects here: the sidebar's Projects group lists every organization's + // projects and opens the same project page, which lists its conversations. + $('sections').innerHTML = items.map(item => `
  • ${link(item)}
  • `).join(''); + foot.innerHTML = link(['/settings', 'Settings', '', 'settings']); + if (focused) [...$('sections').querySelectorAll('a[href]'), ...foot.querySelectorAll('a[href]')].find(a => a.getAttribute('href') === focused)?.focus({ preventScroll: true }); + } function sections(route) { + if (window.MosaicOrg) return orgSections(route); const focused = $('sections').contains(document.activeElement) ? document.activeElement.getAttribute('href') : null; - const items = [['/', 'Dashboard', '', 'board'], ['/projects', 'Projects', '', 'inbox'], ['/inbox', 'Inbox', inboxCount?.open > 0 ? `${inboxCount.open}${inboxCount.blocking ? ` ${blockChip(`${inboxCount.blocking} blocking`)}` : ''}` : '', 'inbox'], ['/messages', 'Messages', messageCount > 0 ? `${messageCount}` : '', 'talk'], ['/tasks', 'Tasks', '', 'tasks'], ['/agents', 'Agents', '', 'agents'], ['/queue', 'Queue', '', 'queue'], ['/docs', 'Docs', '', 'library'], ['/settings', 'Settings', '', 'settings']]; + const items = [['/', 'Dashboard', '', 'board'], ['/projects', 'Projects', '', 'inbox'], ['/inbox', 'Inbox', inboxCount?.open > 0 ? `${inboxCount.open}${inboxCount.blocking ? ` ${blockChip(`${inboxCount.blocking} blocking`)}` : ''}` : '', 'inbox'], ['/messages', 'Assistant', messageCount > 0 ? `${messageCount}` : '', 'talk'], ['/tasks', 'Tasks', '', 'tasks'], ['/agents', 'Agents', '', 'agents'], ['/queue', 'Queue', '', 'queue'], ['/docs', 'Docs', '', 'library'], ['/settings', 'Settings', '', 'settings']]; $('sections').innerHTML = items.map(([h, l, extra, icon]) => { const cur = h === '/' ? (route === '/' || route === '/board') : route.startsWith(h) || (h === '/projects' && route.startsWith('/chat')) || (h === '/tasks' && route.startsWith('/trail/task')) || (h === '/inbox' && (route.startsWith('/trail/decision') || route.startsWith('/trail/message'))); return `
  • ${l}${extra ? ` ${extra}` : ''}${h === '/projects' ? '
    ' : ''}
  • `; @@ -668,7 +691,12 @@ } } async function agentsView(get) { - const claims = await get('agents'); + let claims; + try { claims = await get('agents'); } catch (err) { + if (!window.MosaicOrg || err.code === 'signed-out') throw err; + if (refusal(err)) forget(); + return `${await window.MosaicWorkspace.agentGrid()}`; + } let instances = null, threads = []; if (!isTester) { const reads = await Promise.allSettled([get('instances'), get.api('chat/threads')]); @@ -683,7 +711,9 @@ for (const claim of claims) if (claim.holder_run && claim.role && !holders.has(claim.holder_run)) holders.set(claim.holder_run, claim.role); const threadSection = await threadClaimsSection(get, holders, threads, !!instances, running); const rows = claims.map(c => `${txt(c.role)}${stateMark(c.state)}${c.working ? `${esc(plural(c.working.messages, 'message'))} since ${when(c.working.since)}` : ''}${attention(c)}${txt(holders.get(c.holder_run) || c.role)}run ${txt(c.holder_run)}${!instances ? ', running status unavailable' : running.has(c.holder_run) ? '' : ', not running'}${txt(c.harness)}${c.address ? `${txt(c.address)}` : ''}${when(c.at)}`).join(''); - return `${head('Agents', readNote(get))} + // Organization mode (sample 08): the levels grid carries the page heading; held roles follow. + const top = window.MosaicOrg ? await window.MosaicWorkspace.agentGrid(readNote(get)) : head('Agents', readNote(get)); + return `${top}

    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} @@ -753,7 +783,7 @@ const b = (await get.api('business')).business || {}; const orgs = window.MosaicOrg ? await window.MosaicOrg.list : null; if (orgs) await configRead; // orgSetup decides the "New organization" link - const picker = orgs ? `

    Organization

    ${orgSetup ? `

    New organization

    ` : ''}
    ` : ''; + const picker = ''; const instances = Array.isArray(b.instances) ? b.instances : [], creds = Array.isArray(b.credentials) ? b.credentials : [], actions = Array.isArray(b.actions) ? b.actions : []; const launch = b.launch || {}; const authKnown = instances.some(i => i.authority); @@ -1172,7 +1202,7 @@ const label=pages.find(([id])=>id===page)?.[1] || 'Appearance'; const isDirty=id=>(id==='routing'&&routesDraft)||(id==='limits'&&settingsInputs)||(id==='assistant'&&(Object.keys(assistantDrafts).length||Object.keys(nameDrafts).length))||(id==='agents'&&(instanceDrafts.add||instanceDrafts.change)); const dot='unsaved changes'; - const links=pages.map(([id,name],i)=>`${i===0?'
    Your browser
    ':i===1?'
    This instance
    ':''}${name}${isDirty(id)?dot:''}`).join(''); + const links=pages.map(([id,name],i)=>`${i===0?'
    Your browser
    ':i===1?'
    This instance
    ':''}${name}${isDirty(id)?dot:''}`).join('') + (!isTester ? '
    Members and invites not built
    ' : ''); return `${head('Settings','Your browser and this instance.')}

    ${label}

    ${helper}

    ${readonlyPage(page)?'

    Read only. Saving requires signed-in send mode.

    ':''}${body}
    `; } async function settingsView(get, page='appearance') { @@ -1412,10 +1442,20 @@ // ---------------------------------------------------------------- router // #/ and anything that is not a #/ route is the control board; the rest is this file's. const routeOf = () => window.MosaicOrg?.route() ?? (location.hash.startsWith('#/') ? location.hash.slice(1) : '/'); + // A one-line scope note right under a view's page heading. + function afterHead(html, note) { + const start = html.indexOf('
    '), end = start < 0 ? -1 : html.indexOf('
    ', start); + const line = `

    ${esc(note)}

    `; + return end < 0 ? `${line}${html}` : `${html.slice(0, end + 12)}${line}${html.slice(end + 12)}`; + } function view(get, path, q, opts, current) { 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 (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 === '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.`); if (a === 'messages' && n === 1) return messagesView(get, q); @@ -1441,6 +1481,7 @@ function keep() { const a = document.activeElement, view = $('bus-view'); return { + focusKey: view.contains(a) ? a.dataset?.focusKey || (a.hasAttribute?.('data-bus-restart') ? 'bus-restart' : null) : null, href: view.contains(a) ? a.getAttribute('href') : null, copy: view.contains(a) ? a.dataset?.copy : null, retry: view.contains(a) && a.hasAttribute?.('data-retry'), mirror: view.contains(a) ? a.dataset?.mirror : null, h1: view.contains(a) && a.tagName === 'H1', settingsChoice: view.contains(a) && a.type==='radio' ? [a.name,a.value] : null, settingsField: view.contains(a) && a.closest('.settings-content') && (a.dataset?.instanceField || a.dataset?.assistantField || a.dataset?.route || a.dataset?.setting) ? {form:a.closest('form')?.id || null, instance:a.closest('[data-instance]')?.dataset.instance || null, key:a.dataset.instanceField?'instanceField':a.dataset.assistantField?'assistantField':a.dataset.route?'route':'setting', value:a.dataset.instanceField || a.dataset.assistantField || a.dataset.route || a.dataset.setting} : null, @@ -1459,7 +1500,10 @@ const dec = k.decide ? $('bus-view').querySelector(k.decide === 'status' ? '#decide-status' : `[data-decide="${k.decide}"]`) : null; const choice=k.settingsChoice && [...$('bus-view').querySelectorAll('input[type=radio]')].find(x=>x.name===k.settingsChoice[0]&&x.value===k.settingsChoice[1]); 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)); - 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];} } + // 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 }); + 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 }); else if (el && (k.href || k.copy || k.retry || k.mirror || k.field || k.send)) { @@ -1557,7 +1601,7 @@ let html, state = 'fresh'; const live = reader(true); try { - if (path !== '/messages' && !['/settings','/settings/appearance','/settings/model-proxy','/settings/organizations'].includes(path)) { + if (path !== '/organization' && !(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; } } @@ -1578,6 +1622,7 @@ $('bus-view').innerHTML = html; shown = route; syncAppearance(true); if (path.startsWith('/docs/')) paintDoc(); + if (path === '/organization') window.MosaicConsole?.attachBus(document.querySelector('[data-dashboard-bus]')); if (path === '/settings/model-proxy') proxyCleanup=window.MosaicProxy.mount(); if (path === '/settings/organizations') orgCleanup=window.MosaicOrgCreate.mount(); sections(path); @@ -1639,7 +1684,7 @@ // Ctrl+K opens it. It lists the views, and the decisions and tasks from the last inbox and // tasks reads (opening it reads both again, GET only). Enter goes; Esc closes and puts focus // back where it was. It only navigates. - const VIEWS = [['#/', 'Dashboard'], ['#/projects', 'Projects'], ['#/inbox', 'Inbox'], ['#/messages', 'Messages'], ['#/tasks', 'Tasks'], ['#/agents', 'Agents'], ['#/queue', 'Queue'], ['#/settings/business', 'Business'], ['#/docs', 'Docs'], ['#/settings', 'Settings'], ['#/settings/display', 'Sidebar display']]; + const VIEWS = [['#/', 'Dashboard'], ['#/projects', 'Projects'], ['#/inbox', 'Inbox'], ['#/messages', 'Assistant'], ['#/tasks', 'Tasks'], ['#/agents', 'Agents'], ['#/queue', 'Queue'], ['#/settings/business', 'Business'], ['#/docs', 'Docs'], ['#/settings', 'Settings'], ['#/settings/display', 'Sidebar display']]; let pkAll = [], pkShown = [], pkAt = 0, pkBack = null; function pkItems() { const decisions = (last.get('inbox')?.rows || []).map(d => ({ href: `#/inbox/${enc(d.id)}`, label: first(d.question), group: `decision ${short(d.id)}` })); diff --git a/packages/webui/src/public/index.html b/packages/webui/src/public/index.html index 8c522cd6a..186c62623 100644 --- a/packages/webui/src/public/index.html +++ b/packages/webui/src/public/index.html @@ -7,7 +7,7 @@ - + @@ -19,7 +19,7 @@
    +

    Board project filter

    Loading projects…

    Select a project to filter sessions. Waiting on you always shows all projects.

    Dashboard

    Business overview

    Loading board…

    Held roles –

    The stack's seats: each role a run holds on the bus, from the bus agents read. Machine sessions are under Show machine sessions.

    Reading the held roles.
    diff --git a/packages/webui/src/public/shell.css b/packages/webui/src/public/shell.css index 2377a26f3..4a735322d 100644 --- a/packages/webui/src/public/shell.css +++ b/packages/webui/src/public/shell.css @@ -351,3 +351,206 @@ body:not(:has(.project-chat)) .content { padding-bottom:calc(22px + var(--foot-h .settings-content:has(.route-actions){padding-bottom:100px} } .assistant-form textarea[data-assistant-field="vars"] { field-sizing:content; min-height:6em; max-height:16em; overflow-y:auto; } +/* Unified workspace, organization mode (PRD 1.20, U2). The sample 01, 03 and 08 layouts, ported + from docs/design/samples/2026-11-09-unified-workspace/workspace.css with ws- names, so nothing + collides with the Console's own .btn, .chip, .panel, .split, .label or .cfg. */ +html[data-organizations]{--glyph:"DejaVu Sans","Segoe UI Symbol","Apple Symbols","Noto Sans Symbols 2",var(--font)} +@media (min-width:960px){html[data-organizations]{--sidebar-width:240px}} +/* An organization's colour for the page's mode: workspace.js sets the three pairs inline. */ +html[data-organizations] .ws-o{--org:var(--org-l);--org-on:var(--org-on-l)} +@media (prefers-color-scheme:dark){html[data-organizations]:not([data-mode="light"]):not([data-mode="dim"]) .ws-o{--org:var(--org-d);--org-on:var(--org-on-d)}} +html[data-organizations][data-mode="dark"] .ws-o{--org:var(--org-d);--org-on:var(--org-on-d)} +html[data-organizations][data-mode="dim"] .ws-o{--org:var(--org-m);--org-on:var(--org-on-m)} +html[data-organizations] .ws-sr{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap} +html[data-organizations] .ws-label{font-size:11px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--muted)} +html[data-organizations] .ws-line{margin:0;padding:3px 8px 3px 10px;font-size:12px;color:var(--muted);list-style:none} + +/* Sidebar (sample 01). */ +html[data-organizations] .tree{padding:10px 8px 14px;gap:2px} +html[data-organizations] #project-tree{border-bottom:0;padding-bottom:0} +html[data-organizations] .drawer-head{background:var(--nav-surface,var(--surface))} +html[data-organizations] #workspace-nav{display:flex;flex-direction:column;gap:2px;min-width:0;border:0;padding:0} +html[data-organizations] .s1-sections{display:grid;gap:2px;flex-basis:auto;overflow:visible;padding:0} +html[data-organizations] .s1-sections>li{width:100%;flex:none} +html[data-organizations] .ws-nav,html[data-organizations] .s1-section.ws-nav{display:flex;align-items:center;gap:9px;padding:5px 8px;min-height:0;min-width:0;border:0;border-radius:var(--r);box-shadow:none;background:transparent;color:var(--text);text-decoration:none;font:600 13.5px/1.5 var(--font);flex-wrap:nowrap;white-space:nowrap} +html[data-organizations] .ws-nav:hover{background:var(--raised)} +html[data-organizations] .ws-nav[aria-current=page],html[data-organizations] .s1-section.ws-nav[aria-current=page]{background:color-mix(in srgb,var(--action) 13%,var(--surface));box-shadow:none;color:var(--strong)} +html[data-organizations] .ws-nav svg.i{width:18px;height:18px;stroke-width:1.75;color:inherit} +html[data-organizations] .ws-nav[aria-current=page] svg.i{color:var(--action)} +html[data-organizations] .ws-nav .t{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +html[data-organizations] .ws-nav.sel{color:var(--strong)} +html[data-organizations] .ws-n{margin-left:auto;font:600 11px var(--mono);color:var(--muted);font-variant-numeric:tabular-nums} +html[data-organizations] .ws-n.hot{color:var(--surface);background:var(--danger);border-radius:999px;padding:0 6px} +html[data-organizations] .ws-hr{border:0;border-top:1px solid var(--line);margin:6px 4px;width:auto} +html[data-organizations] .ws-foot{margin-top:auto;padding-top:8px;border-top:1px solid var(--line)} +html[data-organizations] .ws-grp{display:flex;flex-direction:column;gap:1px} +html[data-organizations] .ws-grp-h{display:flex;align-items:center;gap:6px;padding:10px 8px 4px;color:var(--muted)} +html[data-organizations] .ws-grp-t{display:flex;align-items:center;gap:6px;flex:1;min-width:0;padding:0;margin:0;border:0;background:none;color:inherit;font:inherit;cursor:pointer;text-align:left} +html[data-organizations] .ws-grp-t .ws-label{flex:1} +html[data-organizations] .ws-grp-h>.ws-label{flex:1} +html[data-organizations] .ws-grp-h svg.i{width:14px;height:14px;transition:transform .15s} +html[data-organizations] .ws-grp-t[aria-expanded=false] svg.chev{transform:rotate(-90deg)} +html[data-organizations] .ws-grp-h .ws-n{margin-left:0} +html[data-organizations] .ws-add{display:inline-grid;place-items:center;flex:none;width:22px;height:22px;border-radius:var(--r);color:var(--muted);border:1px solid var(--line)} +html[data-organizations] .ws-add:hover{background:var(--raised);color:var(--strong)} +html[data-organizations] .ws-marks{display:flex;gap:4px;padding:0 8px 6px 28px} +html[data-organizations] .ws-orgs{display:flex;flex-direction:column;gap:1px;list-style:none;margin:0;padding:0} +html[data-organizations] .ws-orgs[hidden]{display:none} +html[data-organizations] .ws-project-list[hidden]{display:none} +html[data-organizations] .ws-seg{display:inline-flex;margin-left:auto;border:1px solid var(--line);border-radius:var(--r);overflow:hidden;background:var(--surface)} +html[data-organizations] .ws-seg>button{border:0;background:none;padding:2px 8px;color:var(--muted);font:600 12px/1.5 var(--font);display:inline-flex;align-items:center;white-space:nowrap;cursor:pointer;min-height:0} +html[data-organizations] .ws-seg.xs>button{padding:0 6px;font-size:11px} +html[data-organizations] .ws-seg [aria-pressed=true]{background:var(--action);color:var(--onAction)} +html[data-organizations] .ws-pgroup{display:flex;flex-direction:column;gap:1px;margin-bottom:4px} +html[data-organizations] .ws-pgroup-h{display:flex;align-items:center;gap:7px;padding:4px 8px 2px;font-size:12px;font-weight:700;color:var(--strong)} +html[data-organizations] .ws-pgroup-h .t{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +html[data-organizations] .ws-projs{margin-left:17px;border-left:2px solid var(--org);display:flex;flex-direction:column;gap:1px} +html[data-organizations] .ws-proj{padding:3px 8px 3px 10px;font-weight:500;font-size:13px} +html[data-organizations] .ws-proj.flat{padding-left:8px} +html[data-organizations] .ws-flat{display:flex;flex-direction:column;gap:1px} + +/* Avatars, status marks, chips, buttons. */ +html[data-organizations] .ws-av{display:inline-grid;place-items:center;flex:none;width:20px;height:20px;border-radius:5px;background:var(--org,var(--muted));color:var(--org-on,var(--surface));font:700 9.5px/1 var(--font);letter-spacing:.02em} +html[data-organizations] .ws-av.xs{width:16px;height:16px;border-radius:4px;font-size:8.5px;letter-spacing:0} +html[data-organizations] .ws-av.md{width:28px;height:28px;border-radius:7px;font-size:12px} +html[data-organizations] .ws-av.lg{width:44px;height:44px;border-radius:10px;font-size:17px} +html[data-organizations] .ws-av.all{background:var(--raised);color:var(--strong)} +html[data-organizations] .ws-av.all .mosaic-logo{width:18px;height:18px;fill:currentColor} +html[data-organizations] .ws-dot{display:inline-flex;align-items:center;gap:6px;flex:none} +html[data-organizations] .ws-dot b{font:400 13px/1 var(--glyph);width:14px;text-align:center} +html[data-organizations] .ws-dot.s-working{color:var(--success)} +html[data-organizations] .ws-dot.s-waiting{color:var(--warning)} +html[data-organizations] .ws-dot.s-error{color:var(--danger)} +html[data-organizations] .ws-dot.s-offline,html[data-organizations] .ws-dot.s-idle,html[data-organizations] .ws-dot.s-unknown{color:var(--muted)} +html[data-organizations] .ws-nav .ws-dot{margin-left:auto} +html[data-organizations] .ws-org-row .ws-dot{font-size:12.5px;font-weight:500} +html[data-organizations] .ws-org-row .ws-dot.s-offline,html[data-organizations] .ws-org-row .ws-dot.s-error{color:var(--text)} +html[data-organizations] .ws-org-row .ws-dot.s-offline b{color:var(--muted)} +html[data-organizations] .ws-org-row .ws-dot.s-error b{color:var(--danger)} +html[data-organizations] .ws-btn,html[data-organizations] .ws-busctl [data-bus-restart]{display:inline-flex;align-items:center;gap:6px;min-height:0;border:1px solid var(--line);background:var(--surface);border-radius:var(--r);padding:4px 10px;font:600 13px/1.4 var(--font);color:var(--strong);text-decoration:none;white-space:nowrap;cursor:pointer;box-shadow:none} +html[data-organizations] .ws-btn:hover:not(:disabled),html[data-organizations] .ws-busctl [data-bus-restart]:hover:not(:disabled){background:var(--raised)} +html[data-organizations] .ws-btn:disabled,html[data-organizations] .ws-busctl [data-bus-restart]:disabled{color:var(--muted);cursor:not-allowed;opacity:1} +html[data-organizations] .ws-btn svg.i{width:15px;height:15px} +/* The live bus restart is console-restart.js's own button; its icon sits beside it, outside the + part that file repaints. */ +html[data-organizations] .ws-busctl{position:relative;display:inline-flex;flex-direction:column;align-items:flex-end} +html[data-organizations] .ws-busctl .bus-restart{display:inline-flex;flex-direction:column;align-items:flex-end;gap:4px} +html[data-organizations] .ws-busctl [data-bus-restart]{padding-left:31px} +html[data-organizations] .ws-busctl .ws-busicon{position:absolute;left:11px;top:7px;width:15px;height:15px;pointer-events:none;color:var(--strong);z-index:1} +html[data-organizations] .ws-busctl [data-bus-restart-receipt]{font-size:12px;color:var(--muted);max-width:28em;text-align:right} +html[data-organizations] .ws-busctl [data-bus-restart-receipt]:empty{display:none} +html[data-organizations] .ws-chips{display:flex;flex-wrap:wrap;align-items:center;gap:6px} + +/* Page frame (sample main column). */ +html[data-organizations] .content:has(.ws){padding-top:18px;padding-inline:24px} +body:has([data-org-dashboard]) #breadcrumbs,body:has([data-org-agents]) #breadcrumbs{display:none} +html[data-organizations] .ws{font-size:14px;line-height:1.5;color:var(--text);min-width:0} +html[data-organizations] .ws h1{margin:0;font-size:28px;font-weight:800;letter-spacing:-.02em;line-height:1.15;color:var(--strong)} +html[data-organizations] .ws h1:focus,html[data-organizations] .ws h1:focus-visible{outline:none} +html[data-organizations] .ws h2{margin:0;font-size:15px;font-weight:700;color:var(--strong)} +html[data-organizations] .ws code,html[data-organizations] .ws .mono{font-family:var(--mono);font-size:12.5px} +html[data-organizations] .ws .muted,html[data-organizations] .ws .note{color:var(--muted)} +html[data-organizations] .ws .note{font-size:13px} +html[data-organizations] .ws-crumb{display:flex;gap:6px;align-items:center;font-size:12.5px;color:var(--muted);margin-bottom:4px} +html[data-organizations] .ws-crumb a{color:var(--muted);text-decoration:none} +html[data-organizations] .ws-crumb a:hover{color:var(--action);text-decoration:underline} +html[data-organizations] .ws-vh{display:flex;flex-wrap:wrap;align-items:center;gap:8px 14px;margin-bottom:14px} +html[data-organizations] .ws-vh .sub{flex-basis:100%;margin:0;font-size:13.5px;color:var(--muted)} +html[data-organizations] .ws-right{margin-left:auto;display:flex;flex-wrap:wrap;align-items:flex-start;gap:8px} +html[data-organizations] .ws-sec-h{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 10px;margin:22px 0 8px} +html[data-organizations] .ws-sec-h .note{flex:1} +html[data-organizations] .ws-sec-h a{margin-left:auto;font-size:13px;font-weight:600;color:var(--action);text-decoration:none} +html[data-organizations] .ws-sec-h a:hover{text-decoration:underline} +html[data-organizations] .ws-panel{background:var(--surface);border:1px solid var(--line);border-radius:10px;padding:16px;margin:0} +html[data-organizations] .ws-panel.tight{padding:12px 14px} +html[data-organizations] .ws-split{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(0,1fr);gap:16px;align-items:start} +html[data-organizations] .ws-split{margin-top:22px} +html[data-organizations] .ws-split>section>.ws-sec-h:first-child{margin-top:0} + +/* Organization dashboard (sample 03). */ +html[data-organizations] .ws-orghead{display:flex;flex-wrap:wrap;align-items:center;gap:14px;margin-bottom:14px} +html[data-organizations] .ws-orghead h1{display:flex;align-items:center;gap:10px} +html[data-organizations] .ws-orghead h1 svg.i{width:20px;height:20px;color:var(--muted)} +html[data-organizations] .ws-meta{flex-basis:100%;display:flex;flex-wrap:wrap;align-items:center;gap:4px 14px;margin:-6px 0 0;padding-left:58px;font-size:13px;color:var(--muted)} +html[data-organizations] .ws-meta code{color:var(--text)} +html[data-organizations] .ws-meta .ws-dot{color:var(--muted)} +html[data-organizations] .ws-meta .ws-dot.s-working b{color:var(--success)} +html[data-organizations] .ws-meta .ws-dot.s-offline b,html[data-organizations] .ws-meta .ws-dot.s-error b{color:var(--danger)} +html[data-organizations] .ws-typechips,html[data-organizations] .ws-docrow{margin-top:8px} +html[data-organizations] .ws-typechips .ws-label,html[data-organizations] .ws-docrow .ws-label{min-width:104px} +html[data-organizations] .ws-doc{display:inline-flex;align-items:center;gap:5px;border:1px solid var(--line);background:var(--surface);border-radius:var(--r);padding:2px 8px;font-size:12.5px;font-weight:600;color:var(--strong);text-decoration:none} +html[data-organizations] .ws-doc:hover{background:var(--raised)} +html[data-organizations] .ws-doc svg.i{width:14px;height:14px;color:var(--muted)} +html[data-organizations] .ws-doc small{font-weight:500;color:var(--muted);font-size:11px} +html[data-organizations] .ws-more{font-size:13px;font-weight:600;margin-left:4px;color:var(--action);text-decoration:none} +html[data-organizations] .ws-tiles{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px} +html[data-organizations] .ws-tile{background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:12px 14px;display:grid;gap:6px;align-content:start} +html[data-organizations] .ws-tile.is-empty{grid-column:1/-1;border-style:dashed;background:transparent} +html[data-organizations] .ws-empty-t{font-size:13.5px;font-weight:600;color:var(--strong)} +html[data-organizations] .ws-tbl{overflow-x:auto;border:1px solid var(--line);border-radius:8px;background:var(--surface)} +html[data-organizations] .ws-tbl table{width:100%;border-collapse:collapse;font-size:13px;margin:0} +html[data-organizations] .ws-tbl th{font-size:11px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--muted);text-align:left;padding:7px 10px;border-bottom:1px solid var(--line);background:none;white-space:nowrap} +html[data-organizations] .ws-tbl td{padding:7px 10px;border-bottom:1px solid color-mix(in srgb,var(--line) 60%,transparent);vertical-align:middle} +html[data-organizations] .ws-tbl tr:last-child td{border-bottom:0} +html[data-organizations] .ws-tbl .t1{color:var(--strong)} +html[data-organizations] .ws-tbl .t2{display:block;font-size:12px;color:var(--muted)} +html[data-organizations] .ws-tbl td.mono{font-family:var(--mono);font-size:12.5px;white-space:nowrap} +html[data-organizations] .ws-cfg{display:grid;list-style:none;margin:0;padding:0;border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--surface)} +html[data-organizations] .ws-cfg li{display:grid;align-items:center;grid-template-columns:18px 132px minmax(0,1fr) auto auto;gap:0 10px;padding:7px 12px;border-bottom:1px solid color-mix(in srgb,var(--line) 60%,transparent)} +html[data-organizations] .ws-cfg li:last-child{border-bottom:0} +html[data-organizations] .ws-cfg svg.i{width:16px;height:16px;color:var(--muted)} +html[data-organizations] .ws-cfg .k{font-size:13px;font-weight:600;color:var(--strong)} +html[data-organizations] .ws-cfg .v{font-size:12px;color:var(--muted);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +html[data-organizations] .ws-cfg .src-tag{font:500 11px var(--mono);color:var(--accent);white-space:nowrap} +html[data-organizations] .ws-cfg .go{font-size:12.5px;font-weight:600;color:var(--action);text-decoration:none;min-width:32px;text-align:right} +html[data-organizations] .ws-cfg a.go:hover{text-decoration:underline} +html[data-organizations] .ws-cfg li.danger .k,html[data-organizations] .ws-cfg li.danger svg.i,html[data-organizations] .ws-cfg li.danger .go,html[data-organizations] .ws-cfg li.danger .src-tag{color:var(--danger)} + +/* Agents (sample 08). */ +html[data-organizations] .ws-lvl{display:inline-block;font:700 10.5px/1.5 var(--font);letter-spacing:.05em;text-transform:uppercase;padding:1px 6px;border-radius:3px;margin-right:6px;vertical-align:1px} +html[data-organizations] .ws-lvl.root{background:var(--strong);color:var(--surface)} +html[data-organizations] .ws-lvl.org{background:color-mix(in srgb,var(--org,var(--action)) 18%,transparent);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--org,var(--action)) 50%,transparent);color:var(--strong)} +html[data-organizations] .ws-lvl.proj{box-shadow:inset 0 0 0 1px var(--line);color:var(--text)} +html[data-organizations] .ws-span-band{display:flex;flex-wrap:wrap;align-items:center;gap:8px 10px;padding:8px 12px;margin-bottom:14px;border-radius:8px;border:1px solid var(--action);background:color-mix(in srgb,var(--action) 8%,var(--surface));font-size:13px;color:var(--strong)} +html[data-organizations] .ws-span-band .orgs{display:inline-flex;gap:4px} +html[data-organizations] .ws-band-note{flex-basis:100%;font-size:12.5px} +html[data-organizations] .ws-levels{display:grid;border:1px solid var(--line);border-radius:10px;overflow:hidden;background:var(--surface)} +html[data-organizations] .ws-levels>div{padding:10px 12px;border-bottom:1px solid color-mix(in srgb,var(--line) 60%,transparent);border-right:1px solid color-mix(in srgb,var(--line) 60%,transparent);min-width:0} +html[data-organizations] .ws-levels>.endc{border-right:0} +html[data-organizations] .ws-levels>.last{border-bottom:0} +html[data-organizations] .ws-levels>.lh{background:color-mix(in srgb,var(--raised) 45%,transparent);display:grid;gap:4px;align-content:start} +html[data-organizations] .ws-levels>.lh .ws-lvl{justify-self:start} +html[data-organizations] .ws-levels>.lh small{font-size:11.5px;color:var(--muted);line-height:1.4} +html[data-organizations] .ws-levels>.oh{display:flex;align-items:center;gap:8px;font-weight:700;color:var(--strong);background:color-mix(in srgb,var(--raised) 45%,transparent)} +html[data-organizations] .ws-levels>.span{grid-column:2/-1;display:flex;align-items:center} +html[data-organizations] .ws-levels .mlabel{display:none;align-items:center;gap:6px;font-size:12px;font-weight:700;color:var(--strong);margin-bottom:4px} +html[data-organizations] .ws-agent{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);border-radius:999px;padding:2px 10px 2px 8px;font-size:12.5px;font-weight:600;background:var(--canvas);margin:2px 4px 2px 0;color:var(--strong)} +html[data-organizations] .ws-agent small{color:var(--muted);font-weight:500;font-size:11px} +html[data-organizations] .ws-agent .ws-dot b{font-size:11px;width:10px} +html[data-organizations] .ws-rules{display:grid;gap:10px;font-size:13px} +html[data-organizations] .ws-rules p{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px;margin:0} +html[data-organizations] .ws-rules .ws-lvl{margin-right:0} +html[data-organizations] .ws-scope{margin:-8px 0 14px} + +@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} + html[data-organizations] .tree{padding:10px 12px 20px} + html[data-organizations] .ws h1{font-size:24px} + html[data-organizations] .ws-split,html[data-organizations] .ws-tiles{grid-template-columns:minmax(0,1fr)} + html[data-organizations] .ws-tile.is-empty{grid-column:auto} + html[data-organizations] .ws-sec-h .note{flex-basis:100%;order:3} + html[data-organizations] .ws-cfg li{grid-template-columns:18px minmax(0,1fr) auto auto} + html[data-organizations] .ws-cfg .v{grid-column:2/-1;grid-row:2} + html[data-organizations] .ws-meta{padding-left:0;margin-top:0} + html[data-organizations] .ws-orghead .ws-right{margin-left:0} + html[data-organizations] .ws-busctl,html[data-organizations] .ws-busctl .bus-restart{align-items:flex-start} + html[data-organizations] .ws-busctl [data-bus-restart-receipt]{text-align:left} + html[data-organizations] .ws-typechips .ws-label,html[data-organizations] .ws-docrow .ws-label{min-width:0} + html[data-organizations] .ws-levels{grid-template-columns:minmax(0,1fr)!important} + html[data-organizations] .ws-levels>div{border-right:0} + html[data-organizations] .ws-levels>.hide-m,html[data-organizations] .ws .hide-m{display:none} + 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} +} diff --git a/packages/webui/src/public/workspace-data.js b/packages/webui/src/public/workspace-data.js new file mode 100644 index 000000000..e5b9f596c --- /dev/null +++ b/packages/webui/src/public/workspace-data.js @@ -0,0 +1,21 @@ +// Every read the unified workspace screens make: the organization list, the theme table and the +// per-organization routes under /api/orgs//. Nothing here writes. A read that fails throws, so +// each caller says "unavailable" for that one part instead of guessing. +(() => { + 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'); + return response.json(); + }; + const orgPath = (id, path) => `/api/orgs/${encodeURIComponent(id)}/${path}`; + const organizations = () => read('/api/orgs'); + const themes = () => read('/api/themes'); + const projects = id => read(orgPath(id, 'chat/projects')); + const threads = id => read(orgPath(id, 'chat/threads')); + const instances = id => read(orgPath(id, 'bus/instances')); + const queue = id => read(orgPath(id, 'queue')); + 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)}`)); + window.MosaicWorkspaceData = Object.freeze({ organizations, themes, projects, threads, instances, queue, business, settings, projectFiles }); +})(); diff --git a/packages/webui/src/public/workspace.js b/packages/webui/src/public/workspace.js new file mode 100644 index 000000000..ba8266313 --- /dev/null +++ b/packages/webui/src/public/workspace.js @@ -0,0 +1,277 @@ +// The unified workspace screens in organization mode: the sidebar's Organizations and Projects +// groups (sample 01), the organization dashboard (sample 03) and the Agents levels (sample 08). +// Every read goes through MosaicWorkspaceData (workspace-data.js). Nothing here writes; the bus +// restart button is console-restart.js's own control, with its gating and trail unchanged. +(() => { + 'use strict'; + if (!document.documentElement.hasAttribute('data-organizations')) return; + const data = window.MosaicWorkspaceData; + const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); + const enc = encodeURIComponent; + const GROUPING = 'mosaic-workspace-project-grouping-v1', ORGS_OPEN = 'mosaic-workspace-orgs-open-v1', PROJECTS_OPEN = 'mosaic-workspace-projects-open-v1'; + const load = key => { try { return localStorage.getItem(key); } catch { return null; } }; + const save = (key, value) => { try { localStorage.setItem(key, value); } catch {} }; + let grouping = load(GROUPING) === 'flat' ? 'flat' : 'org'; + let expanded = load(ORGS_OPEN) !== 'closed'; + let projectsOpen = load(PROJECTS_OPEN) !== 'closed'; + let orgs = null, orgError = false, themes = null, projects = new Map(); + + // Icons: the Console sprite where it has one, inline paths from the U0 sample where it does not. + const PATHS = { + folder: '', + columns: '', + chevron: '', + plus: '', + restart: '', + doc: '', + people: '', + cube: '', + }; + const icon = (id, cls = '') => ``; + const LOGO = ''; + + // An organization's colour is its theme's action colour, per mode, with that mode's onAction for + // the initials. The CSS picks the pair for the page's mode (.ws-o in shell.css). + const HEX = /^#[0-9a-f]{6}$/i; + const themeOf = org => (themes || []).find(t => t.id === (org.theme || 'harbor')) || (themes || []).find(t => t.id === 'harbor'); + function colours(org) { + const tokens = themeOf(org)?.tokens || {}; + const pick = (mode, name, fallback) => (HEX.test(tokens[mode]?.[name] || '') ? tokens[mode][name] : fallback); + const l = [pick('light', '--action', '#2266bf'), pick('light', '--onAction', '#ffffff')]; + const d = [pick('dark', '--action', '#74a6e7'), pick('dark', '--onAction', '#10141a')]; + const m = [pick('dim', '--action', d[0]), pick('dim', '--onAction', d[1])]; + return `--org-l:${l[0]};--org-on-l:${l[1]};--org-d:${d[0]};--org-on-d:${d[1]};--org-m:${m[0]};--org-on-m:${m[1]}`; + } + // Two words give their first letters (Distinctly Digital, DD); one word gives its first letter and + // its last consonant (Forge, FG; Home, HM), as the U0 sample marks them. + function initials(org) { + const words = String(org.label || org.id || '?').trim().split(/[\s_.-]+/).filter(Boolean); + if (words.length > 1) return (words[0][0] + words[1][0]).toUpperCase(); + const word = words[0] || '?', rest = word.slice(1).replace(/[^a-z0-9]/gi, ''), consonants = rest.match(/[bcdfghjklmnpqrstvwxz]/gi); + return (word[0] + (consonants ? consonants[consonants.length - 1] : rest[0] || '')).toUpperCase(); + } + const av = (org, size = '') => ``; + const label = org => org.label || org.id; + const state = org => (org.invalid ? ['s-error', '▲', 'invalid'] : org.busHealthy ? ['s-working', '●', 'bus running'] : ['s-offline', '○', 'bus unavailable']); + // A status mark: a glyph plus its word, shown or read aloud only. + const dot = (cls, glyph, word, shown = false) => `${shown ? esc(word) : `${esc(word)}`}`; + const orgHref = id => `#/orgs/${enc(id)}`; + const route = () => location.hash.replace(/^#\/orgs\/[^/]+/, '') || '/'; + const ensureThemes = async () => { if (!themes) themes = await data.themes().then(b => (Array.isArray(b?.themes) ? b.themes : [])).catch(() => []); return themes; }; + const instancesOf = value => { const v = value?.rows?.[0]?.instances ?? value?.instances; return v && typeof v === 'object' && !Array.isArray(v) ? v : null; }; + const running = item => (Array.isArray(item?.running) ? item.running.length : 0); + + // Focus survives a repaint: the focused control's data-focus-key is found again afterwards. + const focusKey = root => { const a = document.activeElement; return root && a && root.contains(a) ? a.dataset?.focusKey || null : null; }; + const refocus = (root, key) => { if (key) root.querySelector(`[data-focus-key="${CSS.escape(key)}"]`)?.focus({ preventScroll: true }); }; + + // ---------- sidebar (sample 01) ---------- + function projectLinks(org, flat) { + const rows = projects.get(org.id); + if (rows === undefined) return flat ? '' : '

    Reading projects…

    '; + if (rows === null) return `

    ${flat ? `${esc(label(org))}: projects unavailable` : 'Projects unavailable'}

    `; + const live = rows.filter(p => p && !p.archived); + if (!live.length) return flat ? '' : '

    No projects yet

    '; + const hash = location.hash; + return live.map(p => { + const href = `${orgHref(org.id)}/projects/${enc(p.id)}`, current = hash === href || hash.startsWith(`${href}/`); + return `${flat ? av(org, 'xs') : ''}${esc(p.name || p.id)}`; + }).join(''); + } + function projectGroups(list) { + if (grouping === 'flat') { + const body = list.map(org => projectLinks(org, true)).join(''); + if (body) return `
    ${body}
    `; + return list.some(org => projects.get(org.id) === undefined) ? '

    Reading projects…

    ' : '

    No projects yet

    '; + } + return list.map(org => `
    ${av(org, 'xs')}${esc(label(org))}
    ${projectLinks(org, false)}
    `).join('') || '

    No projects yet

    '; + } + function paint() { + const root = document.getElementById('workspace-nav'); if (!root) return; + const key = focusKey(root); + if (orgError || !orgs) { root.innerHTML = `

    ${orgError ? 'Organizations unavailable' : 'Reading organizations…'}

    `; return; } + const here = route(), selected = window.MosaicOrg?.id; + const rows = orgs.map(org => { + const [cls, glyph, word] = state(org), mine = org.id === selected, current = mine && here === '/organization'; + return `
  • ${av(org)}${esc(label(org))}${dot(cls, glyph, word, cls !== 's-working')}
  • `; + }).join(''); + const marks = expanded || !orgs.length ? '' : ``; + root.innerHTML = `
    ${icon('plus')}
    ${marks}
      ${rows || '
    • No organizations yet
    • '}

    ${projectGroups(orgs.filter(org => !org.invalid))}
    `; + refocus(root, key); + } + let reading = 0; + async function refresh(rows) { + const turn = ++reading; + try { + const [list] = await Promise.all([Array.isArray(rows) ? rows : data.organizations(), ensureThemes()]); + if (turn !== reading) return; + orgs = Array.isArray(list) ? list : []; orgError = false; + } catch { if (turn === reading) { orgError = true; paint(); } return; } + paint(); + const results = await Promise.all(orgs.filter(org => !org.invalid).map(org => data.projects(org.id).then(b => [org.id, Array.isArray(b?.rows) ? b.rows : null]).catch(() => [org.id, null]))); + if (turn !== reading) return; + projects = new Map(results); paint(); + } + document.addEventListener('click', e => { + const toggle = e.target.closest?.('[data-org-toggle]'); + 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(); } + }); + window.addEventListener('hashchange', () => { if (orgs) paint(); }); + document.addEventListener('mosaic-org-list', e => refresh(e.detail?.rows)); + + // ---------- organization dashboard (sample 03) ---------- + const SAFE = /^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,159}$/; + const DOC_PATH = /^(spec\/north-star\.md|docs\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.md)$/; + const docCache = new Map(); + // Docs are read at most once a minute per organization: the dashboard repaints every 10 s. + async function docs(id, names) { + const hit = docCache.get(id); + if (hit && Date.now() - hit.at < 60000) return hit.value; + const list = (Array.isArray(names) ? names : []).filter(p => typeof p === 'string' && SAFE.test(p)).slice(0, 6); + const read = await Promise.allSettled(list.map(p => data.projectFiles(id, p).then(body => (Array.isArray(body?.files) ? body.files : []).filter(f => typeof f?.path === 'string' && DOC_PATH.test(f.path)).map(f => ({ project: p, path: f.path }))))); + const value = { rows: read.flatMap(r => (r.status === 'fulfilled' ? r.value : [])), failed: read.length > 0 && read.every(r => r.status === 'rejected') }; + docCache.set(id, { at: Date.now(), value }); + return value; + } + const docName = path => (path === 'spec/north-star.md' ? 'North star' : path.replace(/^.*\//, '').replace(/\.md$/, '').replace(/[-_]+/g, ' ').replace(/^./, c => c.toUpperCase())); + const titleCase = s => String(s || '').replace(/(^|[-_\s])(\w)/g, (_, sep, c) => `${sep ? ' ' : ''}${c.toUpperCase()}`); + const clock = () => new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }); + const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; + const secH = (title, note = '', link = '') => `

    ${title}

    ${note ? `${note}` : ''}${link}
    `; + + function settingsList(org, ctx) { + const { business, settings, instances, orgCount } = ctx; + const b = business?.business, s = settings; + const unread = 'Could not be read'; + const names = instances ? Object.keys(instances) : null; + const models = b && Array.isArray(b.instances) ? [...new Set(b.instances.map(i => i?.vars?.model).filter(m => typeof m === 'string' && m))] : null; + const arbiters = b?.arbiters && typeof b.arbiters === 'object' ? Object.entries(b.arbiters).filter(([, v]) => typeof v === 'string').map(([k, v]) => `${v} (${k})`).join(' · ') : null; + const total = s?.launch && !s.launch.refused ? s.launch.limits?.total : undefined; + const notifier = s?.notifier; + const theme = b?.appearance?.theme || org.theme || 'harbor'; + const rows = [ + ['business', 'Identity', b ? `${label(org)} · ${org.id} · kind not recorded` : unread, 'org file', 'business'], + ['flag', 'Appearance', `${titleCase(theme)} theme · ${initials(org)} avatar`, b?.appearance?.theme || org.theme ? 'org file' : 'system', 'appearance'], + ['cube', 'System types', 'Not built yet', 'not built', null], + ['folder', 'Projects', b ? (Array.isArray(b.projects) && b.projects.length ? plural(b.projects.length, 'project') : 'No projects') : unread, 'org file', '#/projects'], + ['people', 'Agents and roles', names ? (names.length ? `${plural(names.length, 'agent')} · ${Object.values(instances).filter(running).length} running` : 'No agents') : unread, 'org file', 'agents'], + ['term', 'Models and routing', models ? (models.length ? models.join(' · ') : 'No models set') : unread, 'org file', 'routing'], + ['queue', 'Arbiters', b ? arbiters || 'None set' : unread, 'org file', 'business'], + ['tasks', 'Task tracker', b ? (b.vars?.['tracker.kind'] ? titleCase(b.vars['tracker.kind']) : 'Not set') : unread, 'org file', 'business'], + ['talk', 'Channels', !s ? unread : typeof notifier?.binding === 'string' ? `Notifier ${notifier.binding}` : notifier?.refused ? unread : 'No notifier set', 'system', 'about'], + ['ledger', 'Launch limits', !s ? unread : s.launch?.refused ? unread : Number.isFinite(total) ? `${plural(total, 'session')} at once` : 'No session limit', 'org file', 'limits'], + ['talk', 'Assistant', 'The assistant agent and its seat names', 'org file', 'assistant'], + ['ledger', 'Token use', 'Usage and limits per provider and model', 'system', 'tokens'], + ['term', 'Model proxy', 'Accounts, priority and client keys', 'system', 'model-proxy'], + ['restart', 'Console', 'Console restart', 'system', 'console'], + ['business', 'Organizations', orgCount === null ? unread : plural(orgCount, 'organization'), 'system', 'organizations'], + ['flag', 'About', typeof s?.release === 'string' ? `Release ${s.release}` : 'Address, release and notifier', 'system', 'about'], + ['people', 'Members and invites', 'Not built yet', 'not built', null], + ['restart', 'Bus', `${org.busHealthy ? 'Running' : 'Unavailable'} · restart from this page's header`, 'system', null], + ['close', 'Archive or delete', "Archive or delete this organization's file", 'danger', 'organizations'], + ]; + return `
      ${rows.map(([ic, name, value, tag, page]) => { + const href = page === null ? null : page.startsWith('#') ? page : `#/settings/${page}`; + const go = href ? `Open` : ''; + return `${icon(ic)}${esc(name)}${esc(value)}${esc(tag)}${go}`; + }).join('')}
    `; + } + + async function dashboard() { + const id = window.MosaicOrg.id; + const reads = await Promise.allSettled([data.organizations(), ensureThemes(), data.business(id), data.settings(id), data.instances(id), data.threads(id), data.projects(id), data.queue(id)]); + const value = i => (reads[i].status === 'fulfilled' ? reads[i].value : null); + const list = Array.isArray(value(0)) ? value(0) : null; + const business = value(2), settings = value(3), instances = instancesOf(value(4)); + const threads = Array.isArray(value(5)?.rows) ? value(5).rows : null, projectRows = Array.isArray(value(6)?.rows) ? value(6).rows : null; + const queue = Array.isArray(value(7)?.rows) ? value(7).rows : null; + const docRead = business?.business ? await docs(id, business.business.projects).catch(() => ({ rows: [], failed: true })) : null; + await window.MosaicConsole?.ready; + const org = list?.find(o => o.id === id) || { id, label: id, busHealthy: false }; + const name = esc(label(org)); + const tracker = business?.business?.vars?.['tracker.kind']; + + // Header: the bus restart is console-restart.js's button where the Console allows it, otherwise + // the same control, present and disabled, with the reason. + const restart = window.MosaicConsole?.busButton?.('Restart bus') || ''; + const bus = restart ? `${icon('restart', 'ws-busicon')}${restart}` : ``; + const reload = ``; + const [bcls, bglyph] = state(org); + const meta = `

    Kind not recordedid ${esc(id)}Tracker: ${tracker ? esc(titleCase(tracker)) : 'not set'}${dot(bcls, bglyph, org.busHealthy ? `bus running, read ${clock()}` : `bus unavailable, read ${clock()}`, true)}Restart is a trailed human action; reload arrives with the cross-org update.

    `; + + const projectName = pid => projectRows?.find(p => p.id === pid)?.name || pid; + const typechips = '
    System typesNo system types yet. They arrive with the system types update.
    '; + const docChips = !docRead ? 'Docs unavailable' : docRead.failed ? 'Docs unavailable' : docRead.rows.length ? docRead.rows.slice(0, 6).map(d => `${icon('doc')}${esc(docName(d.path))}${esc(projectName(d.project))}`).join('') : 'No docs yet'; + const docrow = `
    Docs${docChips}All docs
    `; + + const tiles = (title, note, empty) => `${secH(title, note)}
    ${empty}
    `; + const modelOf = inst => business?.business?.instances?.find(i => i?.instance === inst)?.vars?.model; + const live = instances ? Object.entries(instances).filter(([, item]) => running(item)) : null; + const sessionRows = (live || []).map(([agent, item]) => { + const mine = (threads || []).filter(t => t?.instance === agent); + const first = mine[0], model = modelOf(agent), count = running(item); + const where = first ? `${esc(projectName(first.project))}${esc(first.name || first.id)}${mine.length > 1 ? ` · ${mine.length - 1} more` : ''}` : 'No conversation recorded'; + return `${esc(agent)}${where}${model ? esc(model) : 'not reported'}${dot('s-working', '●', 'running', true)}${count > 1 ? ` ${count} sessions` : ''}`; + }).join(''); + const sessions = live === null ? '

    Sessions unavailable. The bus did not answer the instance read.

    ' : live.length ? `
    ${sessionRows}
    AgentProject and taskModelStatus
    ` : '

    No active agent sessions

    '; + const open = queue ? queue.filter(r => r?.state !== 'done').length : null; + const queueNote = queue === null ? 'unavailable' : queue.length ? `${plural(queue.length, 'row')}, ${open} not done` : 'no rows'; + + return `
    + +
    ${av(org, 'lg')}

    ${name}

    ${bus}${reload}
    ${meta}
    + ${typechips}${docrow} +
    +
    + ${tiles('KPIs', 'defined in the organization file', 'No KPIs defined in the organization file')} + ${tiles('Metrics', 'measured by the bus', 'No metrics recorded yet')} + ${secH('Active agent sessions', live ? (live.length ? `${live.length} running` : 'none running') : '', 'All agents')} + ${sessions} + ${secH('Queue', queueNote, 'Open queue')} +
    +
    + ${secH('Settings', 'every setting, with where its value comes from')} + ${settingsList(org, { business, settings, instances, orgCount: list ? list.length : null })} +
    +
    +
    `; + } + + // ---------- agents levels (sample 08) ---------- + async function agentGrid(note = '') { + const [list] = await Promise.all([data.organizations().catch(() => null), ensureThemes()]); + const selected = window.MosaicOrg?.id; + const head = `

    Agents

    Agents are defined at three levels: root, organization and project. Only organization agents can be read today.${note ? ` ${note}` : ''}

    `; + if (!Array.isArray(list)) return `
    ${head}

    Organizations unavailable.

    `; + const valid = list.filter(org => !org.invalid); + const [results, business] = await Promise.all([ + Promise.all(valid.map(org => data.instances(org.id).then(v => ({ org, inst: instancesOf(v) })).catch(() => ({ org, inst: null })))), + selected ? data.business(selected).catch(() => null) : null, + ]); + const band = `
    assistantroot${dot('s-unknown', '?', 'status not reported', true)}Works across${valid.map(org => av(org)).join('')}The assistant talks with you across organizations. Its status is not reported on this page; set it up under Settings, Assistant.
    `; + const n = Math.max(valid.length, 1); + const cell = (org, inner, cls = '') => `
    ${av(org, 'xs')}${esc(label(org))}${inner}
    `; + const pill = (name, item) => { const cos = item?.definition === 'chief-of-staff' || name === 'chief'; const on = running(item) > 0; return `${dot(on ? 's-working' : 's-idle', on ? '●' : '–', on ? 'working' : 'idle')}${esc(name)}${cos && name !== 'chief' ? ' chief' : ''}`; }; + const orgRow = results.map(({ org, inst }, i) => cell(org, inst === null ? 'Agents unavailable' : Object.keys(inst).length ? Object.entries(inst).map(([k, v]) => pill(k, v)).join('') : 'No agents configured', i === results.length - 1 ? ' endc' : '')).join(''); + const levels = valid.length ? `
    +
    ${valid.map((org, i) => `
    ${av(org)}${esc(label(org))}
    `).join('')} +
    rootYour root configuration, shared by every organization.
    Root agents are not available yet.
    +
    orgDefined in the organization file. Each organization's agents work only inside it.
    ${orgRow} +
    projectDefined in one project and available only there.
    Project agents are not available yet.
    +
    ` : '

    No organizations yet.

    '; + const mine = results.find(r => r.org.id === selected); + const selOrg = list.find(o => o.id === selected) || { id: selected, label: selected }; + const modelOf = inst => business?.business?.instances?.find(i => i?.instance === inst)?.vars?.model; + const table = !mine ? '

    The selected organization is not on the list.

    ' : mine.inst === null ? '

    Agents unavailable. The bus did not answer the instance read.

    ' : !Object.keys(mine.inst).length ? '

    No agents configured

    ' : `
    ${Object.entries(mine.inst).map(([k, v]) => { const on = running(v) > 0, model = modelOf(k); return ``; }).join('')}
    AgentLevelDefined inStatusModel
    ${esc(k)}${v?.definition && v.definition !== k ? `${esc(v.definition)}` : ''}org${esc(label(selOrg))} file${dot(on ? 's-working' : 's-idle', on ? '●' : '–', on ? 'working' : 'idle', true)}${model ? esc(model) : 'not reported'}
    `; + const rules = `

    orgAgents come from the organization file. Add, change or remove them under Settings, Agents.

    projectrootNot built yet, so nothing can be defined at these levels.

    An agent's harness, model and thinking are set under Settings, Routing.

    `; + return `
    ${head}${band}${levels} +
    ${secH(`Agents in ${esc(label(selOrg))}`, 'organization level', '')}${table}
    ${secH('Who changes what')}${rules}
    +
    `; + } + + window.MosaicWorkspace = Object.freeze({ dashboard, agentGrid, icon, refresh: () => refresh() }); + refresh(); +})(); diff --git a/packages/webui/src/serve.mjs b/packages/webui/src/serve.mjs index 6bd3ad2ad..93ce2133d 100644 --- a/packages/webui/src/serve.mjs +++ b/packages/webui/src/serve.mjs @@ -58,7 +58,7 @@ const files = new Map([ ['/', ['index.html', 'text/html; charset=utf-8']], ['/proxy.js', ['proxy.js', 'text/javascript; charset=utf-8']], ['/project-remote.js', ['project-remote.js', 'text/javascript; charset=utf-8']], - ...['app.js', 'brand.js', 'bus.js', 'markdown-preview.js', 'chat.js', 'project-archive.js', 'processing.js', 'agents.js', 'federation.js', 'requests.js', 'org-create.js', 'console-restart.js', 'onboarding.js'].map(f => ['/' + f, [f, 'text/javascript; charset=utf-8']]), + ...['app.js', 'brand.js', 'bus.js', 'markdown-preview.js', 'chat.js', 'project-archive.js', 'processing.js', 'agents.js', 'federation.js', 'requests.js', 'org-create.js', 'console-restart.js', 'onboarding.js', 'workspace-data.js', 'workspace.js'].map(f => ['/' + f, [f, 'text/javascript; charset=utf-8']]), ['/files.js', ['files.js', 'text/javascript; charset=utf-8']], ['/projects.js', ['projects.js', 'text/javascript; charset=utf-8']], ['/projects.css', ['projects.css', 'text/css; charset=utf-8']], diff --git a/packages/webui/tests/browser.test.mjs b/packages/webui/tests/browser.test.mjs index 0ad50b940..c270961d2 100644 --- a/packages/webui/tests/browser.test.mjs +++ b/packages/webui/tests/browser.test.mjs @@ -18,8 +18,8 @@ test('served Console browser: real board fixtures, keyboard, drafts, receipts, t assert.equal(await b.evaluate('document.querySelector("#session-count").textContent'), '3 of 4'); await b.evaluate('document.querySelector("#hide-offline").click()'); assert.equal(await b.evaluate('document.querySelectorAll("table.sessions tbody tr").length'), 4); - // Rows 129, 154, 191, 194 and 294: chat.js, editor.js, processing.js, agents.js and federation.js are the scripts added, and #1839 adds requests.js (the intake panel under an owner's chat message), all same origin; the list is the pin, so another script is a visible change. #797 adds project-archive.js immediately after chat.js. F2 adds onboarding.js after org-create.js, and F3 adds console-restart.js after it. - assert.deepEqual(await b.evaluate('[...document.querySelectorAll("script")].map(s => s.getAttribute("src"))'), ['/editor.js', '/processing.js', '/org-create.js', '/onboarding.js', '/console-restart.js', '/display.js', '/inbox.js', '/files.js', '/project-remote.js', '/federation.js', '/brand.js', '/app.js', '/markdown-preview.js', '/projects.js', '/chat.js', '/project-archive.js', '/agents.js', '/bus.js', '/requests.js']); + // Rows 129, 154, 191, 194 and 294: chat.js, editor.js, processing.js, agents.js and federation.js are the scripts added, and #1839 adds requests.js (the intake panel under an owner's chat message), all same origin; the list is the pin, so another script is a visible change. #797 adds project-archive.js immediately after chat.js. F2 adds onboarding.js after org-create.js, and F3 adds console-restart.js after it. U2 (#1873) adds workspace-data.js and workspace.js before console-restart.js. + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("script")].map(s => s.getAttribute("src"))'), ['/editor.js', '/processing.js', '/org-create.js', '/onboarding.js', '/workspace-data.js', '/workspace.js', '/console-restart.js', '/display.js', '/inbox.js', '/files.js', '/project-remote.js', '/federation.js', '/brand.js', '/app.js', '/markdown-preview.js', '/projects.js', '/chat.js', '/project-archive.js', '/agents.js', '/bus.js', '/requests.js']); assert.equal(await b.evaluate(`document.querySelectorAll('script[src="/processing.js"]').length`), 1); assert.equal(await b.evaluate(`document.querySelectorAll('script[src="/chat.js"]').length`), 1); assert.equal(await b.evaluate('!!window.injected'), false); diff --git a/packages/webui/tests/org-delete-browser.test.mjs b/packages/webui/tests/org-delete-browser.test.mjs index 5fde11a3a..eb4b7e323 100644 --- a/packages/webui/tests/org-delete-browser.test.mjs +++ b/packages/webui/tests/org-delete-browser.test.mjs @@ -137,14 +137,15 @@ for (const [status, body] of [[201, { outcome: 'done', step: 'delete' }], [503, }); } -test('review: deleting a non-current org refreshes the organization switcher', async t => { +// U2 (#1873): the sidebar's Organizations group replaced the organization switcher. +test('review: deleting a non-current org refreshes the sidebar organization list', async t => { const f = await reviewFixture(t); await f.confirm('beta'); assert.deepEqual((await registry.listOrgs(f.ctx)).map(e=>e.id), ['alpha']); - await f.b.evaluate(`location.hash='#/orgs/alpha/settings/business'`); - await f.wait(`!!document.querySelector('#org-picker')`); - assert.deepEqual(await f.b.evaluate(`[...document.querySelector('#org-picker').options].map(e=>e.value)`), ['alpha']); - assert.equal(await f.b.evaluate(`document.querySelector('#org-picker').value`), 'alpha'); + await f.b.evaluate(`location.hash='#/orgs/alpha/organization'`); + await f.wait(`document.querySelectorAll('[data-workspace-org]').length === 1`); + assert.deepEqual(await f.b.evaluate(`[...document.querySelectorAll('[data-workspace-org]')].map(e=>e.dataset.workspaceOrg)`), ['alpha']); + assert.equal(await f.b.evaluate(`document.querySelector('[data-workspace-org="alpha"] a').getAttribute('aria-current')`), 'page'); assert.deepEqual(await f.b.evaluate(`window.MosaicOrg.list.then(rows => rows.map(row => row.id))`), ['alpha']); }); diff --git a/packages/webui/tests/org-new-entry-browser.test.mjs b/packages/webui/tests/org-new-entry-browser.test.mjs index acc4e7630..4356ba14d 100644 --- a/packages/webui/tests/org-new-entry-browser.test.mjs +++ b/packages/webui/tests/org-new-entry-browser.test.mjs @@ -60,15 +60,16 @@ for (const [width, height] of [[1400, 900], [390, 844]]) { }); } -test('the organization picker offers New organization', { timeout: 60000 }, async t => { +// U2 (#1873): the sidebar's Organizations group replaced the organization picker. +test('the sidebar Organizations group offers New organization', { timeout: 60000 }, async t => { const { base, b, wait, formFocused } = await consoleWith(t, ['alpha', 'beta']); await b.viewport(1400, 900); await b.navigate(`${base}#/orgs/alpha/settings/business`); - const link = `document.querySelector('section[aria-labelledby="org-picker-title"] a[href="#/settings/organizations?new=1"]')`; - await wait(`document.querySelector('#org-picker') && ${link}`, 'picker link'); - assert.equal(await b.evaluate(`${link}.textContent`), 'New organization'); + const link = `document.querySelector('#workspace-nav a.ws-add[href="#/settings/organizations?new=1"]')`; + await wait(`document.querySelectorAll('[data-workspace-org]').length === 2 && ${link}`, 'sidebar link'); + assert.equal(await b.evaluate(`${link}.getAttribute('aria-label')`), 'New organization'); await b.evaluate(`${link}.click()`); - await formFocused('#/orgs/alpha', 'picker'); + await formFocused('#/orgs/alpha', 'sidebar'); }); test('the no-organization empty state offers New organization next to its Settings link', { timeout: 60000 }, async t => { diff --git a/packages/webui/tests/org-switch-browser.test.mjs b/packages/webui/tests/org-switch-browser.test.mjs index 6615947b6..426a82eac 100644 --- a/packages/webui/tests/org-switch-browser.test.mjs +++ b/packages/webui/tests/org-switch-browser.test.mjs @@ -128,7 +128,7 @@ test('project creation offers repositories from the scoped business read', async assert.equal(await b.evaluate(`document.querySelector('#chat-repo option[value=work]').value`), 'work'); }); -test('Settings lists organizations and switching changes the route and header', async t => { +test('sidebar lists organizations and navigating changes the route and header', async t => { const organizations = { list: async () => [{ id: 'alpha', label: 'Alpha', theme: null, busHealthy: true }, { id: 'beta', label: 'Beta', theme: null, busHealthy: false }], resolve: async id => ['alpha', 'beta'].includes(id) ? { @@ -141,11 +141,12 @@ test('Settings lists organizations and switching changes the route and header', const b = await browser({ machine: false }); t.after(() => b.close()); await b.viewport(390, 900); await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/alpha/settings/business`); - await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('#org-picker'))return;await new Promise(r=>setTimeout(r,30))}throw Error('Organization picker did not appear')})()`); + await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelectorAll('[data-workspace-org]').length===2 && document.querySelector('#settings-page-title'))return;await new Promise(r=>setTimeout(r,30))}throw Error('Organizations did not appear')})()`); assert.match(await b.evaluate(`document.querySelector('header').textContent`), /Alpha/); assert.equal(await b.evaluate(`document.querySelector('#settings-page-title').textContent`), 'Organization'); - assert.deepEqual(await b.evaluate(`[...document.querySelector('#org-picker').options].map(o=>o.value)`), ['alpha', 'beta']); - await b.evaluate(`(()=>{const e=document.querySelector('#org-picker');e.value='beta';e.dispatchEvent(new Event('change',{bubbles:true}))})()`); + assert.equal(await b.evaluate(`!!document.querySelector('#org-picker')`), false); + assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-workspace-org]')].map(o=>o.dataset.workspaceOrg)`), ['alpha', 'beta']); + await b.evaluate(`document.querySelector('[data-workspace-org=beta] a').click()`); let switched = false; for (let i = 0; i < 150 && !switched; i++) { try { switched = await b.evaluate(`location.hash.startsWith('#/orgs/beta/') && document.querySelector('header')?.textContent.includes('Beta')`); } catch { /* reload replaced the page */ } @@ -178,12 +179,12 @@ test('a chat draft is kept on Stay and discarded on an organization switch', asy assert.equal(await b.evaluate(`!!document.querySelector('#chat-session-form, #chat-share-form, #chat-clear')`), false, 'unmapped session and sharing controls are unavailable'); await b.evaluate(`(()=>{const el=document.querySelector('#chat-body');el.value='unsent alpha';el.dispatchEvent(new Event('input',{bubbles:true}))})()`); await b.evaluate(`location.hash='#/settings/business'`); - await wait('!!document.querySelector("#org-picker")'); - await b.evaluate(`(()=>{const el=document.querySelector('#org-picker');el.value='beta';el.dispatchEvent(new Event('change',{bubbles:true}))})()`); + await wait('!!document.querySelector("[data-workspace-org=beta] a")'); + await b.evaluate(`document.querySelector('[data-workspace-org=beta] a').click()`); await wait('!!document.querySelector("dialog[open] [data-stay]")'); await b.evaluate(`document.querySelector('[data-stay]').click()`); assert.match(await b.evaluate('location.hash'), /^#\/orgs\/alpha\//); - assert.equal(await b.evaluate(`document.querySelector('#org-picker').value`), 'alpha'); + assert.equal(await b.evaluate(`window.MosaicOrg.id`), 'alpha'); await b.evaluate(`location.hash='#/chat/threads/${thread}'`); await wait('!!document.querySelector("#chat-body")'); assert.equal(await b.evaluate(`document.querySelector('#chat-body').value`), 'unsent alpha'); @@ -210,8 +211,16 @@ test('organization switch isolates browser board preferences', async t => { const base = `http://127.0.0.1:${server.address().port}/`; await b.navigate(base + '#/orgs/alpha/'); await b.evaluate(`document.querySelector('#show-machine').click()`); - await b.navigate(base + '#/orgs/beta/'); - await b.evaluate(`(async()=>{for(let i=0;i<100;i++){if(window.MosaicOrg?.id === 'beta')return;await new Promise(r=>setTimeout(r,30))}throw Error('beta did not load')})()`); + assert.equal(await b.evaluate(`document.querySelector('#show-machine').checked`), true); + // The switch reloads the page. The navigate helper's load checks can be in flight when that + // reload commits, so set the hash in the page and poll one short check at a time. + await b.evaluate(`location.hash = '#/orgs/beta/'`); + let loaded = false; + for (let i = 0; i < 150 && !loaded; i++) { + try { loaded = await b.evaluate(`window.MosaicOrg?.id === 'beta' && !!document.querySelector('#show-machine')`); } catch {} + if (!loaded) await new Promise(r => setTimeout(r, 30)); + } + assert.equal(loaded, true, 'beta did not load'); assert.equal(await b.evaluate(`document.querySelector('#show-machine').checked`), false); }); diff --git a/packages/webui/tests/unified-workspace-browser.test.mjs b/packages/webui/tests/unified-workspace-browser.test.mjs new file mode 100644 index 000000000..941b9e793 --- /dev/null +++ b/packages/webui/tests/unified-workspace-browser.test.mjs @@ -0,0 +1,311 @@ +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 { createOrgAdmin } from '../src/org-admin.mjs'; +import { browser } from './browser.mjs'; +import { close } from './fixture.mjs'; + +const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`); + +// Three organizations as sample 01 and 03 show them: two running buses and one stopped. +function workspaceOrgs() { + const ORGS = [ + { id: 'ddigital', label: 'Distinctly Digital', theme: 'rosewood', busHealthy: true }, + { id: 'forge', label: 'Forge', theme: 'cobalt', busHealthy: true }, + { id: 'home', label: 'Home', theme: 'grove', busHealthy: false }, + ]; + const PROJECTS = { ddigital: [{ id: 'spring-launch', name: 'Spring launch' }, { id: 'brand-refresh', name: 'Brand refresh' }], forge: [{ id: 'api-gateway', name: 'API gateway' }], home: [] }; + const INSTANCES = { ddigital: { chief: ['chief-of-staff', ['r1']], copywriter: ['copywriter', ['r2']], 'montage-producer': ['producer', ['r3', 'r4']], editor: ['editor', []] }, forge: { chief: ['chief-of-staff', []] } }; + const THREADS = { ddigital: [{ id: 't1', name: 'V-112 Launch email, draft 2', project: 'spring-launch', instance: 'copywriter' }, { id: 't2', name: 'V-118 Teaser reel', project: 'spring-launch', instance: 'montage-producer' }, { id: 't3', name: 'Weekly plan', project: 'brand-refresh', instance: 'chief' }], forge: [] }; + const FILES = { 'spring-launch': ['docs/north-star.md', 'docs/launch-plan.md', 'src/index.js'], 'brand-refresh': ['docs/brand-voice-guide.md'], 'api-gateway': [] }; + const instances = id => ({ business: id, revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {}, + instances: Object.fromEntries(Object.entries(INSTANCES[id]).map(([n, [definition, running]]) => [n, { definition, vars: {}, launched: true, launcher: false, protected: false, kept: false, running, alive: [] }])) }); + const business = id => ({ business: { id, human: 'jason', arbiters: ['chief'], projects: PROJECTS[id].map(p => p.id), vars: id === 'ddigital' ? { 'tracker.kind': 'vikunja' } : {}, + instances: Object.keys(INSTANCES[id]).map(n => ({ instance: n, vars: { model: 'sonnet-5.5' } })), appearance: { theme: ORGS.find(o => o.id === id).theme } } }); + return { + list: async () => ORGS, + resolve: async id => { + const org = ORGS.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), settings: async () => ({ release: '0.0.42', notifier: { binding: 'discord' }, launch: { limits: { total: 4 } } }), + queue: async () => ({ rows: id === 'ddigital' ? [{ state: 'done' }, { state: 'in-progress' }, { state: 'queued' }] : [] }), busStatus: async () => ({}) }, + bus: { instances: async () => instances(id), messages: async () => ({ messages: [], unread: 0 }), agents: async () => [], inbox: async () => [], tasks: async () => [] }, + chat: { projects: async () => PROJECTS[id], threads: async () => THREADS[id] }, + projectFiles: async ({ project }) => ({ head: 'a'.repeat(40), files: (FILES[project] || []).map(path => ({ path })) }), + }; + }, + }; +} +// No bus or setup work runs in these tests: every restart below is refused before the admin is used. +const refusingAdmin = () => createOrgAdmin({ service: {}, context: async () => ({ configDir: '/cfg', dataRoot: '/data', instance: 'test' }) }); +const SETTINGS = ['Identity', 'Appearance', 'System types', 'Projects', 'Agents and roles', 'Models and routing', 'Arbiters', 'Task tracker', 'Channels', 'Launch limits', 'Assistant', 'Token use', 'Model proxy', 'Console', 'Organizations', 'About', 'Members and invites', 'Bus', 'Archive or delete']; +const TAGS = ['org file', 'override', 'system', 'root', 'not built', 'danger']; +// Every page the Settings view has for the owner (bus.js settingsPages). +const SETTINGS_PAGES = ['appearance', 'business', 'limits', 'organizations', 'routing', 'agents', 'assistant', 'tokens', 'model-proxy', 'console', 'about']; + +test('workspace navigation exposes all organizations and remembers project grouping', async t => { + const organizations = { + list: async () => [{ id:'alpha', label:'Alpha', theme:null, busHealthy:true }, { id:'beta', label:'Beta', theme:'cobalt', busHealthy:false }], + resolve: async id => ({ busHealthy:id === 'alpha', reads:{ business:async()=>({ business:{ id, projects:[] } }) }, bus:{}, chat:{projects:async()=>[],threads: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()); + const wait = waitFor(b); + await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/alpha/`); + await wait('document.querySelectorAll("[data-workspace-org]").length === 2'); + assert.match(await b.evaluate('document.querySelector("[data-workspace-org=beta]").textContent'), /Beta.*bus unavailable/is); + // An organization's colour is its theme's action colour; no theme is the harbor default. + assert.equal(await b.evaluate('document.querySelector("[data-workspace-org=alpha] .ws-av").style.getPropertyValue("--org-l")'), '#2266bf'); + await b.evaluate('document.querySelector("[data-org-toggle]").click()'); + assert.equal(await b.evaluate('document.querySelector("[data-org-list]").hidden'),true); + await b.evaluate('document.querySelector("[data-org-toggle]").click(); document.querySelector("[data-group=flat]").click()'); + // The Projects group collapses too, and each group's open state is remembered (sample 01). + await b.evaluate('document.querySelector("[data-projects-toggle]").click()'); + assert.deepEqual(await b.evaluate('[document.querySelector("#ws-project-list").hidden, document.querySelector("[data-projects-toggle]").getAttribute("aria-expanded"), document.activeElement?.dataset.focusKey]'), [true, 'false', 'projects-toggle']); + await b.evaluate('location.reload()'); + await wait('document.querySelector("[data-group=flat]")?.getAttribute("aria-pressed") === "true"'); + assert.deepEqual(await b.evaluate('[document.querySelector("#ws-project-list").hidden, document.querySelector("[data-org-list]").hidden]'), [true, false]); + await b.evaluate('document.querySelector("[data-projects-toggle]").click()'); + assert.equal(await b.evaluate('document.querySelector("#ws-project-list").hidden'), false); + await b.viewport(390,844); + assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'),true); +}); + +test('sidebar follows sample 01 and Queue opens from the organization dashboard, not the sidebar', async t => { + const server = await startServer({ port: 0, sso: createDevOwner(), organizations: workspaceOrgs(), log: () => {} }); t.after(() => close(server)); + const b = await browser({ machine: false }); t.after(() => b.close()); + const wait = waitFor(b); + await b.viewport(1440, 900); + await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/ddigital/organization`); + await wait('document.querySelector("[data-org-dashboard] [data-org-settings]") && document.querySelectorAll("#workspace-nav .ws-proj").length === 3'); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#sections > li > a .t")].map(e => e.textContent)'), ['Dashboard', 'Inbox', 'Tasks', 'Projects', 'Side by side', 'Agents', 'Assistant']); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#sections-foot a")].map(e => e.textContent.trim())'), ['Settings']); + assert.match(await b.evaluate('document.querySelector("[data-org-toggle]").textContent.replace(/\\s+/g, " ").trim()'), /^Organizations\s*3$/); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-workspace-org]")].map(li => [li.dataset.workspaceOrg, !!li.querySelector(".ws-av"), [...li.querySelector(".ws-dot").classList].find(c => c.startsWith("s-"))])'), + [['ddigital', true, 's-working'], ['forge', true, 's-working'], ['home', true, 's-offline']]); + assert.equal(await b.evaluate('document.querySelector("#workspace-nav [data-group=org]").getAttribute("aria-pressed")'), 'true'); + // The four-tile logo stays. + assert.equal(await b.evaluate('document.querySelectorAll(".wordmark .mosaic-logo rect").length'), 4); + // No organization switcher remains anywhere on the page. + assert.equal(await b.evaluate('document.querySelector("#org-picker, select[name=org], [data-org-switch]")'), null); + // Projects has no conversation tree under it; the Projects group links to each project page. + assert.equal(await b.evaluate('document.querySelector("#sections #project-tree, #sections .project-tree-list")'), null); + assert.match(await b.evaluate('document.querySelector("#workspace-nav .ws-proj").getAttribute("href")'), /^#\/orgs\/[a-z0-9-]+\/projects\/[^/]+$/); + // Queue and Docs are not sidebar items. + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#console-nav a[href]")].filter(a => /\\/(queue|docs)$/.test(a.getAttribute("href"))).length'), 0); + // Settings stays pinned to the foot of the sidebar. + assert.equal(await b.evaluate('(() => { const nav = document.getElementById("console-nav").getBoundingClientRect(), foot = document.getElementById("sections-foot").getBoundingClientRect(); return foot.bottom >= nav.bottom - 24; })()'), true); + const queue = await b.evaluate('document.querySelector("[data-org-dashboard] [data-org-queue]").getAttribute("href")'); + assert.equal(queue, '#/queue'); + 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']]) { + 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); + } +}); + +test('organization dashboard renders every section from the per-organization reads', async t => { + const server = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), organizations: workspaceOrgs(), log: () => {} }); t.after(() => close(server)); + const b = await browser({ machine: false }); t.after(() => b.close()); + const wait = waitFor(b); + await b.viewport(1440, 900); + await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/ddigital/organization`); + await wait('document.querySelectorAll("[data-org-dashboard] .ws-doc").length > 0'); + const head = await b.evaluate(`(() => { const h = document.querySelector('[data-org-dashboard] .ws-orghead'); return { avatar: h.querySelector('.ws-av')?.textContent, title: h.querySelector('h1').textContent, meta: h.querySelector('.ws-meta').innerText, colour: h.style.getPropertyValue('--org-l') }; })()`); + assert.equal(head.avatar, 'DD'); assert.equal(head.title, 'Distinctly Digital'); + assert.match(head.meta, /Kind not recorded/); assert.match(head.meta, /id ddigital/); assert.match(head.meta, /Tracker: Vikunja/); assert.match(head.meta, /bus running, read \d/); + assert.match(head.colour, /^#[0-9a-f]{6}$/i); + assert.match(await b.evaluate('document.querySelector(".ws-typechips").innerText'), /System types\s+No system types yet/i); + // Docs come from the project files reads: only documents, named by project. + assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".ws-doc")].map(a => a.innerText.replace(/\\s+/g, " ").trim())'), ['North star Spring launch', 'Launch plan Spring launch', 'Brand voice guide Brand refresh']); + // KPIs and metrics: one honest empty tile each, with no invented number. + const tiles = await b.evaluate('[...document.querySelectorAll(".ws-tiles")].map(t => [t.querySelectorAll(".ws-tile").length, t.querySelector(".ws-tile").classList.contains("is-empty"), t.innerText.replace(/\\s+/g, " ").trim()])'); + assert.deepEqual(tiles, [[1, true, 'No KPIs defined in the organization file'], [1, true, 'No metrics recorded yet']]); + // Active agent sessions: the running instances, their project and task, model and status. + const rows = await b.evaluate('[...document.querySelectorAll(".ws-tbl tbody tr")].map(tr => [...tr.cells].map(c => c.innerText.replace(/\\s+/g, " ").trim()))'); + assert.deepEqual(rows, [ + ['chief', 'Brand refresh Weekly plan', 'sonnet-5.5', '● running'], + ['copywriter', 'Spring launch V-112 Launch email, draft 2', 'sonnet-5.5', '● running'], + ['montage-producer', 'Spring launch V-118 Teaser reel', 'sonnet-5.5', '● running 2 sessions'], + ]); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".ws-tbl thead th")].map(th => th.textContent)'), ['Agent', 'Project and task', 'Model', 'Status']); + assert.match(await b.evaluate('document.querySelector("[data-org-dashboard]").innerText'), /Queue\s+3 rows, 2 not done\s+Open queue/); + // Settings: one row per setting, each with an icon, a value, a source tag and, where a page exists, Open. + const settings = await b.evaluate(`[...document.querySelectorAll('[data-org-settings] > li')].map(li => ({ name: li.dataset.orgSetting, icon: !!li.querySelector('svg'), value: li.querySelector('.v').textContent, tag: li.querySelector('.src-tag').textContent, href: li.querySelector('a.go')?.getAttribute('href') ?? null, danger: li.classList.contains('danger') }))`); + assert.deepEqual(settings.map(s => s.name), SETTINGS); + for (const s of settings) { assert.ok(s.icon, s.name); assert.ok(s.value, s.name); assert.ok(TAGS.includes(s.tag), `${s.name}: ${s.tag}`); } + const by = Object.fromEntries(settings.map(s => [s.name, s])); + assert.deepEqual([by['Members and invites'].tag, by['Members and invites'].href], ['not built', null]); + assert.deepEqual([by['System types'].tag, by['System types'].href], ['not built', null]); + assert.deepEqual([by['Archive or delete'].tag, by['Archive or delete'].danger, by['Archive or delete'].href], ['danger', true, '#/settings/organizations']); + assert.equal(by.Identity.value, 'Distinctly Digital · ddigital · kind not recorded'); + assert.equal(by['Task tracker'].value, 'Vikunja'); + assert.equal(by['Launch limits'].value, '4 sessions at once'); + assert.equal(by['Agents and roles'].value, '4 agents · 3 running'); + for (const page of SETTINGS_PAGES) assert.ok(settings.some(s => s.href === `#/settings/${page}`), `no row opens settings/${page}`); +}); + +test('organization dashboard empty states say so in one short line', async t => { + const organizations = { list: async () => [{ id: 'alpha', label: 'Alpha', busHealthy: true }], resolve: async () => ({ busHealthy: true, + reads: { business: async () => ({ business: { id: 'alpha', projects: [] } }), settings: async () => ({}), queue: async () => ({ rows: [] }), busStatus: async () => ({}) }, + bus: { instances: async () => ({ business: 'alpha', revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {}, instances: {} }), messages: async () => ({ messages: [], unread: 0 }), agents: async () => [] }, + chat: { projects: async () => [], threads: 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/organization`); + await waitFor(b)('document.querySelector("[data-org-dashboard] [data-org-settings]")'); + const text = await b.evaluate('document.querySelector("[data-org-dashboard]").innerText'); + // Section labels are uppercased by CSS, so innerText carries the uppercase form. + for (const line of [/System types\s+No system types yet\. They arrive with the system types update\./i, /Docs\s+No docs yet/i, /No KPIs defined in the organization file/, /No metrics recorded yet/, /Active agent sessions\s+none running/i, /No active agent sessions/, /Queue\s+no rows/i, /Tracker: not set/]) + assert.match(text, line); + assert.equal(await b.evaluate('document.querySelectorAll("[data-org-settings] > li").length'), SETTINGS.length); +}); + +test('organization dashboard presents sections and honest unavailable controls', async t => { + const organizations = { list:async()=>[{id:'alpha',label:'Alpha',busHealthy:false}], resolve:async()=>({busHealthy:false,reads:{business:async()=>({business:{id:'alpha',projects:[]}})},bus:{},chat:{projects:async()=>[],threads:async()=>[]}}) }; + const server=await startServer({port:0,sso:createDevOwner(),organizations,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/organization`); + await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('[data-org-dashboard]'))return;await new Promise(r=>setTimeout(r,30))}throw Error('dashboard missing')})()`); + const text=await b.evaluate('document.querySelector("[data-org-dashboard]").innerText'); + for(const label of ['Docs','KPIs','Metrics','Active agent sessions','Settings','Queue']) assert.match(text,new RegExp(label,'i')); + assert.match(text,/reload organization file/i); + assert.match(text,/no metrics recorded yet/i); + assert.match(text,/bus unavailable, read \d/); + assert.match(text,/Sessions unavailable/); + assert.equal(await b.evaluate('document.querySelector("[data-org-reload]").disabled'),true); +}); + +test('each header control is present, reload is disabled, and restart is refused without the owner', async t => { + const owner = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), organizations: workspaceOrgs(), orgAdmin: refusingAdmin(), log: () => {} }); t.after(() => close(owner)); + const readOnly = await startServer({ port: 0, sso: createDevOwner(), organizations: workspaceOrgs(), orgAdmin: refusingAdmin(), log: () => {} }); t.after(() => close(readOnly)); + const signedOut = await startServer({ port: 0, organizations: workspaceOrgs(), orgAdmin: refusingAdmin(), log: () => {} }); t.after(() => close(signedOut)); + const b = await browser({ machine: false }); t.after(() => b.close()); + const wait = waitFor(b); + const header = server => b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/ddigital/organization`).then(() => wait('document.querySelector("[data-org-dashboard] [data-org-settings]")')).then(() => b.evaluate(`(() => { + const h = document.querySelector('[data-org-dashboard] .ws-orghead'), live = h.querySelector('[data-bus-restart]'), off = h.querySelector('[data-bus-restart-off]'), reload = h.querySelector('[data-org-reload]'); + return { live: live ? [live.textContent, live.disabled] : null, off: off ? [off.textContent, off.disabled, !!off.title] : null, + reload: [reload.textContent, reload.disabled, reload.title, document.getElementById(reload.getAttribute('aria-describedby'))?.textContent] }; + })()`)); + const RELOAD = ['Reload organization file', true, 'Reload arrives with the cross-org update', 'Restart is a trailed human action; reload arrives with the cross-org update.']; + // The owner on a Console started with --send gets console-restart.js's restart button. + assert.deepEqual(await header(owner), { live: ['Restart bus', false], off: null, reload: RELOAD }); + // Without --send, or with nobody signed in, the control is present and disabled, and the route refuses. + const post = 'fetch("/api/orgs/ddigital/restart/bus", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }).then(async r => [r.status, (await r.json()).error])'; + assert.deepEqual(await header(readOnly), { live: null, off: ['Restart bus', true, true], reload: RELOAD }); + assert.deepEqual(await b.evaluate(post), [403, 'read-only']); + assert.deepEqual(await header(signedOut), { live: null, off: ['Restart bus', true, true], reload: RELOAD }); + // With nobody signed in, the server refuses every per-org route before the admin hooks run. + assert.deepEqual(await b.evaluate(post), [404, 'org-unavailable']); + // There is no reload route. + assert.equal(await b.evaluate('fetch("/api/orgs/ddigital/reload", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }).then(r => r.ok)'), false); +}); + +// Tab from the first sidebar link through the dashboard and return each stop's region and box. +async function tabStops(b, start) { + await b.evaluate(`(${start}).focus()`); + const stops = []; + for (let i = 0; i < 90; i++) { + const at = await b.evaluate(`(() => { const a = document.activeElement, sec = a.closest('[data-org-dashboard] section'); return { i: [...document.querySelectorAll('*')].indexOf(a), region: a.closest('#console-nav') ? 'nav' : sec ? sec.getAttribute('aria-label') : a.closest('[data-org-dashboard]') ? 'head' : 'other', key: a.dataset.focusKey || a.getAttribute('href') || a.textContent.trim() }; })()`); + if (stops.length && at.region === 'other' && stops.at(-1).region !== 'other') break; + stops.push(at); + await b.key('Tab'); + } + const boxes = await b.evaluate(`(${JSON.stringify(stops.map(s => s.i))}).map(i => { const r = document.querySelectorAll('*')[i].getBoundingClientRect(); return { top: r.top, bottom: r.bottom, left: r.left }; })`); + return stops.map((s, n) => ({ ...s, ...boxes[n] })); +} +function assertVisualOrder(stops, regions, label) { + for (let n = 1; n < stops.length; n++) { + const a = stops[n - 1], z = stops[n], where = `${label}: ${a.key} then ${z.key}`; + assert.ok(z.i > a.i, `tab order leaves DOM order at ${where}`); + assert.ok(regions.indexOf(z.region) >= regions.indexOf(a.region), `region order at ${where}`); + if (z.region !== a.region) continue; + const sameRow = z.top < a.bottom && z.bottom > a.top; + assert.ok(sameRow ? z.left > a.left : z.top >= a.top, `visual order at ${where}`); + } +} + +test('keyboard focus follows visual order and survives a data refresh', async t => { + const server = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), organizations: workspaceOrgs(), log: () => {} }); t.after(() => close(server)); + const b = await browser({ machine: false }); t.after(() => b.close()); + const wait = waitFor(b); + await b.viewport(1440, 900); + await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/ddigital/organization`); + await wait('document.querySelectorAll("[data-org-dashboard] .ws-doc").length > 0 && document.querySelectorAll("#workspace-nav .ws-proj").length === 3'); + const wide = await tabStops(b, 'document.querySelector("#sections a")'); + const regions = ['nav', 'head', 'Measures and sessions', 'Settings']; + assert.deepEqual([...new Set(wide.map(s => s.region))].filter(r => r !== 'other'), regions); + assertVisualOrder(wide.filter(s => s.region !== 'other'), regions, '1440'); + const keys = wide.map(s => s.key); + for (const key of ['org:forge', 'proj:ddigital:spring-launch', 'doc:spring-launch:docs/north-star.md', 'docs-all', 'agents-all', 'queue-open', 'set:Identity', 'set:Archive or delete']) assert.ok(keys.includes(key), `Tab never reaches ${key}`); + // The disabled reload is not a tab stop; the restart button is. + assert.ok(!keys.includes('org-reload')); assert.ok(keys.includes('Restart bus')); + await b.viewport(390, 844); + await wait('document.querySelector("[data-org-dashboard]")'); + const narrow = (await tabStops(b, 'document.querySelector("[data-org-dashboard] .ws-crumb a")')).filter(s => s.region !== 'other'); + assertVisualOrder(narrow, regions.slice(1), '390'); + for (let n = 1; n < narrow.length; n++) assert.ok(narrow[n].top >= narrow[n - 1].top - 1 || narrow[n].region === narrow[n - 1].region, `stacked order at 390: ${narrow[n - 1].key} then ${narrow[n].key}`); + await b.viewport(1440, 900); + + // A refresh repaints the dashboard, the sidebar and the restart button; focus stays on the same control. + for (const key of ['set:Projects', 'queue-open', 'doc:spring-launch:docs/launch-plan.md']) { + await wait(`document.querySelector('[data-focus-key="${key}"]')`); + await b.evaluate(`window.oldDashboard = document.querySelector('[data-org-dashboard]'); document.querySelector('[data-focus-key="${key}"]').focus(); document.getElementById('refresh').click()`); + await wait('document.querySelector("[data-org-dashboard]") && document.querySelector("[data-org-dashboard]") !== window.oldDashboard'); + assert.equal(await b.evaluate('document.activeElement.dataset.focusKey'), key); + } + await b.evaluate(`window.oldDashboard = document.querySelector('[data-org-dashboard]'); document.querySelector('[data-bus-restart]').focus(); document.getElementById('refresh').click()`); + await wait('document.querySelector("[data-org-dashboard]") !== window.oldDashboard'); + assert.equal(await b.evaluate('document.activeElement.hasAttribute("data-bus-restart")'), true); + await b.evaluate(`window.oldRow = document.querySelector('[data-workspace-org=forge]'); document.querySelector('[data-focus-key="org:forge"]').focus(); window.MosaicOrg.refreshList()`); + await wait('document.querySelector("[data-workspace-org=forge]") !== window.oldRow'); + assert.equal(await b.evaluate('document.activeElement.dataset.focusKey'), 'org:forge'); +}); + +test('phone drawer opens over the dashboard with no horizontal scroll', async t => { + const server = await startServer({ port: 0, sso: createDevOwner(), organizations: workspaceOrgs(), log: () => {} }); t.after(() => close(server)); + const b = await browser({ machine: false }); t.after(() => b.close()); + const wait = waitFor(b); + await b.viewport(390, 844); + for (const route of ['organization', 'agents']) { + await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/ddigital/${route}`); + await wait(route === 'organization' ? 'document.querySelector("[data-org-dashboard] [data-org-settings]")' : 'document.querySelector("[data-org-agents] .ws-levels")'); + assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, route); + } + 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-open").click()'); + await wait('document.getElementById("nav-open").getAttribute("aria-expanded") === "true"'); + await wait('document.querySelectorAll("[data-workspace-org]").length === 3'); + const drawer = await b.evaluate('(() => { const r = document.getElementById("console-nav").getBoundingClientRect(); return { left: r.left, right: r.right, sw: document.documentElement.scrollWidth, cw: document.documentElement.clientWidth }; })()'); + assert.ok(drawer.left >= 0 && drawer.right <= 390 && drawer.right > 200, JSON.stringify(drawer)); + assert.ok(drawer.sw <= drawer.cw, JSON.stringify(drawer)); + // The open drawer itself does not scroll sideways; the only clipped children are screen-reader text. + assert.deepEqual(await b.evaluate('(() => { const nav = document.getElementById("console-nav"); return [nav.scrollWidth <= nav.clientWidth, [...nav.querySelectorAll("*")].filter(e => e.scrollWidth > e.clientWidth + 1 && getComputedStyle(e).overflowX !== "visible" && !e.classList.contains("ws-sr")).map(e => e.className)]; })()'), [true, []]); +}); + +test('agents view includes organization-scoped instances without inventing root or project agents', async t => { + const organizations={list:async()=>[{id:'alpha',label:'Alpha',busHealthy:true},{id:'beta',label:'Beta',busHealthy:false}],resolve:async id=>({busHealthy:id==='alpha',reads:{business:async()=>({business:{id}})},bus:{messages:async()=>({messages:[],unread:0}),agents:async()=>[],instances:async()=>({business:id,revision:'a'.repeat(64),launch:true,noHire:[],retired:[],instances:{chief:{definition:'chief-of-staff',vars:{},launched:true,launcher:false,protected:false,kept:false,running:['run-1'],alive:[]}},definitions:{'chief-of-staff':{services:[],accepted:true}}})},chat:{threads:async()=>[],projects: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/agents`); + await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('[data-org-agents]'))return;await new Promise(r=>setTimeout(r,30))}throw Error('organization agent grid missing')})()`); + const text=await b.evaluate('document.querySelector("[data-org-agents]").innerText'); + assert.match(text,/Alpha/); assert.match(text,/chief/); assert.match(text,/Beta/); + assert.match(text,/Root agents are not available yet/); assert.match(text,/Project agents are not available yet/); +}); + +test('an unavailable selected bus does not hide other organizations on Agents', async t => { + const organizations={list:async()=>[{id:'alpha',label:'Alpha',busHealthy:true},{id:'beta',label:'Beta',busHealthy:false}],resolve:async id=>({busHealthy:id==='alpha',reads:{business:async()=>({business:{id}})},bus:id==='alpha'?{agents:async()=>[],messages:async()=>({messages:[],unread:0}),instances:async()=>({business:id,revision:'a'.repeat(64),launch:true,noHire:[],retired:[],instances:{chief:{definition:'chief-of-staff',vars:{},launched:true,launcher:false,protected:false,kept:false,running:['run-1'],alive:[]}},definitions:{'chief-of-staff':{services:[],accepted:true}}})}:{},chat:{threads:async()=>[],projects: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/beta/agents`); + await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('[data-org-agents]'))return;await new Promise(r=>setTimeout(r,30))}throw Error('organization agent grid missing')})()`); + const text=await b.evaluate('document.querySelector("[data-org-agents]").innerText'); + assert.match(text,/Alpha/); assert.match(text,/chief/); assert.match(text,/Beta/); assert.match(text,/Agents unavailable/); +});