From 67c1bcd8913701d419812b0cba757b4e1f7c945a Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Fri, 6 Nov 2026 11:14:54 -0600 Subject: [PATCH 001/116] feat(webui): dashboard shell, navbar, sidebar and logo (ui slice 1) --- packages/webui/src/public/app.js | 4 +- packages/webui/src/public/brand.js | 48 ++++++++++++++++++ packages/webui/src/public/bus.js | 40 +++++++++------ packages/webui/src/public/index.html | 23 ++++----- packages/webui/src/public/processing.css | 27 ++++++++++ packages/webui/src/public/processing.js | 3 ++ packages/webui/src/public/tokens.css | 4 ++ packages/webui/tests/bus-browser.test.mjs | 2 +- .../tests/dashboard-shell-browser.test.mjs | 49 +++++++++++++++++++ .../webui/tests/processing-browser.test.mjs | 23 ++------- packages/webui/tests/processing-ui.test.mjs | 2 +- packages/webui/tests/shell.test.mjs | 20 ++++---- packages/webui/tests/sso-browser.test.mjs | 2 + packages/webui/tests/w15-fixture.mjs | 2 +- .../tests/w15-integration-browser.test.mjs | 4 +- .../webui/tests/w15-shell-browser.test.mjs | 6 +-- 16 files changed, 193 insertions(+), 66 deletions(-) create mode 100644 packages/webui/tests/dashboard-shell-browser.test.mjs diff --git a/packages/webui/src/public/app.js b/packages/webui/src/public/app.js index b6767183f..bdd415d53 100644 --- a/packages/webui/src/public/app.js +++ b/packages/webui/src/public/app.js @@ -7,7 +7,7 @@ // Delivered replies with no newer answer yet, by row: the board's sentAt. Page memory only. const awaiting = new Map(); let data = null, project = null, selected = null, returnFocus = null, paused = false, busy = false, writing = false, reading = null, timer; - let board = 'the configured board', palette = 'harbor', mode = 'system', failed = false; + let board = 'the configured board', palette = 'harbor', mode = 'dark', failed = false; // Show machine sessions (#1589): off by default, kept with the page's settings. While it is off the // page doesn't read /api/board at all; the held roles above come from the bus (bus.js). let machine = false; @@ -480,5 +480,5 @@ setTimeout(() => { const a = document.activeElement; if (!a || a === document.body || a.disabled || !a.getClientRects().length) line.focus(); }); }); // Sign out (sage-1347, F7): a plain same-origin form POST to /auth/logout, shown only under --sso. - api('/api/config').then(config => { board = config.board; $('board-url').textContent = `Board: ${board}`; window.MosaicFederation?.render(config.federation, $('federation')); if (config.sso === true) { sso = true; $('sign-out').hidden = out(); } }).catch(err => { if (machine) error(err); }).finally(refresh); + api('/api/config').then(config => { board = config.board; $('board-url').textContent = `Board: ${board}`; window.MosaicFederation?.render(config.federation, $('federation')); if (config.sso === true) { sso = true; $('sign-out').hidden = out(); $('local-sign-out').hidden = true; $('avatar-name').textContent = 'Operator'; $('avatar-button').querySelector('.avatar-initial').textContent = 'O'; } }).catch(err => { if (machine) error(err); }).finally(refresh); })(); diff --git a/packages/webui/src/public/brand.js b/packages/webui/src/public/brand.js index a0bbe2af6..b17a42f2a 100644 --- a/packages/webui/src/public/brand.js +++ b/packages/webui/src/public/brand.js @@ -75,3 +75,51 @@ function icon(id) {return ``;} root.Brand = {palettes,fonts,logos,icons,tokens,contrast,logo,icon}; })(typeof window === 'undefined' ? globalThis : window); + +/* Shared dashboard chrome. All values come from the Console's existing reads. */ +(() => { + if (typeof document === 'undefined' || !document.getElementById('dashboard-kpis')) return; + const $ = id => document.getElementById(id); + let data = {}, halted = null; + const escape = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); + function paint() { + if (!$('dashboard-kpis')) return; + const metrics = [ + ['Active agents', data.agents, 'Held roles now'], ['Needs your input', data.inbox?.length, 'Open decisions'], + ['Unread messages', data.messages, 'Messages'], ['Open tasks', data.tasks, 'Tasks'], + ['Projects', data.projects, 'Active projects'], ['Queue rows open', data.queue, 'Rows'], + ['Processing', halted === null ? null : halted ? 'Stopped' : 'On', 'Instance status'] + ]; + $('dashboard-kpis').innerHTML = metrics.map(([label, value, caption]) => `
${label}
${value == null ? '–' : escape(value)}${value == null ? 'Not available yet' : caption}
`).join(''); + $('dashboard-business').textContent = data.business ? `Business · ${data.business}` : 'Business overview'; + $('dashboard-inbox-items').innerHTML = data.inbox == null ? '

Not available yet

' : data.inbox.length ? `` : '

Nothing is waiting on you.

'; + age(); + } + function age() { if (!$('dashboard-updated')) return; $('dashboard-updated').textContent = data.readAt ? `Updated ${Math.max(0, Math.floor((Date.now() - data.readAt) / 1000))} s ago` : 'Not read yet'; } + window.MosaicDashboard = { update(value) { data = value; paint(); } }; + document.addEventListener('mosaic-processing-state', e => { halted = e.detail.halted; paint(); }); + setInterval(age, 1000); + const button = $('avatar-button'), menu = $('avatar-menu'); + const controls = () => [...menu.querySelectorAll('a[href],button:not(:disabled),select:not(:disabled)')].filter(el => el.getClientRects().length); + function close(focus = false) { menu.hidden = true; button.setAttribute('aria-expanded', 'false'); if (focus) button.focus(); } + function open() { menu.hidden = false; button.setAttribute('aria-expanded', 'true'); } + button.addEventListener('click', () => menu.hidden ? open() : close()); + button.addEventListener('keydown', e => { if (e.key === 'Escape' && !menu.hidden) { e.preventDefault(); close(true); } else if (['ArrowDown','ArrowUp'].includes(e.key)) { e.preventDefault(); open(); const items = controls(); (e.key === 'ArrowDown' ? items[0] : items.at(-1))?.focus(); } }); + menu.addEventListener('keydown', e => { if (e.key === 'Escape') { e.preventDefault(); close(true); } else if (['ArrowDown','ArrowUp'].includes(e.key) && e.target.tagName !== 'SELECT') { e.preventDefault(); const items = controls(), i = items.indexOf(document.activeElement); items[(i + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length]?.focus(); } }); + menu.addEventListener('click', e => { if (e.target.closest('a')) close(); }); + document.addEventListener('click', e => { if (!e.target.closest('.avatar-wrap')) close(); }); + function breadcrumbs() { + const path = location.hash.slice(2).split('?')[0], parts = path.split('/').filter(Boolean), box = $('breadcrumbs'); + if (!box || !$('bus-view')) return; + if (!parts.length || parts[0] === 'board') { box.innerHTML = 'Dashboard'; return; } + const names = {projects:'Projects',chat:'Projects',inbox:'Inbox',messages:'Messages',tasks:'Tasks',agents:'Agents',queue:'Queue',business:'Business',docs:'Docs',settings:'Settings'}; + const name = names[parts[0]] || 'Dashboard', heading = $('bus-view').querySelector('h1')?.textContent?.trim(); + const project = $('bus-view').querySelector('.chat-conversation > p:first-child a, .chat-room > p:first-child a'); + const middle = project && heading !== project.textContent.trim() ? `${escape(project.textContent.trim())}` : ''; + box.innerHTML = parts.length > 1 && heading && heading !== name ? `${name}${middle}${escape(heading)}` : `${name}`; + } + window.addEventListener('hashchange', () => { close(); breadcrumbs(); }); + new MutationObserver(breadcrumbs).observe($('bus-view'), {childList:true, subtree:true}); + $('processing-link').addEventListener('click', () => { if (!location.hash || location.hash === '#/' || location.hash === '#/board') $('dashboard-processing').scrollIntoView({block:'center'}); else setTimeout(() => $('dashboard-processing').scrollIntoView({block:'center'}), 0); }); + paint(); breadcrumbs(); +})(); diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index 8bd14c1be..dc96bbd05 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -248,10 +248,10 @@ let inboxCount = null, messageCount = null; function sections(route) { const focused = $('sections').contains(document.activeElement) ? document.activeElement.getAttribute('href') : null; - const items = [['/', 'Board', '', 'board'], ['/inbox', 'Inbox', inboxCount ? `${inboxCount.open}${inboxCount.blocking ? ` ${blockChip(`${inboxCount.blocking} blocking`)}` : ''}` : '', 'inbox'], ['/projects', 'Projects', '', 'inbox'], ['/messages', 'Messages', messageCount === null ? '' : `${messageCount}`, 'inbox'], ['/tasks', 'Tasks', '', 'tasks'], ['/agents', 'Agents', '', 'agents'], ['/queue', 'Queue', '', 'queue'], ['/business', 'Business', '', 'business'], ['/docs', 'Docs', '', 'library'], ['/settings', 'Settings', '', 'settings']]; + const items = [['/', 'Dashboard', '', 'board'], ['/projects', 'Projects', '', 'inbox'], ['/inbox', 'Inbox', inboxCount ? `${inboxCount.open}${inboxCount.blocking ? ` ${blockChip(`${inboxCount.blocking} blocking`)}` : ''}` : '', 'inbox'], ['/messages', 'Messages', messageCount === null ? '' : `${messageCount}`, 'talk'], ['/tasks', 'Tasks', '', 'tasks'], ['/agents', 'Agents', '', 'agents'], ['/queue', 'Queue', '', 'queue'], ['/business', 'Business', '', 'business'], ['/docs', 'Docs', '', 'library'], ['/settings', 'Settings', '', 'settings']]; $('sections').innerHTML = items.map(([h, l, extra, icon]) => { - const cur = h === '/' ? route === '/' : 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}` : ''}
  • `; + 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}` : ''}
  • `; }).join(''); if (focused) [...$('sections').querySelectorAll('a[href]')].find(a => a.getAttribute('href') === focused)?.focus({ preventScroll: true }); } @@ -1246,7 +1246,7 @@ // A refresh due while this render reads would replace it: a navigation would lose its heading focus. clearTimeout(timer); if (out()) return; - const route = routeOf(), [path, query = ''] = route.split('?'), board = path === '/' || path === ''; + const route = routeOf(), [path, query = ''] = route.split('?'), board = path === '/' || path === '' || path === '/board'; // Leaving a decision discards its confirmation immediately, including a preview in flight. if (answer && (navigated || path !== `/inbox/${answer.id}`)) answer = null; const g = ++gen; @@ -1274,10 +1274,13 @@ } if (board) { // The board page keeps its own title; the Inbox count still follows the bus. - if (shown !== null) { shown = null; unmountEditor(); $('bus-view').innerHTML = ''; document.title = 'Mosaic Console'; if (navigated) $('main').focus(); } + if (shown !== null) { shown = null; unmountEditor(); $('bus-view').innerHTML = ''; document.title = 'Dashboard · Mosaic Console'; if (navigated) $('main').focus(); } // The held roles (row 95) are read with it. A refusal of either forgets both, as on the bus pages. - const [inbox, agents, messages] = await Promise.allSettled([fetchRead('inbox'), fetchRead('agents'), fetchRead('messages')]); - const failed = [inbox, agents, messages].filter(s => s.status === 'rejected').map(s => s.reason); + const [inbox, agents, messages, tasks, queue, business, projects] = await Promise.allSettled([ + fetchRead('inbox'), fetchRead('agents'), fetchRead('messages'), fetchRead('tasks'), fetchApi('queue'), fetchApi('business'), + fetch('/api/chat/projects', { cache: 'no-store', redirect: 'manual' }).then(async r => { if (r.type === 'opaqueredirect') { signOut(); throw signedOut(); } const body = await r.json(); if (signInRequired(r, body)) { signOutSso(); throw signedOut(); } if (!r.ok || !Array.isArray(body.rows)) throw new ReadError(body?.error, body?.message, r.status); return body; }) + ]); + const failed = [inbox, agents, messages, tasks].filter(s => s.status === 'rejected').map(s => s.reason); if (failed.some(err => err.code === 'signed-out')) return; if (inbox.status === 'fulfilled') last.set('inbox', inbox.value); if (agents.status === 'fulfilled') last.set('agents', agents.value); @@ -1287,6 +1290,17 @@ if (g !== gen) return; if (inbox.status === 'fulfilled' && !refused) countInbox(inbox.value.rows); if (messages.status === 'fulfilled' && !refused) messageCount = messages.value.unread; + const good = result => !refused && result.status === 'fulfilled' ? result.value : null; + const taskRows = good(tasks)?.rows, queueRows = good(queue)?.rows, projectRows = good(projects)?.rows; + window.MosaicDashboard?.update({ + agents: good(agents)?.rows?.length ?? null, inbox: good(inbox)?.rows ?? null, + messages: Number.isFinite(good(messages)?.unread) ? good(messages).unread : null, + tasks: Array.isArray(taskRows) ? taskRows.map(r => task(r)).filter(t => !t.missing && !t.done).length : null, + queue: Array.isArray(queueRows) ? queueRows.filter(r => r.state !== 'done').length : null, + projects: Array.isArray(projectRows) ? projectRows.filter(p => !p.archived).length : null, + business: good(business)?.business?.id ?? null, + readAt: !refused && [inbox, agents, messages, tasks, queue, business, projects].some(r => r.status === 'fulfilled') ? Date.now() : null + }); paintHeld(refused || (agents.status === 'rejected' ? agents.reason : null)); sections(path); schedule(); return; @@ -1369,7 +1383,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 = [['#/', 'Board'], ['#/projects', 'Projects'], ['#/inbox', 'Inbox'], ['#/messages', 'Messages'], ['#/tasks', 'Tasks'], ['#/agents', 'Agents'], ['#/queue', 'Queue'], ['#/business', 'Business'], ['#/docs', 'Docs'], ['#/settings', 'Settings'], ['#/settings/display', 'Sidebar display']]; + const VIEWS = [['#/', 'Dashboard'], ['#/projects', 'Projects'], ['#/inbox', 'Inbox'], ['#/messages', 'Messages'], ['#/tasks', 'Tasks'], ['#/agents', 'Agents'], ['#/queue', 'Queue'], ['#/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)}` })); @@ -1455,6 +1469,7 @@ // Signed out: drop every bus read, kept ones included, and the page drawn from them. The send // form stays, with its draft and receipt, so nothing typed is lost; it sends nothing more. document.addEventListener('mosaic-signed-out', () => { + window.MosaicDashboard?.update({}); clearTimeout(timer); gen++; forget(); for (const el of [...$('bus-view').children]) if (el.id !== 'send-section') el.remove(); $('held').replaceChildren(); $('held-count').textContent = '–'; heldHtml = null; @@ -1527,12 +1542,7 @@ }).observe($('bus-view'), { childList: true, subtree: true }); // The drawer keeps the background inert and returns focus to its opener. const nav = $('console-nav'), opener = $('nav-open'), closer = $('nav-close'), scrim = $('nav-scrim'); - const processing = $('processing-controls'), mobileProcessing = $('processing-mobile'); - function placeProcessing() { - if (innerWidth < 760 && processing.parentElement !== mobileProcessing) mobileProcessing.append(processing); - else if (innerWidth >= 760 && processing.parentElement !== nav) nav.insertBefore(processing, nav.querySelector(':scope > .tree-title')); - } - placeProcessing(); + const mobileProcessing = $('processing-mobile'); let drawerOpen = false; const background = [document.querySelector('.cmdbar'), document.querySelector('.rail'), mobileProcessing, $('main'), $('inspector'), document.querySelector('.foot')]; function drawer(open, restore = true) { @@ -1556,7 +1566,7 @@ else if (!e.shiftKey && document.activeElement === controls.at(-1)) { e.preventDefault(); controls[0].focus(); } }); nav.addEventListener('click', e => { if (drawerOpen && e.target.closest('a[href^="#/"]')) drawer(false, false); }); - window.addEventListener('resize', () => { if (drawerOpen && innerWidth >= 760) drawer(false, false); placeProcessing(); if (drawerOpen) $('nav-overflow').hidden = nav.scrollHeight <= nav.clientHeight + 1; }); + window.addEventListener('resize', () => { if (drawerOpen && innerWidth >= 760) drawer(false, false); if (drawerOpen) $('nav-overflow').hidden = nav.scrollHeight <= nav.clientHeight + 1; }); window.addEventListener('hashchange', () => render(true)); $('refresh').addEventListener('click', () => render(false)); $('pause').addEventListener('click', () => setTimeout(schedule)); // after app.js flips aria-pressed diff --git a/packages/webui/src/public/index.html b/packages/webui/src/public/index.html index 8c2cfde86..b45a821cd 100644 --- a/packages/webui/src/public/index.html +++ b/packages/webui/src/public/index.html @@ -1,6 +1,6 @@ -Mosaic Console +Dashboard · Mosaic Console @@ -8,26 +8,27 @@ -
    MosaicConsole +
    Mosaic Stack - -

    -
    +

    +
    Processing unavailable
    - -

    Control board

    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.
    +

    Needs your input

    Not available yet

    Open Inbox →
    -`; } async function composer(get) { - if (!canSend) return ''; + if (!canSend) return '

    Messaging a role needs a Console started with --send behind the sign-in proxy; this one only reads.

    '; try { sendRoles = (await get('agents')).map(c => c.role).filter(r => typeof r === 'string' && SAFE.test(r)); } catch { sendRoles = null; } if (receipt?.kind === 'sent') { const r = receipt; @@ -578,7 +578,7 @@ const claims = r.rows; html = `${err ? `` : ''} ${claims.length ? heldTable(claims) : empty('No role is held on the bus right now.', 'A role shows here while a run holds its claim on the bus. Machine sessions are under Show machine sessions.')} -

    Read from the bus ${when(r.at)}.${canSend ? '' : ' Messaging a role needs a Console started with --send behind the sign-in proxy; this one only reads.'}

    `; +

    Read from the bus ${when(r.at)}.

    `; } $('held-count').textContent = err && (refusal(err) || !r) ? '–' : String(r.rows.length); if (html === heldHtml) return; // unchanged: no repeated alert, focus stays put diff --git a/packages/webui/src/public/index.html b/packages/webui/src/public/index.html index b45a821cd..0bab04afa 100644 --- a/packages/webui/src/public/index.html +++ b/packages/webui/src/public/index.html @@ -8,10 +8,10 @@ -
    Mosaic Stack - +
    Mosaic Stack +

    -
    Processing unavailable
    +
    Processing unavailable
    diff --git a/packages/webui/src/public/processing.css b/packages/webui/src/public/processing.css index 19f6c1ca0..f2ad53f7a 100644 --- a/packages/webui/src/public/processing.css +++ b/packages/webui/src/public/processing.css @@ -47,3 +47,33 @@ body.signed-out #dashboard-summary,body.signed-out #dashboard-cards,body.signed- @media(max-width:759px){.cmdbar{padding-inline:8px}.cmd-right{flex:1 1 100%;flex-wrap:wrap}.avatar-wrap>button{min-width:44px;justify-content:center;padding:4px}.avatar-wrap>button>span:last-child{display:none}} @media(max-width:759px){.processing-link{display:inline-flex;align-items:center;gap:4px;min-height:44px}} + +/* Dashboard polish: compact controls share a single row at every width. */ +.cmdbar .fresh + .cmd-right{margin-left:auto} +.cmdbar .header-action{display:inline-flex;align-items:center;justify-content:center;gap:7px;min-height:44px;padding:0 9px;border:0;border-radius:var(--r);background:transparent;color:var(--text);font:inherit;cursor:pointer;white-space:nowrap} +.cmdbar .header-action:hover{background:var(--raised)} +.cmdbar .header-action:disabled{opacity:.55;cursor:default} +.s1-section[aria-current=page]{background:var(--nav-active,color-mix(in srgb,var(--action) 22%,var(--surface)));box-shadow:inset 0 0 0 1px var(--nav-active-border,color-mix(in srgb,var(--action) 26%,transparent));color:var(--strong)} +.s1-section .count{background:var(--raised);color:var(--strong);border-radius:999px;padding:2px 7px;line-height:1.3} +.kpi div{font-size:13px;font-weight:600}.kpi strong{font-size:24px}.kpi span{font-size:12px} +.mobile-menu-item{display:none!important} +@media(max-width:759px){ + .cmdbar{position:static;flex-wrap:nowrap;gap:4px;padding:8px;min-height:64px} + #nav-open{min-width:44px;min-height:44px;justify-content:center;padding:0} + .wordmark{flex:1 1 auto;min-width:0;margin:0;font-size:16px;gap:5px} + .mosaic-logo{width:28px;height:28px} + .cmdk{order:0;flex:0 0 44px;width:44px;min-width:44px;height:44px;padding:0;justify-content:center;border:0;background:transparent} + .cmdk span,.cmdk kbd{display:none} + .cmd-right{flex:0 0 auto;gap:0;margin-left:0!important;flex-wrap:nowrap} + .cmd-right .processing-link,.cmd-right #pause{display:none} + .cmdbar .header-action{width:44px;min-width:44px;padding:0} + .cmdbar .header-action span{display:none} + .avatar-wrap>button{width:44px;min-width:44px;padding:0;justify-content:center} + .avatar-menu{position:absolute;top:calc(100% + 8px);right:0;width:min(240px,calc(100vw - 16px))} + .avatar-menu .mobile-menu-item{display:block!important} +} + +/* Extreme zoom can reduce the CSS viewport below the width of all controls. */ +@media(max-width:330px){.cmdbar{flex-wrap:wrap}.wordmark{flex:1 1 auto}.cmd-right{margin-left:auto!important}} +/* Wrap only when zoom leaves insufficient room for the controls. */ +.cmdbar{flex-wrap:wrap} diff --git a/packages/webui/src/public/processing.js b/packages/webui/src/public/processing.js index 4ed5163d7..e7dec8daa 100644 --- a/packages/webui/src/public/processing.js +++ b/packages/webui/src/public/processing.js @@ -26,6 +26,8 @@ : snapshot?.halted === false ? 'Processing is enabled.' : 'Processing state unavailable.'; const short = byId('processing-short'); if (short) short.textContent = halted ? 'Processing stopped' : snapshot?.halted === false ? 'Processing on' : 'Processing unavailable'; + const mobileShort = byId('mobile-processing-link'); + if (mobileShort && short) mobileShort.textContent = short.textContent; document.dispatchEvent(new CustomEvent('mosaic-processing-state', { detail: { halted: snapshot?.halted ?? null } })); banner.hidden = !halted; banner.textContent = 'Processing is halted for this instance. Reads and human recovery controls remain available.'; diff --git a/packages/webui/src/public/tokens.css b/packages/webui/src/public/tokens.css index 2f61fdcf2..d7f1e96eb 100644 --- a/packages/webui/src/public/tokens.css +++ b/packages/webui/src/public/tokens.css @@ -817,5 +817,9 @@ } /* Dashboard reference: default Harbor dark surfaces. */ -@media (prefers-color-scheme:dark){:root[data-palette="harbor"]:not([data-mode="light"]):not([data-mode="dim"]){--canvas:#10141d;--surface:#1a202b;--raised:#263247;--line:#404b5d;--text:#e0e8f5;--muted:#b8c5d9;--action:#64b5ff;--strong:#f6f8ff}} -:root[data-palette="harbor"][data-mode="dark"]{--canvas:#10141d;--surface:#1a202b;--raised:#263247;--line:#404b5d;--text:#e0e8f5;--muted:#b8c5d9;--action:#64b5ff;--strong:#f6f8ff} +@media (prefers-color-scheme:dark){:root[data-palette="harbor"]:not([data-mode="light"]):not([data-mode="dim"]){--canvas:#141821;--surface:#1d222b;--raised:#293446;--line:#444f60;--text:#d8e0ef;--muted:#b5c2d6;--action:#64b5ff;--strong:#f6f8ff;--nav-active:#214374;--nav-active-border:#305786}} +:root[data-palette="harbor"][data-mode="dark"]{--canvas:#141821;--surface:#1d222b;--raised:#293446;--line:#444f60;--text:#d8e0ef;--muted:#b5c2d6;--action:#64b5ff;--strong:#f6f8ff;--nav-active:#214374;--nav-active-border:#305786} + +/* Cool Harbor light equivalents for the reference surfaces. */ +:root[data-palette="harbor"][data-mode="light"]{--canvas:#f1f5fa;--surface:#ffffff;--raised:#e4edf8;--line:#c8d4e3;--text:#34445a;--muted:#53677e;--action:#2266bf;--strong:#17283f;--nav-active:#dbeafe;--nav-active-border:#b4cff2} +@media (prefers-color-scheme:light){:root[data-palette="harbor"]:not([data-mode]){--canvas:#f1f5fa;--surface:#ffffff;--raised:#e4edf8;--line:#c8d4e3;--text:#34445a;--muted:#53677e;--action:#2266bf;--strong:#17283f;--nav-active:#dbeafe;--nav-active-border:#b4cff2}} diff --git a/packages/webui/tests/board-held.test.mjs b/packages/webui/tests/board-held.test.mjs index b1feefb0a..029c9e132 100644 --- a/packages/webui/tests/board-held.test.mjs +++ b/packages/webui/tests/board-held.test.mjs @@ -156,7 +156,10 @@ test('the Board: held roles with no machine sessions, a claim with no address, t await b.navigate(`${base}?nosend`); await wait(HELD); assert.equal(await b.evaluate('document.querySelectorAll("#held [data-message-role]").length'), 0); - assert.match(await text('#held'), /--send/); + assert.doesNotMatch(await text('#held'), /--send/); + await b.evaluate("location.hash = '#/inbox'"); + await wait("document.querySelector('#bus-view').textContent.includes('Messaging a role needs')"); + assert.match(await text('#bus-view'), /Messaging a role needs a Console started with --send behind the sign-in proxy; this one only reads/); // Every Console fetch the page made asked for redirect: 'manual'. assert.deepEqual((await reqs()).filter(r => r.redirect !== 'manual'), []); } finally { await done(); } diff --git a/packages/webui/tests/dashboard-shell-browser.test.mjs b/packages/webui/tests/dashboard-shell-browser.test.mjs index 01f086e37..2f899d7cc 100644 --- a/packages/webui/tests/dashboard-shell-browser.test.mjs +++ b/packages/webui/tests/dashboard-shell-browser.test.mjs @@ -47,3 +47,18 @@ test('avatar menu supports keyboard navigation and local or SSO sign out', {time await b.evaluate('document.querySelector("#avatar-button").click()'); assert.deepEqual(await b.evaluate('(()=>{const f=document.querySelector("#sign-out");return [f.hidden,f.method,f.getAttribute("action"),document.querySelector("#local-sign-out").hidden]})()'),[false,'post','/auth/logout',true]); }); + +test('compact header keeps search and refresh usable, with pause in the avatar menu', {timeout:90000}, async t => { + const {f,b,wait}=await w15Fixture(t); + await b.call('Emulation.setDeviceMetricsOverride',{width:390,height:900,deviceScaleFactor:1,mobile:false}); + await b.navigate(f.base+'/#/'); await wait('document.querySelectorAll("#dashboard-kpis .kpi").length > 0'); + const state = await b.evaluate(`(()=>{const ids=['nav-open','cmdk','refresh','avatar-button'];const boxes=ids.map(id=>document.getElementById(id).getBoundingClientRect());return {tops:boxes.map(x=>x.top), widths:boxes.map(x=>x.width), overflow:document.documentElement.scrollWidth>innerWidth, pauseVisible:!!document.querySelector('#pause').getClientRects().length, zeroBadges:document.querySelectorAll('#sections .count').length, held:document.querySelector('#held').textContent}})()`); + assert.ok(Math.max(...state.tops)-Math.min(...state.tops)<15, JSON.stringify(state)); + assert.ok(state.widths.every(x=>x>=44)); assert.equal(state.overflow,false); assert.equal(state.pauseVisible,false); + assert.equal(state.zeroBadges,0); assert.doesNotMatch(state.held,/behind the sign-in proxy/); + await b.evaluate('document.querySelector("#cmdk").click()'); assert.equal(await b.evaluate('document.querySelector("#cmdk-dialog").open'),true); + await b.key('Escape'); await b.evaluate('document.querySelector("#avatar-button").click()'); + assert.equal(await b.evaluate('!!document.querySelector("#mobile-pause").getClientRects().length'),true); + await b.evaluate('document.querySelector("#mobile-pause").click()'); + assert.equal(await b.evaluate('document.querySelector("#pause").getAttribute("aria-pressed")'),'true'); +}); diff --git a/packages/webui/tests/messages.test.mjs b/packages/webui/tests/messages.test.mjs index 32984ece6..5101ca532 100644 --- a/packages/webui/tests/messages.test.mjs +++ b/packages/webui/tests/messages.test.mjs @@ -63,7 +63,7 @@ test('Console Messages lists late unsolicited messages on polling with sender cl const got=s.b.request(s.human,{verb:'message.receive'}); for(const m of got)s.b.request(s.human,{verb:'message.read',args:{id:m.id}}); await wait('document.querySelector("#message-list")?.textContent.includes("Read") && !document.querySelector("#message-list")?.textContent.includes("Unread")'); - assert.equal(await b.evaluate(`document.querySelector('#sections a[href="#/messages"] .count').textContent`),'0'); + assert.equal(await b.evaluate(`document.querySelector('#sections a[href="#/messages"] .count')`),null); }finally{await b.close();await close(web)} }); -- 2.54.0 From 4638c07fcc2f3415516fea4f8d8ac946209bd028 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Fri, 6 Nov 2026 11:52:47 -0600 Subject: [PATCH 004/116] style(webui): council fixes for type, surfaces, targets and focus (ui slice 1) --- packages/webui/src/public/brand.js | 12 ++++-- packages/webui/src/public/bus.js | 12 +++--- packages/webui/src/public/processing.css | 31 ++++++++++++++ packages/webui/src/public/tokens.css | 7 ++++ .../tests/dashboard-shell-browser.test.mjs | 41 +++++++++++++++++++ 5 files changed, 94 insertions(+), 9 deletions(-) diff --git a/packages/webui/src/public/brand.js b/packages/webui/src/public/brand.js index a3846a515..80540567c 100644 --- a/packages/webui/src/public/brand.js +++ b/packages/webui/src/public/brand.js @@ -80,7 +80,7 @@ (() => { if (typeof document === 'undefined' || !document.getElementById('dashboard-kpis')) return; const $ = id => document.getElementById(id); - let data = {}, halted = null; + let data = {}, halted = null, lastInboxHtml = null; const escape = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function paint() { if (!$('dashboard-kpis')) return; @@ -92,12 +92,17 @@ ]; $('dashboard-kpis').innerHTML = metrics.map(([label, value, caption]) => `
    ${label}
    ${value == null ? '–' : escape(value)}${value == null ? 'Not available yet' : caption}
    `).join(''); $('dashboard-business').textContent = data.business ? `Business · ${data.business}` : 'Business overview'; - $('dashboard-inbox-items').innerHTML = data.inbox == null ? '

    Not available yet

    ' : data.inbox.length ? `` : '

    Nothing is waiting on you.

    '; + const inboxHtml = data.inbox == null ? '

    Not available yet

    ' : data.inbox.length ? `` : '

    Nothing is waiting on you.

    '; + if (lastInboxHtml !== inboxHtml) { $('dashboard-inbox-items').innerHTML = inboxHtml; lastInboxHtml = inboxHtml; } age(); } function age() { if (!$('dashboard-updated')) return; $('dashboard-updated').textContent = data.readAt ? `Updated ${Math.max(0, Math.floor((Date.now() - data.readAt) / 1000))} s ago` : 'Not read yet'; } window.MosaicDashboard = { update(value) { data = value; paint(); } }; - document.addEventListener('mosaic-processing-state', e => { halted = e.detail.halted; paint(); }); + document.addEventListener('mosaic-processing-state', e => { + halted = e.detail.halted; + const cell = $('dashboard-kpis').lastElementChild; + if (cell) { cell.querySelector('strong').textContent = halted === null ? '–' : halted ? 'Stopped' : 'On'; cell.querySelector('span').textContent = halted === null ? 'Not available yet' : 'Instance status'; } + }); setInterval(age, 1000); const button = $('avatar-button'), menu = $('avatar-menu'); const controls = () => [...menu.querySelectorAll('a[href],button:not(:disabled),select:not(:disabled)')].filter(el => el.getClientRects().length); @@ -106,6 +111,7 @@ button.addEventListener('click', () => menu.hidden ? open() : close()); button.addEventListener('keydown', e => { if (e.key === 'Escape' && !menu.hidden) { e.preventDefault(); close(true); } else if (['ArrowDown','ArrowUp'].includes(e.key)) { e.preventDefault(); open(); const items = controls(); (e.key === 'ArrowDown' ? items[0] : items.at(-1))?.focus(); } }); menu.addEventListener('keydown', e => { if (e.key === 'Escape') { e.preventDefault(); close(true); } else if (['ArrowDown','ArrowUp'].includes(e.key) && e.target.tagName !== 'SELECT') { e.preventDefault(); const items = controls(), i = items.indexOf(document.activeElement); items[(i + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length]?.focus(); } }); + button.closest('.avatar-wrap').addEventListener('focusout', e => { if (!e.currentTarget.contains(e.relatedTarget)) close(); }); menu.addEventListener('click', e => { if (e.target.closest('a')) close(); }); document.addEventListener('click', e => { if (!e.target.closest('.avatar-wrap')) close(); }); function breadcrumbs() { diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index 2997f5ccd..836d369d1 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -234,7 +234,7 @@ const PRIORITY = ['unset', 'low', 'medium', 'high', 'urgent', 'do now']; const head = (title, sub) => `

    ${title}

    ${sub ? `

    ${sub}

    ` : ''}
    `; let readAt = null; - const readNote = () => `Read from the bus ${when(readAt)}.`; + const readNote = get => `Read from the bus ${when(get.oldest())}.`; // Lead decision 63: what no Q1 read returns carries this label where it would show. const gap = what => `${esc(what)}: not in the Q1 module`; // Which choice authorizes which action on which target, as the broker recorded it at @@ -419,7 +419,7 @@ const body = rows.length ? `
      ${rows.map(decisionCard).join('')}
    ` : empty('Nothing is waiting on you.', 'A decision shows here when an agent raises one routed to you through the bus.'); const answered = canDecide ? 'Open an eligible decision to answer any of its options here, after a confirmation. Grant requests keep their Approve and Deny confirmation. You can also use mosaic decide in a terminal.' : 'Decisions are answered in a terminal with mosaic decide; Console only shows them.'; - return `${head('Inbox', `${readNote()} ${answered}`)} + return `${head('Inbox', `${readNote(get)} ${answered}`)} ${await composer(get)}

    Open decisions ${rows.length}

    ${body}

    Not shown here yet: ${gap('Decisions routed to roles')} ${gap('Closed decisions')} ${gap('Seen and DM state per row')} Open a decision for its seen, DM and closing history.

    `; @@ -431,7 +431,7 @@ const body = page.rows.length ? `
      ${page.rows.map(m => `
    • ${txt(m.from_role)} · ${txt(m.class)} · ${when(m.at)} · ${m.read ? 'Read' : 'Unread'} · trail

      ${txt(m.body)}

    • `).join('')}
    ` : empty('No messages to you.', 'Messages appear here as the bus is read.'); - return `${head('Messages', `${readNote()} Every message to you, newest first. Reading here marks nothing read.`)} + return `${head('Messages', `${readNote(get)} Every message to you, newest first. Reading here marks nothing read.`)}

    ${page.total} messages · ${page.unread} unread

    ${body} `; } @@ -537,7 +537,7 @@ const ext = t.external ? `
    Vikunja
    ${t.external.kind === 'foreign' ? 'Not created by the stack; first read' : 'Changed in Vikunja after the stack wrote it'}${t.external.changed.length ? `: ${txt(t.external.changed.join(', '))}` : ''}${t.external.comments ? `, ${esc(plural(t.external.comments, 'new comment'))}` : ''} ${txt(t.external.via)} read sent ${clock(t.external.readAt)}
    ` : ''; const conflicts = t.conflicts.length ? `
    Refused writes
    ${t.conflicts.map(c => `${txt(c.verb)}: Vikunja changed after the stack read it (expected ${txt(short(c.expected))}, found ${txt(short(c.actual))}) ${when(c.at)}`).join('
    ')}
    ` : ''; const decisions = t.decisions.length ? `
    Decisions
    ${t.decisions.map(d => `${txt(short(d.id))} ${txt(first(d.question))}`).join('
    ')}
    ` : ''; - const sub = t.missing ? `No longer readable in Vikunja (${txt(t.missing.reason)}${t.missing.project ? `, now in project ${txt(t.missing.project)}` : ''}) since ${when(t.missing.at)}.` : `${t.done ? 'Done' : `In bucket ${esc(t.bucket)}`}, last changed ${when(t.changedAt)}. ${readNote()}`; + const sub = t.missing ? `No longer readable in Vikunja (${txt(t.missing.reason)}${t.missing.project ? `, now in project ${txt(t.missing.project)}` : ''}) since ${when(t.missing.at)}.` : `${t.done ? 'Done' : `In bucket ${esc(t.bucket)}`}, last changed ${when(t.changedAt)}. ${readNote(get)}`; return `${head(title(t), `${sub} ${markers(t)}`)}

    Task

    Ref
    ${txt(t.ref)} ${gap('The Vikunja address')}
    Assignees
    ${t.assignees.map(user).join(', ') || 'none'} ${gap('Bot names')}
    Requirement
    ${txt(t.requirement || 'none')}
    Due
    ${due(t.due)}
    Priority
    ${priority(t.priority)}
    Done
    ${esc(t.percent)}%
    ${ext}${conflicts}${decisions}
    ${t.description ? `

    Description

    ${txt(t.description)}

    ` : ''} @@ -612,7 +612,7 @@ const claims = await get('agents'); const threadSection = await threadClaimsSection(get); 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(c.holder_run)}${txt(c.harness)}${c.address ? `${txt(c.address)}` : ''}${when(c.at)}`).join(''); - return `${head('Agents', readNote())} + return `${head('Agents', readNote(get))}

    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} @@ -1010,7 +1010,7 @@ const base = `#/trail/${kind}/${enc(ref)}`; const name = kind === 'task' ? `Trail for task #${esc(String(ref).split('/')[1])}` : `Trail for ${kind} ${txt(short(ref))}`; const back = kind === 'task' ? `Back to the task` : kind === 'message' ? 'Back to the Inbox' : `Back to the decision`; - return `${head(name, `${readNote()} Oldest first. ${back}`)} + return `${head(name, `${readNote(get)} Oldest first. ${back}`)} ${trailList(rows, filter)}`; } diff --git a/packages/webui/src/public/processing.css b/packages/webui/src/public/processing.css index f2ad53f7a..419c40a6d 100644 --- a/packages/webui/src/public/processing.css +++ b/packages/webui/src/public/processing.css @@ -77,3 +77,34 @@ body.signed-out #dashboard-summary,body.signed-out #dashboard-cards,body.signed- @media(max-width:330px){.cmdbar{flex-wrap:wrap}.wordmark{flex:1 1 auto}.cmd-right{margin-left:auto!important}} /* Wrap only when zoom leaves insufficient room for the controls. */ .cmdbar{flex-wrap:wrap} + +/* Round 3: reference hierarchy, navigation and keyboard targets. */ +.tree,footer.foot{background:var(--nav-surface)} +.content h1{font-size:var(--title-size);font-weight:800} +#dashboard-business{font-size:var(--subtitle-size)} +#held-section h2,.dashboard-card h2{font-size:var(--section-size);font-weight:700} +.breadcrumbs{font-size:var(--breadcrumb-size);flex-wrap:wrap}.breadcrumbs > *{min-width:0;overflow-wrap:anywhere} +.s1-section{font-size:var(--nav-label-size);font-weight:500;color:var(--strong)} +.s1-section svg.i{width:var(--nav-icon-size);height:var(--nav-icon-size);stroke-width:var(--nav-icon-stroke)} +.s1-section[aria-current=page] svg{color:var(--strong)} +.mosaic-logo rect:nth-child(1){fill:var(--logo-a)}.mosaic-logo rect:nth-child(2){fill:var(--logo-b)}.mosaic-logo rect:nth-child(3){fill:var(--logo-c)}.mosaic-logo rect:nth-child(4){fill:var(--logo-d)} +.avatar-initial,.btn.primary{background:var(--accent-fill);color:var(--on-accent)}.btn.primary{border-color:var(--accent-fill)} +#dashboard-summary,.dashboard-card{border-radius:var(--dashboard-radius)} +.kpi{border-color:var(--line-soft)}.kpi div{font-size:var(--kpi-label-size);font-weight:600}.kpi strong{font-size:var(--kpi-value-size);font-weight:700}.kpi span{font-size:var(--kpi-caption-size)} +.kpi-footer{border-top:0;padding:0 18px 16px} +.content h2 .count{font-size:inherit;font-weight:inherit;line-height:inherit;color:var(--muted);background:none;border-radius:0;padding:0;margin-left:0;vertical-align:baseline}.content h2 .count::before{content:'· '} +#bus-view:has(> .chat-area){container-type:inline-size} +.chat-area > h1,.chat-area > h1 + p{position:relative;left:min(0px,calc((72rem - 100cqw)/2))} +.processing-link,#dashboard-inbox > a,#board-head .filters label{display:inline-flex;align-items:center;min-height:44px} +.avatar-menu a[role=menuitem],.avatar-menu button[role=menuitem]{display:flex;align-items:center;min-height:44px} +.avatar-menu #local-sign-out{opacity:1;color:var(--muted)} +#dashboard-processing .btn:disabled{opacity:1;color:var(--muted)} +@media(max-width:759px){ + .content h1{font-size:var(--title-size-mobile)} + #held-section h2,.dashboard-card h2{font-size:var(--section-size-mobile)} + .kpi strong{font-size:var(--kpi-value-size-mobile)} + .cmdbar #nav-open{border:0;background:transparent;color:var(--text)} + .avatar-menu .mobile-menu-item{display:flex!important} + .cmd-right .processing-link{display:none} +} +@media(min-width:760px) and (max-width:1100px){.kpi-grid{grid-template-columns:repeat(4,minmax(0,1fr));row-gap:16px}.kpi:nth-child(4){border-right:0}} diff --git a/packages/webui/src/public/tokens.css b/packages/webui/src/public/tokens.css index d7f1e96eb..428331d6c 100644 --- a/packages/webui/src/public/tokens.css +++ b/packages/webui/src/public/tokens.css @@ -823,3 +823,10 @@ /* Cool Harbor light equivalents for the reference surfaces. */ :root[data-palette="harbor"][data-mode="light"]{--canvas:#f1f5fa;--surface:#ffffff;--raised:#e4edf8;--line:#c8d4e3;--text:#34445a;--muted:#53677e;--action:#2266bf;--strong:#17283f;--nav-active:#dbeafe;--nav-active-border:#b4cff2} @media (prefers-color-scheme:light){:root[data-palette="harbor"]:not([data-mode]){--canvas:#f1f5fa;--surface:#ffffff;--raised:#e4edf8;--line:#c8d4e3;--text:#34445a;--muted:#53677e;--action:#2266bf;--strong:#17283f;--nav-active:#dbeafe;--nav-active-border:#b4cff2}} + +/* Slice 1 chrome tokens; palette overrides keep custom palettes coherent. */ +:root{--nav-surface:var(--canvas);--line-soft:var(--line);--accent-fill:var(--action);--on-accent:var(--onAction);--logo-a:var(--action);--logo-b:color-mix(in srgb,var(--action) 75%,var(--strong));--logo-c:var(--action);--logo-d:color-mix(in srgb,var(--action) 45%,var(--canvas));--dashboard-radius:10px;--title-size:32px;--subtitle-size:16px;--section-size:23px;--breadcrumb-size:14px;--kpi-value-size:30px;--kpi-label-size:14px;--kpi-caption-size:12px;--nav-label-size:14px;--nav-icon-size:20px;--nav-icon-stroke:1.75;--title-size-mobile:26px;--section-size-mobile:21px;--kpi-value-size-mobile:26px} +:root[data-palette="harbor"][data-mode="dark"]{--nav-surface:#10141c;--line-soft:#333b47;--accent-fill:#276bd8;--on-accent:#ffffff;--logo-a:#3691f2;--logo-b:#4a9af5;--logo-c:#3691f2;--logo-d:#1b3e79} +@media(prefers-color-scheme:dark){:root[data-palette="harbor"]:not([data-mode="light"]):not([data-mode="dim"]){--nav-surface:#10141c;--line-soft:#333b47;--accent-fill:#276bd8;--on-accent:#ffffff;--logo-a:#3691f2;--logo-b:#4a9af5;--logo-c:#3691f2;--logo-d:#1b3e79}} +:root[data-palette="harbor"][data-mode="light"]{--nav-surface:#f7f9fc;--accent-fill:#2266bf;--on-accent:#ffffff} +@media(prefers-color-scheme:light){:root[data-palette="harbor"]:not([data-mode]){--nav-surface:#f7f9fc;--accent-fill:#2266bf;--on-accent:#ffffff}} diff --git a/packages/webui/tests/dashboard-shell-browser.test.mjs b/packages/webui/tests/dashboard-shell-browser.test.mjs index 2f899d7cc..5b96ba1dd 100644 --- a/packages/webui/tests/dashboard-shell-browser.test.mjs +++ b/packages/webui/tests/dashboard-shell-browser.test.mjs @@ -46,6 +46,7 @@ test('avatar menu supports keyboard navigation and local or SSO sign out', {time await b.call('Page.reload'); await wait('!!document.querySelector("#sign-out") && !document.querySelector("#sign-out").hidden'); await b.evaluate('document.querySelector("#avatar-button").click()'); assert.deepEqual(await b.evaluate('(()=>{const f=document.querySelector("#sign-out");return [f.hidden,f.method,f.getAttribute("action"),document.querySelector("#local-sign-out").hidden]})()'),[false,'post','/auth/logout',true]); + assert.deepEqual(await b.evaluate('(()=>{const r=document.querySelector("#sign-out button").getBoundingClientRect();return [r.width>=44,r.height>=44]})()'),[true,true]); }); test('compact header keeps search and refresh usable, with pause in the avatar menu', {timeout:90000}, async t => { @@ -62,3 +63,43 @@ test('compact header keeps search and refresh usable, with pause in the avatar m await b.evaluate('document.querySelector("#mobile-pause").click()'); assert.equal(await b.evaluate('document.querySelector("#pause").getAttribute("aria-pressed")'),'true'); }); + +test('processing polls preserve decision focus and unchanged inbox nodes', {timeout:90000}, async t => { + const {f,b,wait}=await w15Fixture(t,{scenario:{'/api/bus/inbox':{rows:[{id:'decision-1',question:"Jason's direction?"}]},'/api/processing':{halted:false}}}); + await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`document.addEventListener('mosaic-processing-state',()=>window.__processingReads=(window.__processingReads||0)+1)`}); + await b.navigate(f.base+'/#/'); + await wait('document.querySelector("#dashboard-inbox-items a") && window.__processingReads'); + const reads=await b.evaluate('window.__processingReads'); + await b.evaluate('window.__focusedDecision=document.querySelector("#dashboard-inbox-items a");window.__focusedDecision.focus()'); + await wait(`window.__processingReads > ${reads}`); + await b.evaluate(`window.MosaicDashboard.update({inbox:[{id:'decision-1',question:"Jason's direction?"}]})`); + assert.equal(await b.evaluate('document.activeElement===window.__focusedDecision && window.__focusedDecision.isConnected'),true); +}); + +test('avatar closes when Tab or Shift+Tab leaves its wrapper', {timeout:90000}, async t => { + const {f,b,wait}=await w15Fixture(t); + await b.navigate(f.base+'/#/'); await wait('!!document.querySelector("#avatar-button")'); + await b.evaluate('document.querySelector("#avatar-button").focus()'); await b.key('ArrowDown'); + await b.evaluate('document.querySelector("#mode").focus()'); await b.key('Tab'); + assert.deepEqual(await b.evaluate('[document.querySelector("#avatar-menu").hidden,document.querySelector("#avatar-button").getAttribute("aria-expanded")]'),[true,'false']); + await b.evaluate('document.querySelector("#avatar-button").focus()'); await b.key('ArrowDown'); + await b.evaluate('document.querySelector("#avatar-button").focus()'); await b.key('Tab','Tab',8); + assert.deepEqual(await b.evaluate('[document.querySelector("#avatar-menu").hidden,document.querySelector("#avatar-button").getAttribute("aria-expanded")]'),[true,'false']); +}); + +test('dashboard primary targets have 44px width and height', {timeout:90000}, async t => { + const {f,b,wait}=await w15Fixture(t); await b.viewport(1440,1000); await b.navigate(f.base+'/#/'); + await wait('document.querySelectorAll("#dashboard-kpis .kpi").length'); + for (const width of [1440,390]) { + await b.viewport(width,900); await b.evaluate('document.querySelector("#avatar-button").click()'); + const boxes=await b.evaluate(`(()=>{const selectors=['#avatar-menu a[role=menuitem]','#avatar-menu button[role=menuitem]','#dashboard-inbox > a','#show-machine'].concat(innerWidth>=760?['#processing-link']:[]);return selectors.flatMap(s=>[...document.querySelectorAll(s)].filter(e=>e.getClientRects().length).map(e=>{const r=(s==='#show-machine'?e.closest('label'):e).getBoundingClientRect();return [s,r.width,r.height]}))})()`); + assert.ok(boxes.every(([,w,h])=>w>=44&&h>=44),JSON.stringify(boxes)); + await b.evaluate('document.querySelector("#avatar-button").click()'); + } +}); + +test('Inbox reports the time of its first successful bus read', {timeout:90000}, async t => { + const {f,b,wait}=await w15Fixture(t); await b.navigate(f.base+'/#/inbox'); + await wait('document.querySelector("#bus-view h1")?.textContent === "Inbox"'); + assert.doesNotMatch(await b.evaluate('document.querySelector("#bus-status").textContent'),/Read from the bus never/); +}); -- 2.54.0 From f12021c6d744b143073e615df22f7bcdca99545f Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Fri, 6 Nov 2026 12:10:11 -0600 Subject: [PATCH 005/116] fix: dev local owner mode requires the named instance's data-root marker --- docs/SESSIONS.md | 1 + packages/cli/src/cli.mjs | 2 +- packages/cli/src/config.mjs | 4 +- packages/webui/src/cli.mjs | 2 +- packages/webui/tests/dev-local-owner.test.mjs | 38 ++++++++++++++++++- 5 files changed, 42 insertions(+), 5 deletions(-) diff --git a/docs/SESSIONS.md b/docs/SESSIONS.md index 0eee225a1..979b074a1 100644 --- a/docs/SESSIONS.md +++ b/docs/SESSIONS.md @@ -2105,3 +2105,4 @@ are never rewritten or removed; corrections are new entries. 2026-11-06 UTC | Codex implementation sub-agent | #797 Files heading and remount polish on files-polish from 4cc3d05b3 | Single caller heading and fenced sign-out-cleared DOM cache; Node 26 authorized browser gates 91/0/0/0, exact-base behavioral controls and fixture correction recorded in /mnt/storage/scratch/mosaic-lead/mvp3/files-polish-report.md. Queue refused linked worktree; canonical queue reported nothing for this seat. One local candidate for independent review; no push, merge or deployment. 2026-11-06 UTC | mvp3-lead-797 (Claude, #797 lane) | files-polish r2 on 86383a9d1 for Sol r1 F1/F2 | Per-key commit order fences live paints and caches the newest completed result; reviewer probes ported; r1 negative 11/2, w15-files 13/13, caller browser gate 93/0/0/0. Evidence: /mnt/storage/scratch/mosaic-lead/mvp3/files-polish-r2-evidence/. 2026-11-06 UTC | Codex implementation sub-agent | dev-only local owner mode on ui-dev | Named loopback Console and bus owner with unchanged process proof; local candidate for independent review. Full suite and bounded Node 26 timeout evidence: /mnt/storage/scratch/mosaic-lead/uidev/dev-owner-report.md. Queue refused linked worktree; no push, merge or deployment. +2026-11-06 UTC | Codex implementation sub-agent | dev local owner named data-root claim correction on ui-dev | Both entry points use the existing named-instance validator; missing, mismatched and hard-linked claims refuse before startup. Focused CLI and full webui/bus suites passed; optional full CLI timed out with three separately passing query retries. Evidence: /mnt/storage/scratch/mosaic-lead/uidev/dev-owner-report.md. Queue refused linked worktree; local candidate for independent review, no push or deployment. diff --git a/packages/cli/src/cli.mjs b/packages/cli/src/cli.mjs index 4c0e3f50d..e9e0e3672 100644 --- a/packages/cli/src/cli.mjs +++ b/packages/cli/src/cli.mjs @@ -555,7 +555,7 @@ async function bus(rest, io, deps) { if (parsed.flags.has("--dev-local-owner") && parsed.flags.has("--pm")) throw usage("--dev-local-owner cannot be combined with --pm"); const instance = parsed.flags.has("--dev-local-owner") ? devOwnerInstance(io.env) : null; const businessId = parsed.positional[0]; - const system = deps.system ?? loadSystem({ env: io.env }); + const system = instance ? loadSystem({ env: io.env, instance }) : (deps.system ?? loadSystem({ env: io.env })); // Fail closed, and say so (vikunja:19/302): a refused load is recorded where the Console and // `bus status` can read it, then thrown as before. No retry. const file = businessFilePath(businessId, configDir(io.env)); diff --git a/packages/cli/src/config.mjs b/packages/cli/src/config.mjs index 95dc8274f..3c84e3c2d 100644 --- a/packages/cli/src/config.mjs +++ b/packages/cli/src/config.mjs @@ -21,8 +21,8 @@ export const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", // `/bus/writer.lock` (packages/bus/src/store.mjs). export const socketPath = (dataRoot) => join(dataRoot, "bus", "broker.sock"); -export function loadSystem({ env = process.env } = {}) { - const proc = spawnSync(process.execPath, [join(REPO, "scripts", "mosaic-config.mjs"), "validate"], { +export function loadSystem({ env = process.env, instance = null } = {}) { + const proc = spawnSync(process.execPath, [join(REPO, "scripts", "mosaic-config.mjs"), "validate", ...(instance === null ? [] : ["--instance", instance])], { encoding: "utf8", maxBuffer: 1024 * 1024, env, diff --git a/packages/webui/src/cli.mjs b/packages/webui/src/cli.mjs index a98a2c8a9..9ca3a5745 100644 --- a/packages/webui/src/cli.mjs +++ b/packages/webui/src/cli.mjs @@ -76,7 +76,7 @@ try { let bus = null, send = null, settingsWrite = null, projectFiles = null, projectFile = null, libraryFile = null, libraryStatus = null, librarySync = null, libraryRevert = null, librarySave = null, projectSave = null, chat = null, nameWrite = null, assistantStop = null, instancesWrite = null, routesWrite = null, agentWrite = null, proxyCall = null, decisionWrite = null, requestRead = null, requestWrite = null, busLine, system = null; let processing = null, ownerCall = null; try { - system = loadSystem(); + system = loadSystem({ instance }); const { dataRoot } = system; const call = ownerCall = busCaller({ dataRoot, socket: socketPath(dataRoot), business: options.business ?? null }); // FED R6 (#1800): the bus-backed options, shared with each granted user's session (console-bus.mjs). diff --git a/packages/webui/tests/dev-local-owner.test.mjs b/packages/webui/tests/dev-local-owner.test.mjs index 230744bd7..1ac80c916 100644 --- a/packages/webui/tests/dev-local-owner.test.mjs +++ b/packages/webui/tests/dev-local-owner.test.mjs @@ -31,6 +31,41 @@ test('dev owner refuses a named config symlink to the default config', async t = const r=run(['--dev-local-owner'],{HOME:home,MOSAIC_CONFIG:join(named,'config.json')}); assert.equal(r.status,2); assert.match(r.stderr,/--dev-local-owner requires a named instance/); }); + +for (const scenario of [ + { name: 'missing marker', owner: null, reason: /instance-root-unclaimed.*holds no instance\.json naming test/ }, + { name: 'default dev marker', owner: 'dev', reason: /instance-root-mismatch.*claimed by instance dev, not test/ }, + { name: 'different instance marker', owner: 'other', reason: /instance-root-mismatch.*claimed by instance other, not test/ }, + { name: 'named hard link to default config', owner: 'dev', hardLink: true, reason: /instance-root-mismatch.*claimed by instance dev, not test/ }, +]) { + test(`dev owner entry points refuse ${scenario.name} before startup`, async t => { + const { existsSync, linkSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } = await import('node:fs'); + const { tmpdir } = await import('node:os'); + const { join } = await import('node:path'); + const { fixture } = await import('../../cli/tests/helpers.mjs'); + const root = mkdtempSync(join(tmpdir(), 'dev-owner-claim-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + const f = fixture(root), home = join(root, 'home'), base = join(home, '.config'); + mkdirSync(base, { recursive: true }); + if (scenario.hardLink) { + renameSync(join(root, 'config'), join(base, 'mosaic-dev')); + mkdirSync(join(base, 'mosaic-test')); + linkSync(join(base, 'mosaic-dev', 'config.json'), join(base, 'mosaic-test', 'config.json')); + } else renameSync(join(root, 'config'), join(base, 'mosaic-test')); + if (scenario.owner) writeFileSync(join(f.dataRoot, 'instance.json'), JSON.stringify({ instanceVersion: 1, name: scenario.owner })); + const env = { ...f.env, HOME: home, MOSAIC_CONFIG: join(base, 'mosaic-test', 'config.json') }; + for (const args of [ + ['packages/webui/src/cli.mjs', 'serve', '--port', '0', '--dev-local-owner'], + ['packages/cli/src/cli.mjs', 'bus', 'start', 'acme', '--dev-local-owner'], + ]) { + const r = spawnSync(process.execPath, args, { env, encoding: 'utf8', timeout: 3000 }); + assert.notEqual(r.status, 0, args.join(' ')); + assert.match(r.stderr, scenario.reason, args.join(' ')); + assert.doesNotMatch(r.stdout, /DEV LOCAL OWNER MODE|Mosaic Console:|bus host up:/); + assert.equal(existsSync(join(f.dataRoot, 'bus')), false, 'no bus startup state'); + } + }); +} test('dev identity is fixed and cannot be configured as a real SSO issuer', () => { const provider = createDevOwner(), a = provider.session(), b = provider.session(); assert.equal(a,b); assert.deepEqual({provider:a.provider,iss:a.iss,sub:a.sub}, DEV_OWNER); @@ -54,7 +89,7 @@ test('dev owner enforces exact Host and Origin and exposes mode', async t => { }); test('dev owner resolves a decision through the real Console wrapper and bus', {timeout:90000}, async t => { - const { mkdtempSync, mkdirSync, renameSync, openSync, closeSync, readFileSync, rmSync } = await import('node:fs'); + const { mkdtempSync, mkdirSync, renameSync, openSync, closeSync, readFileSync, rmSync, writeFileSync } = await import('node:fs'); const { tmpdir } = await import('node:os'); const { join } = await import('node:path'); const { spawn } = await import('node:child_process'); @@ -66,6 +101,7 @@ test('dev owner resolves a decision through the real Console wrapper and bus', { t.after(()=>rmSync(root,{recursive:true,force:true})); const f=fixture(root); notifyConfig(f.dataRoot, 'acme', null); const home=join(root,'home'), configDir=join(home,'.config','mosaic-test'); mkdirSync(join(home,'.config'),{recursive:true}); renameSync(join(root,'config'),configDir); + writeFileSync(join(f.dataRoot,'instance.json'), JSON.stringify({instanceVersion:1,name:'test'})); const env={...f.env,HOME:home,MOSAIC_CONFIG:join(configDir,'config.json')}; const system=loadSystem({env}), boot=bootConfig({system,businessId:'acme',env}); const store=new Store(f.dataRoot), broker=new Broker({store,businesses:boot.businesses}); -- 2.54.0 From 545f77dd866b0a855d76cfda88941ac2d33b9563 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Fri, 6 Nov 2026 12:12:25 -0600 Subject: [PATCH 006/116] feat(webui): dark/light switch in the navbar (ui slice 1) --- packages/webui/src/public/app.js | 9 ++++++ packages/webui/src/public/index.html | 2 +- packages/webui/src/public/processing.css | 10 +++++++ .../tests/dashboard-shell-browser.test.mjs | 6 ++-- packages/webui/tests/shell.test.mjs | 6 ++-- .../webui/tests/theme-switch-browser.test.mjs | 30 +++++++++++++++++++ 6 files changed, 57 insertions(+), 6 deletions(-) create mode 100644 packages/webui/tests/theme-switch-browser.test.mjs diff --git a/packages/webui/src/public/app.js b/packages/webui/src/public/app.js index 90ea07b0c..b736b4a66 100644 --- a/packages/webui/src/public/app.js +++ b/packages/webui/src/public/app.js @@ -50,6 +50,11 @@ const row = id => data?.sessions.find(r => key(r) === id); const announce = text => { $('announce').textContent = text; }; // Colours come from tokens.css by data-palette and data-mode. System removes data-mode, so the OS setting picks light or dark. + const darkPreference = window.matchMedia('(prefers-color-scheme: dark)'); + function syncThemeSwitch() { + const dark = mode === 'dark' || mode === 'dim' || (mode === 'system' && darkPreference.matches); + $('theme-switch').setAttribute('aria-checked', String(dark)); + } function theme() { const p = Brand.palettes.find(p => p.id === palette) || Brand.palettes[0]; palette = p.id; @@ -57,6 +62,7 @@ document.documentElement.dataset.palette = palette; if (mode === 'system') delete document.documentElement.dataset.mode; else document.documentElement.dataset.mode = mode; $('palette').value = palette; $('mode').value = mode; + syncThemeSwitch(); try { localStorage.setItem('mosaic-console-appearance', JSON.stringify({ palette, mode })); } catch {} } $('palette').innerHTML = Brand.palettes.map(p => ``).join(''); @@ -64,6 +70,9 @@ theme(); $('palette').onchange = e => { palette = e.target.value; theme(); }; $('mode').onchange = e => { mode = e.target.value; theme(); }; + $('mobile-refresh').onclick = () => $('refresh').click(); + $('theme-switch').onclick = () => { $('mode').value = $('theme-switch').getAttribute('aria-checked') === 'true' ? 'light' : 'dark'; $('mode').dispatchEvent(new Event('change', { bubbles: true })); }; + darkPreference.addEventListener('change', syncThemeSwitch); function seenButton(r) { if (!['waiting', 'error'].includes(r.state) || !r.lastActivity) return ''; return ``; diff --git a/packages/webui/src/public/index.html b/packages/webui/src/public/index.html index 0bab04afa..a16a16f95 100644 --- a/packages/webui/src/public/index.html +++ b/packages/webui/src/public/index.html @@ -11,7 +11,7 @@
    Mosaic Stack

    -
    Processing unavailable
    +
    Processing unavailable
    diff --git a/packages/webui/src/public/processing.css b/packages/webui/src/public/processing.css index 419c40a6d..5e390ade5 100644 --- a/packages/webui/src/public/processing.css +++ b/packages/webui/src/public/processing.css @@ -108,3 +108,13 @@ body.signed-out #dashboard-summary,body.signed-out #dashboard-cards,body.signed- .cmd-right .processing-link{display:none} } @media(min-width:760px) and (max-width:1100px){.kpi-grid{grid-template-columns:repeat(4,minmax(0,1fr));row-gap:16px}.kpi:nth-child(4){border-right:0}} + +/* Appearance toggle shares the existing saved appearance setting. */ +.theme-switch{display:inline-flex;align-items:center;justify-content:center;width:56px;min-width:56px;height:44px;padding:0;border:0;border-radius:var(--r);background:transparent;color:var(--muted);cursor:pointer} +.theme-switch:hover{background:var(--raised)} +.theme-switch:focus-visible{outline:2px solid var(--action);outline-offset:2px} +.theme-track{position:relative;display:flex;align-items:center;justify-content:space-between;width:42px;height:24px;padding:4px;border:1px solid var(--line);border-radius:999px;background:var(--raised)} +.theme-track svg{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round} +.theme-thumb{position:absolute;left:3px;top:3px;width:16px;height:16px;border-radius:50%;background:var(--action);transition:transform .15s ease} +.theme-switch[aria-checked="true"] .theme-thumb{transform:translateX(18px)} +@media(max-width:759px){.theme-switch{width:48px;min-width:48px}.cmd-right #refresh{display:none}} diff --git a/packages/webui/tests/dashboard-shell-browser.test.mjs b/packages/webui/tests/dashboard-shell-browser.test.mjs index 5b96ba1dd..68c197b4d 100644 --- a/packages/webui/tests/dashboard-shell-browser.test.mjs +++ b/packages/webui/tests/dashboard-shell-browser.test.mjs @@ -49,17 +49,19 @@ test('avatar menu supports keyboard navigation and local or SSO sign out', {time assert.deepEqual(await b.evaluate('(()=>{const r=document.querySelector("#sign-out button").getBoundingClientRect();return [r.width>=44,r.height>=44]})()'),[true,true]); }); -test('compact header keeps search and refresh usable, with pause in the avatar menu', {timeout:90000}, async t => { +test('compact header keeps search and theme switch usable, with refresh and pause in the avatar menu', {timeout:90000}, async t => { const {f,b,wait}=await w15Fixture(t); await b.call('Emulation.setDeviceMetricsOverride',{width:390,height:900,deviceScaleFactor:1,mobile:false}); await b.navigate(f.base+'/#/'); await wait('document.querySelectorAll("#dashboard-kpis .kpi").length > 0'); - const state = await b.evaluate(`(()=>{const ids=['nav-open','cmdk','refresh','avatar-button'];const boxes=ids.map(id=>document.getElementById(id).getBoundingClientRect());return {tops:boxes.map(x=>x.top), widths:boxes.map(x=>x.width), overflow:document.documentElement.scrollWidth>innerWidth, pauseVisible:!!document.querySelector('#pause').getClientRects().length, zeroBadges:document.querySelectorAll('#sections .count').length, held:document.querySelector('#held').textContent}})()`); + const state = await b.evaluate(`(()=>{const ids=['nav-open','cmdk','theme-switch','avatar-button'];const boxes=ids.map(id=>document.getElementById(id).getBoundingClientRect());return {tops:boxes.map(x=>x.top), widths:boxes.map(x=>x.width), overflow:document.documentElement.scrollWidth>innerWidth, pauseVisible:!!document.querySelector('#pause').getClientRects().length, zeroBadges:document.querySelectorAll('#sections .count').length, held:document.querySelector('#held').textContent}})()`); assert.ok(Math.max(...state.tops)-Math.min(...state.tops)<15, JSON.stringify(state)); assert.ok(state.widths.every(x=>x>=44)); assert.equal(state.overflow,false); assert.equal(state.pauseVisible,false); assert.equal(state.zeroBadges,0); assert.doesNotMatch(state.held,/behind the sign-in proxy/); await b.evaluate('document.querySelector("#cmdk").click()'); assert.equal(await b.evaluate('document.querySelector("#cmdk-dialog").open'),true); await b.key('Escape'); await b.evaluate('document.querySelector("#avatar-button").click()'); + assert.equal(await b.evaluate('!!document.querySelector("#mobile-refresh").getClientRects().length && !document.querySelector("#refresh").getClientRects().length'),true); assert.equal(await b.evaluate('!!document.querySelector("#mobile-pause").getClientRects().length'),true); + assert.equal(await b.evaluate('(()=>{let n=0;document.querySelector("#refresh").addEventListener("click",()=>n++,{once:true});document.querySelector("#mobile-refresh").click();return n})()'),1); await b.evaluate('document.querySelector("#mobile-pause").click()'); assert.equal(await b.evaluate('document.querySelector("#pause").getAttribute("aria-pressed")'),'true'); }); diff --git a/packages/webui/tests/shell.test.mjs b/packages/webui/tests/shell.test.mjs index fcb45a0ea..fe4681153 100644 --- a/packages/webui/tests/shell.test.mjs +++ b/packages/webui/tests/shell.test.mjs @@ -326,7 +326,7 @@ test('shell in a browser: System default, seeded states, 400px, focus and the Ct // Ctrl+K: opens on the views and the kept tasks, filters, Enter goes, Esc restores focus. await go('#/inbox', 'Inbox'); - await b.evaluate('document.querySelector("#refresh").focus()'); + await b.evaluate('document.querySelector("#theme-switch").focus()'); await b.key('k', 'KeyK', 3); await new Promise(r => setTimeout(r, 200)); assert.equal(await b.evaluate('document.querySelector("#cmdk-dialog").open'), false, 'Ctrl+Alt+K opens nothing'); await b.key('k', 'KeyK', 2); await wait('document.querySelector("#cmdk-dialog").open'); @@ -336,14 +336,14 @@ test('shell in a browser: System default, seeded states, 400px, focus and the Ct assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#cmdk-list [data-href]")].map(e=>e.dataset.href)'), ['#/agents']); // The view render focuses its h1; wait for it so a late render can't take focus from the next step. await b.key('Enter'); await wait('location.hash==="#/agents" && !document.querySelector("#cmdk-dialog").open && document.activeElement===document.querySelector("#bus-view h1") && document.activeElement.textContent==="Agents"'); - await b.evaluate('document.querySelector("#refresh").focus()'); + await b.evaluate('document.querySelector("#theme-switch").focus()'); await b.key('k', 'KeyK', 2); await wait('document.querySelector("#cmdk-dialog").open'); await b.call('Input.insertText', { text: 'kept' }); assert.equal(await b.evaluate('document.querySelector("#cmdk-list [aria-selected=true]").dataset.href'), '#/tasks/vikunja%3A32%2F7'); await b.key('ArrowDown'); await b.key('ArrowUp'); assert.equal(await b.evaluate('document.querySelector("#cmdk-input").getAttribute("aria-activedescendant")'), 'cmdk-opt-0'); await flat(); await shot('palette-400'); - await b.key('Escape'); await wait('!document.querySelector("#cmdk-dialog").open && document.activeElement?.id==="refresh"'); + await b.key('Escape'); await wait('!document.querySelector("#cmdk-dialog").open && document.activeElement?.id==="theme-switch"'); await b.evaluate('{const c=document.querySelector("#cmdk");c.focus();c.click()}'); await wait('document.querySelector("#cmdk-dialog").open'); await b.call('Input.insertText', { text: 'zzzz' }); assert.match(await text('#cmdk-list'), /No view, decision or task matches\./); diff --git a/packages/webui/tests/theme-switch-browser.test.mjs b/packages/webui/tests/theme-switch-browser.test.mjs new file mode 100644 index 000000000..5c807f8aa --- /dev/null +++ b/packages/webui/tests/theme-switch-browser.test.mjs @@ -0,0 +1,30 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { w15Fixture } from './w15-fixture.mjs'; + +test('navbar theme switch follows and persists appearance', {timeout:90000}, async t => { + const {f,b,wait}=await w15Fixture(t); + await b.call('Emulation.setEmulatedMedia',{features:[{name:'prefers-color-scheme',value:'light'}]}); + await b.navigate(f.base+'/#/'); await wait('!!document.querySelector("#mode")'); + assert.equal(await b.evaluate('document.querySelector("#theme-switch")?.getAttribute("role")'),'switch'); + await b.evaluate('document.querySelector("#mode").value="system";document.querySelector("#mode").dispatchEvent(new Event("change",{bubbles:true}))'); + assert.equal(await b.evaluate('document.querySelector("#theme-switch").getAttribute("aria-checked")'),'false'); + await b.evaluate('document.querySelector("#theme-switch").click()'); + assert.deepEqual(await b.evaluate('[document.documentElement.dataset.mode,document.querySelector("#mode").value,document.querySelector("#theme-switch").getAttribute("aria-checked")]'),['dark','dark','true']); + await b.call('Page.reload'); await wait('document.querySelector("#theme-switch")?.getAttribute("aria-checked") === "true"'); + assert.equal(await b.evaluate('document.documentElement.dataset.mode'),'dark'); + await b.evaluate('document.querySelector("#mode").value="dim";document.querySelector("#mode").dispatchEvent(new Event("change"))'); + assert.equal(await b.evaluate('document.querySelector("#theme-switch").getAttribute("aria-checked")'),'true'); + await b.evaluate('document.querySelector("#theme-switch").click()'); + assert.deepEqual(await b.evaluate('[document.documentElement.dataset.mode,document.querySelector("#mode").value]'),['light','light']); + await b.evaluate('document.querySelector("#mode").value="system";document.querySelector("#mode").dispatchEvent(new Event("change"))'); + assert.equal(await b.evaluate('document.querySelector("#theme-switch").getAttribute("aria-checked")'),'false'); + await b.call('Emulation.setEmulatedMedia',{features:[{name:'prefers-color-scheme',value:'dark'}]}); + await wait('document.querySelector("#theme-switch").getAttribute("aria-checked") === "true"'); + assert.equal(await b.evaluate('document.documentElement.hasAttribute("data-mode")'),false); + for (const width of [1440,390]) { + await b.viewport(width,900); + const v=await b.evaluate(`(()=>{const s=document.querySelector('#theme-switch'),a=document.querySelector('#avatar-button'),r=s.getBoundingClientRect(),ar=a.getBoundingClientRect();return {role:s.getAttribute('role'),name:s.getAttribute('aria-label'),width:r.width,height:r.height,left:r.right<=ar.left,top:Math.abs(r.top-ar.top),overflow:document.documentElement.scrollWidth>innerWidth}})()`); + assert.deepEqual([v.role,v.name,v.width>=44,v.height>=44,v.left,v.top<15,v.overflow],['switch','Dark mode',true,true,true,true,false],JSON.stringify(v)); + } +}); -- 2.54.0 From 700259aa38886d24c33f2d7b4a0ae3641136e1ed Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Fri, 6 Nov 2026 12:16:36 -0600 Subject: [PATCH 007/116] feat: allow agent launches in dev local owner mode --- docs/SESSIONS.md | 1 + docs/TOOLS.md | 2 +- packages/bus/tests/dev-local-owner.test.mjs | 41 +++++++++++++++++-- packages/cli/src/cli.mjs | 4 +- packages/webui/tests/dev-local-owner.test.mjs | 2 +- 5 files changed, 43 insertions(+), 7 deletions(-) diff --git a/docs/SESSIONS.md b/docs/SESSIONS.md index 979b074a1..8a725a83c 100644 --- a/docs/SESSIONS.md +++ b/docs/SESSIONS.md @@ -2106,3 +2106,4 @@ are never rewritten or removed; corrections are new entries. 2026-11-06 UTC | mvp3-lead-797 (Claude, #797 lane) | files-polish r2 on 86383a9d1 for Sol r1 F1/F2 | Per-key commit order fences live paints and caches the newest completed result; reviewer probes ported; r1 negative 11/2, w15-files 13/13, caller browser gate 93/0/0/0. Evidence: /mnt/storage/scratch/mosaic-lead/mvp3/files-polish-r2-evidence/. 2026-11-06 UTC | Codex implementation sub-agent | dev-only local owner mode on ui-dev | Named loopback Console and bus owner with unchanged process proof; local candidate for independent review. Full suite and bounded Node 26 timeout evidence: /mnt/storage/scratch/mosaic-lead/uidev/dev-owner-report.md. Queue refused linked worktree; no push, merge or deployment. 2026-11-06 UTC | Codex implementation sub-agent | dev local owner named data-root claim correction on ui-dev | Both entry points use the existing named-instance validator; missing, mismatched and hard-linked claims refuse before startup. Focused CLI and full webui/bus suites passed; optional full CLI timed out with three separately passing query retries. Evidence: /mnt/storage/scratch/mosaic-lead/uidev/dev-owner-report.md. Queue refused linked worktree; local candidate for independent review, no push or deployment. +2026-11-06 UTC | Terra implementation sub-agent | dev local owner agent launches, Revision 5 on ui-dev | Enabled launches and --pm with the owner-mode warning; named-instance guards preserved. Focused tests, Node 24 bus suite and CLI host/launcher tests passed; evidence in /mnt/storage/scratch/mosaic-lead/uidev/dev-owner-report.md. Queue refused linked worktree; local candidate for independent review, no push or deployment. diff --git a/docs/TOOLS.md b/docs/TOOLS.md index 91bdc14a3..bc93d9a16 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -318,7 +318,7 @@ scripts/bus-service.sh [--instance NAME] install [--copy ID [--copies DIR]] [--p scripts/bus-service.sh [--instance NAME] uninstall | status ``` -For local development on a named instance only, `mosaic bus start BUSINESS --dev-local-owner` admits the fixed local-dev Console owner and disables launches. It refuses the default instance and `--pm`. Start the matching Console with `--dev-local-owner`; the usual Console wrapper, process proof and nonce checks still apply. This mode has no sign-in and is for local development only. +For local development on a named instance only, `mosaic bus start BUSINESS --dev-local-owner` admits the fixed local-dev Console owner and refuses the default instance. Launches are enabled unless `--no-launch` is supplied; `--pm` can start the business's PM. Launched agents run as this OS user and can reach the loopback Console as owner; use this instance for UI testing only. Start the matching Console with `--dev-local-owner`; the usual Console wrapper, process proof and nonce checks still apply. This mode has no sign-in and is for local development only. The instance processing switch is separate from per-business launches off/on. `mosaic halt` durably stops managed processing across every business in the diff --git a/packages/bus/tests/dev-local-owner.test.mjs b/packages/bus/tests/dev-local-owner.test.mjs index 33fb707bf..cb25df788 100644 --- a/packages/bus/tests/dev-local-owner.test.mjs +++ b/packages/bus/tests/dev-local-owner.test.mjs @@ -1,7 +1,13 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { spawnSync } from 'node:child_process'; +import { spawn, spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import { once } from 'node:events'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { DEV_OWNER } from '../../cli/src/dev-local-owner.mjs'; +import { fixture, notifyConfig } from '../../cli/tests/helpers.mjs'; +import { initializeControl, transition } from '../../processing-control/src/state.mjs'; import { verifyPrincipal } from '../src/principal.mjs'; import { checkConsole } from '../../webui/src/sso-config.mjs'; @@ -26,9 +32,38 @@ test('dev issuer cannot be a configured SSO issuer',()=>{ const sso={sso:{publicOrigin:'https://console.example',providers:[{id:DEV_OWNER.provider,issuer:DEV_OWNER.iss,clientId:'fake',clientSecret:{slot:'fake'},algs:['RS256'],subjects:[{sub:DEV_OWNER.sub,name:'operator'}]}]}}; assert.throws(()=>checkConsole(sso),/issuer.*https URL/); }); -test('bus dev flag refuses default instance and --pm before config access',()=>{ +test('bus dev flag refuses the default instance with or without --pm before config access',()=>{ for(const args of [['bus','start','demo','--dev-local-owner'], ['bus','start','demo','--dev-local-owner','--pm']]) { const r=spawnSync(process.execPath,['packages/cli/src/cli.mjs',...args],{encoding:'utf8',env:{...process.env,MOSAIC_CONFIG:''}}); - assert.notEqual(r.status,0); assert.match(r.stderr,args.includes('--pm') ? /--dev-local-owner cannot be combined with --pm/ : /--dev-local-owner requires a named instance/); + assert.notEqual(r.status,0); assert.match(r.stderr,/--dev-local-owner requires a named instance/); } }); + +for (const pm of [false, true]) { + test(`bus dev owner enables launches ${pm ? 'with --pm and prints the warning' : 'without --pm'}`, { timeout: 30000 }, async t => { + const root=mkdtempSync(join(tmpdir(),'dev-owner-launch-')); + t.after(()=>rmSync(root,{recursive:true,force:true})); + const f=fixture(root), home=join(root,'home'), base=join(home,'.config'); + mkdirSync(base,{recursive:true}); renameSync(join(root,'config'),join(base,'mosaic-test')); + writeFileSync(join(f.dataRoot,'instance.json'),JSON.stringify({instanceVersion:1,name:'test'})); + notifyConfig(f.dataRoot,'acme',null); + // A halted instance exercises the real --pm path without launching a harness. + initializeControl(f.dataRoot); + transition(f.dataRoot,{business:'acme',human:'jason',halted:true}); + const env={...f.env,HOME:home,MOSAIC_CONFIG:join(base,'mosaic-test','config.json')}; + const child=spawn(process.execPath,['packages/cli/src/cli.mjs','bus','start','acme','--dev-local-owner',...(pm ? ['--pm'] : [])],{env,stdio:['ignore','pipe','pipe']}); + const exited=once(child,'exit'); let stdout='', stderr=''; + child.stdout.on('data',b=>stdout+=b); child.stderr.on('data',b=>stderr+=b); + t.after(async()=>{if(child.exitCode===null && child.signalCode===null){child.kill('SIGTERM'); await exited;}}); + const deadline=Date.now()+15000; + while(Date.now()setTimeout(r,50)); + assert.match(stdout,/DEV LOCAL OWNER MODE: console owner local-dev accepted \(named instance test\)\n/,stderr); + const warning='DEV LOCAL OWNER MODE: launched agents run as this OS user and can reach the loopback Console as owner; use this instance for UI testing only'; + if(pm) { + assert.ok(stdout.includes(`DEV LOCAL OWNER MODE: console owner local-dev accepted (named instance test)\n${warning}\n`),stdout); + assert.match(stdout,/processing halted: chief launch skipped/); + } else assert.ok(!stdout.includes(warning)); + assert.match(stdout,/bus host up: business acme, socket \S+, notifier off\n/); + assert.equal(child.exitCode,null,stderr); + }); +} diff --git a/packages/cli/src/cli.mjs b/packages/cli/src/cli.mjs index e9e0e3672..e786aa5e3 100644 --- a/packages/cli/src/cli.mjs +++ b/packages/cli/src/cli.mjs @@ -550,9 +550,8 @@ async function bus(rest, io, deps) { const parsed = parse(args, { flags: ["--pm", "--no-launch", "--dev-local-owner"] }); if (parsed.positional.length !== 1) throw usage("bus start takes one business"); // Row 163: --no-launch is the D2 rehearsal's host. No unit passes it. - const launches = !parsed.flags.has("--no-launch") && !parsed.flags.has("--dev-local-owner"); + const launches = !parsed.flags.has("--no-launch"); if (parsed.flags.has("--no-launch") && parsed.flags.has("--pm")) throw usage("bus start takes --pm or --no-launch, not both"); - if (parsed.flags.has("--dev-local-owner") && parsed.flags.has("--pm")) throw usage("--dev-local-owner cannot be combined with --pm"); const instance = parsed.flags.has("--dev-local-owner") ? devOwnerInstance(io.env) : null; const businessId = parsed.positional[0]; const system = instance ? loadSystem({ env: io.env, instance }) : (deps.system ?? loadSystem({ env: io.env })); @@ -574,6 +573,7 @@ async function bus(rest, io, deps) { const launcher = createLauncher({ host, system, env: io.env, tracker: Boolean(boot.trackers?.[businessId]), launches, ...(deps.launcher ?? {}) }); await launcher.listen(); if (instance) io.stdout.write(`DEV LOCAL OWNER MODE: console owner local-dev accepted (named instance ${instance})\n`); + if (instance && parsed.flags.has("--pm")) io.stdout.write('DEV LOCAL OWNER MODE: launched agents run as this OS user and can reach the loopback Console as owner; use this instance for UI testing only\n'); io.stdout.write(`bus host up: business ${businessId}, socket ${host.path}, notifier ${binding ?? "off"}${launches ? "" : ", launches disabled"}\n`); if (parsed.flags.has("--pm")) { try { diff --git a/packages/webui/tests/dev-local-owner.test.mjs b/packages/webui/tests/dev-local-owner.test.mjs index 1ac80c916..8fe66684f 100644 --- a/packages/webui/tests/dev-local-owner.test.mjs +++ b/packages/webui/tests/dev-local-owner.test.mjs @@ -109,7 +109,7 @@ test('dev owner resolves a decision through the real Console wrapper and bus', { broker.request(cap,{verb:'role.claim'}); const decision=broker.request(cap,{verb:'decision.raise',args:{action:'prd.approve',question:'Choose?',blocking:false,options:[{key:'yes',text:'Yes'},{key:'no',text:'No'}],recommendation:'yes',approvalChoice:'yes'}}); store.close(); - let bus=spawn(process.execPath,['packages/cli/src/cli.mjs','bus','start','acme','--dev-local-owner'],{env,stdio:['ignore','pipe','pipe']}); + let bus=spawn(process.execPath,['packages/cli/src/cli.mjs','bus','start','acme','--dev-local-owner','--no-launch'],{env,stdio:['ignore','pipe','pipe']}); let busOut=''; bus.stdout.on('data',c=>busOut+=c); bus.stderr.on('data',c=>busOut+=c); t.after(()=>bus.kill('SIGTERM')); const wait=async (fn) => { for(let i=0;i<300;i++){ const v=fn(); if(v)return v; await new Promise(r=>setTimeout(r,100)); } throw Error(`startup timeout: ${busOut}`); }; -- 2.54.0 From a06d792ff99535fd18b026eb665b175b4c4fd92f Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Fri, 6 Nov 2026 14:43:04 -0600 Subject: [PATCH 008/116] feat(webui): settings page redesign (ui slice 2) --- packages/webui/src/public/agents.js | 69 ++++---- packages/webui/src/public/app.js | 3 +- packages/webui/src/public/bus.js | 141 +++++++++------ packages/webui/src/public/display.js | 165 +++++++++++++----- packages/webui/src/public/index.html | 3 +- packages/webui/src/public/proxy.html | 66 ++++--- packages/webui/src/public/shell.css | 68 ++++++++ packages/webui/src/public/tokens.css | 56 ++++++ packages/webui/tests/agents-browser.test.mjs | 72 ++++---- .../tests/dashboard-shell-browser.test.mjs | 4 +- .../webui/tests/instances-browser.test.mjs | 32 ++-- packages/webui/tests/limits-browser.test.mjs | 17 +- packages/webui/tests/messages.test.mjs | 6 +- packages/webui/tests/proxy-browser.test.mjs | 11 +- packages/webui/tests/proxy-page.test.mjs | 6 +- packages/webui/tests/routes-browser.test.mjs | 4 +- packages/webui/tests/settings-form.test.mjs | 56 ++++-- .../tests/settings-redesign-browser.test.mjs | 106 +++++++++++ packages/webui/tests/tester-browser.test.mjs | 6 +- packages/webui/tests/usage-browser.test.mjs | 2 +- packages/webui/tests/views.test.mjs | 38 ++-- .../tests/w15-r1-regression-browser.test.mjs | 13 +- .../webui/tests/w15-shell-browser.test.mjs | 64 +++---- 23 files changed, 685 insertions(+), 323 deletions(-) create mode 100644 packages/webui/tests/settings-redesign-browser.test.mjs diff --git a/packages/webui/src/public/agents.js b/packages/webui/src/public/agents.js index 3a56bfda4..d3108c2fb 100644 --- a/packages/webui/src/public/agents.js +++ b/packages/webui/src/public/agents.js @@ -22,40 +22,27 @@ const redraw = () => { if (ctx && !ctx.out()) ctx.render(); }; const reread = () => { if (ctx && !ctx.out()) ctx.refresh(); }; + let editing = null; function section(v, c) { ctx = c; view = v; - const { txt, esc } = c, title = '

    Agents

    '; - if (!v) return `
    ${title}

    The agents could not be read, so there is nothing to act on. Read again to retry.

    `; - const open = usable(), off = !open || busy || pending ? ' disabled' : ''; - const button = (action, name, label, extra = '') => - ``; - const confirmPair = (action, name, label, ask) => confirming?.action === action && confirming?.name === name - ? `${txt(ask)} ${button(action, name, `Confirm ${label.toLowerCase()}`, ' data-agent-confirmed=""')} ` - : button(action, name, label); - const rows = Object.entries(v.instances).map(([name, e]) => { - const running = Array.isArray(e.running) ? e.running : []; - // D7 (S6): a run a fire's stop left alive holds no claim, so it isn't in running. - const alive = Array.isArray(e.alive) ? e.alive : []; - const acts = [button('launch', name, 'Launch'), - ``, - button('end', name, 'Terminate')]; - if (!c.isTester) { - acts.push(confirmPair('regenerate', name, 'Regenerate', `Regenerate ${name}? Its workspace is renamed under .retired and it starts fresh.`)); - acts.push(e.kept ? button('unkeep', name, 'Unkeep') : button('keep', name, 'Keep')); - // endProtected is the server's delete check for this reader (row 256): false on the human's - // page for a creative instance, true for the assistant and on the tester's. - if (!e.endProtected) acts.push(confirmPair('delete', name, 'Delete', `Delete ${name}? Its evidence and its workspace under .retired stay.`)); - } - return `${txt(name)}${txt(e.definition)}${e.launched ? 'yes' : 'no'}${e.kept ? 'yes' : 'no'}${running.length ? running.map(r => `${txt(r)}`).join(' ') : 'none'}${alive.map(r => ` still running after fire: ${txt(r)}`).join('')}${acts.join(' ')}`; + const { txt, esc } = c, title = '

    Agents

    '; + if (!v) return `
    ${title}

    The agents could not be read, so there is nothing to act on. Read again to retry.

    `; + const open=usable(), off=!open||busy||pending||c.instanceBusy?' disabled':'', defs=Object.keys(v.definitions||{}), accepted=defs.filter(d=>v.definitions[d]?.accepted); + const option=(name,selected,first)=>`${accepted.map(d=>``).join('')}`; + const button=(action,name,label)=>``; + const rows=Object.entries(v.instances).map(([name,e])=>{ + const running=Array.isArray(e.running)?e.running:[], alive=Array.isArray(e.alive)?e.alive:[]; + const menu=open?``:''; + const d=c.instanceDrafts.change?.instance===name?c.instanceDrafts.change:{}; + const editor=editing===name?`
    ${v.launch?``:''}
    Vars as JSON

    Harness, model and thinking are set in Routing.

    `:''; + return `${txt(name)}${txt(e.definition)}${e.launcher?'Launcher':e.launched?'Yes':'No'}${e.kept?'Yes':'No'}${running.length?running.map(r=>`${txt(r)}`).join(' '):'None'}${alive.map(r=>` still running after fire: ${txt(r)}`).join('')}${open?button('launch',name,'Launch'):''}${menu}${editor}`; }).join(''); - const noHire = Array.isArray(v.noHire) ? v.noHire : [], retired = Array.isArray(v.retired) ? v.retired : []; - const defs = Object.keys(v.definitions || {}); - const hiring = c.isTester ? '' : `

    Hiring per definition

      ${defs.map(d => `
    • ${txt(d)}: ${noHire.includes(d) ? `no hire ${button('hire', d, 'Allow hiring')}` : `hire allowed ${button('nohire', d, 'No hire')}`}
    • `).join('')}
    `; - const accepted = defs.filter(d => v.definitions[d]?.accepted); - const createForm = c.isTester ? '' : `
    Create an agent
    `; - const state = pending ? `

    Request ${txt(pending.request)} to ${txt(pending.action)} ${txt(pending.instance)}: ${txt(pending.state)}.

    ` : ''; - const note = open ? `

    Actions are checked and logged with your identity.

    ` : `

    ${txt(UNAVAILABLE)}

    `; - return `
    ${title}

    Each agent with its definition, launch membership, keep and running runs. A launch refuses no-route until the agent has a route in Routing.

    ${note}
    ${rows}
    InstanceDefinitionLaunchedKeptRunningActions
    ${hiring}${createForm}${retired.length ? `

    Retired names, never reused: ${retired.map(txt).join(', ')}.

    ` : ''}${state}

    ${txt(receipt)}

    `; + const d=c.instanceDrafts.add||{}, bound=defs.filter(n=>Array.isArray(v.definitions[n].services)&&v.definitions[n].services.length).map(n=>`${txt(n)} (${v.definitions[n].services.map(txt).join(', ')})`); + const add=!c.isTester&&open?`

    Add an agent

    ${v.launch?``:''}
    Vars as JSON

    Harness, model and thinking are set in Routing.

    ${bound.length?`

    Definitions that declare credentials are a hand edit: ${bound.join(', ')}.

    `:''}
    `:''; + const noHire=Array.isArray(v.noHire)?v.noHire:[], retired=Array.isArray(v.retired)?v.retired:[]; + const hiring=!c.isTester?`

    Hiring

    Turn hiring off to stop new agents of a definition.

    ${defs.map(n=>`
    ${open?``:`${noHire.includes(n)?'Off':'On'}`}${txt(n)}
    `).join('')}
    ${retired.length?`

    Retired names, never reused: ${retired.map(txt).join(', ')}.

    `:''}
    `:''; + const state=pending?`

    Request ${txt(pending.request)} to ${txt(pending.action)} ${txt(pending.instance)}: ${txt(pending.state)}.

    `:''; + return `
    ${title}${state}
    ${rows}
    AgentDefinitionLaunchKeptRunningActions

    ${txt(receipt)}

    ${txt(c.instanceReceipt)}

    ${add}${hiring}

    `; } // One POST. `null` means the page signed out; otherwise the status and the parsed answer. @@ -136,15 +123,21 @@ else { receipt = answer.ok ? UNKNOWN : `${refused(answer.result)} Draft kept.`; redraw(); } } + let dialogAction=null, dialogName=null, dialogReturn=null; + function closeMenu(more, focus=false){const menu=more?.nextElementSibling;if(!menu)return;menu.hidden=true;more.setAttribute('aria-expanded','false');if(focus)more.focus();} + function openMenu(more){document.querySelectorAll('.agent-more[aria-expanded="true"]').forEach(b=>closeMenu(b));more.nextElementSibling.hidden=false;more.setAttribute('aria-expanded','true');more.nextElementSibling.querySelector('button')?.focus();} document.addEventListener('click', e => { - const t = e.target; - if (!t?.closest?.('#agents-section')) return; - if (t.dataset.agentCancel !== undefined) { confirming = null; redraw(); return; } - const action = t.dataset.agentAction, name = t.dataset.agentName; - if (!action || name === undefined) return; - if ((action === 'regenerate' || action === 'delete') && t.dataset.agentConfirmed === undefined) { confirming = { action, name }; redraw(); return; } - act(action, name); + const t=e.target, more=t.closest?.('.agent-more'); + if(more){if(more.getAttribute('aria-expanded')==='true')closeMenu(more);else openMenu(more);return;} + if(t.id==='agent-dialog-cancel'){document.querySelector('#agent-dialog').close();dialogReturn?.focus();return;} + if(t.id==='agent-dialog-confirm'){const dialog=document.querySelector('#agent-dialog');if(dialogAction==='end')reasons[dialogName]=document.querySelector('#agent-dialog-reason').value;dialog.close();act(dialogAction,dialogName);return;} + if(!t.closest?.('#agents-section'))return; + if(t.dataset.agentEdit!==undefined){editing=t.dataset.agentEdit;redraw();return;} + if(t.dataset.agentDialog){dialogAction=t.dataset.agentDialog;dialogName=t.dataset.agentName;dialogReturn=t.closest('.agent-menu').previousElementSibling;closeMenu(dialogReturn);const dialog=document.querySelector('#agent-dialog'),label={end:'Terminate',regenerate:'Regenerate',delete:'Delete'}[dialogAction];document.querySelector('#agent-dialog-title').textContent=`${label} ${dialogName}?`;document.querySelector('#agent-dialog-copy').textContent=dialogAction==='regenerate'?`Its workspace is renamed under .retired and it starts fresh.`:dialogAction==='delete'?`Its evidence and its workspace under .retired stay.`:'';document.querySelector('#agent-reason-label').hidden=dialogAction!=='end';document.querySelector('#agent-dialog-reason').value='';document.querySelector('#agent-dialog-confirm').textContent=label;dialog.showModal();(dialogAction==='end'?document.querySelector('#agent-dialog-reason'):document.querySelector('#agent-dialog-cancel')).focus();return;} + const action=t.dataset.agentAction,name=t.dataset.agentName;if(action&&name!==undefined){const menu=t.closest('.agent-menu');if(menu)closeMenu(menu.previousElementSibling);act(action,name);} }); + document.addEventListener('keydown',e=>{const menu=e.target.closest?.('.agent-menu'),more=e.target.closest?.('.agent-more');if(more && ['ArrowDown','Enter',' '].includes(e.key)){e.preventDefault();openMenu(more);return;}if(menu){const trigger=menu.previousElementSibling,items=[...menu.querySelectorAll('button')];if(e.key==='Escape'){e.preventDefault();closeMenu(trigger,true);}else if(e.key==='Tab')closeMenu(trigger);else if(e.key==='ArrowDown'||e.key==='ArrowUp'){e.preventDefault();items[(items.indexOf(e.target)+(e.key==='ArrowDown'?1:-1)+items.length)%items.length]?.focus();}}}); + document.addEventListener('cancel',e=>{if(e.target.id==='agent-dialog'){e.preventDefault();e.target.close();dialogReturn?.focus();}},true); document.addEventListener('input', e => { const t = e.target; if (t?.dataset?.agentReason !== undefined) reasons[t.dataset.agentReason] = t.value; diff --git a/packages/webui/src/public/app.js b/packages/webui/src/public/app.js index b736b4a66..30682d1dd 100644 --- a/packages/webui/src/public/app.js +++ b/packages/webui/src/public/app.js @@ -63,7 +63,8 @@ if (mode === 'system') delete document.documentElement.dataset.mode; else document.documentElement.dataset.mode = mode; $('palette').value = palette; $('mode').value = mode; syncThemeSwitch(); - try { localStorage.setItem('mosaic-console-appearance', JSON.stringify({ palette, mode })); } catch {} + let stored = true; try { localStorage.setItem('mosaic-console-appearance', JSON.stringify({ palette, mode })); } catch { stored = false; } + document.dispatchEvent(new CustomEvent('mosaic-theme-change', {detail: {palette, mode, stored}})); } $('palette').innerHTML = Brand.palettes.map(p => ``).join(''); try { const saved = JSON.parse(localStorage.getItem('mosaic-console-appearance')); if (saved) { palette = saved.palette; mode = saved.mode; } } catch {} diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index 836d369d1..ff821c66f 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -624,7 +624,7 @@ // Row 54 (#1543), read-only. A row moves only with `scripts/mosaic queue move` in a terminal, // so its page shows that command and has no button for it. The business file is edited where // it lives. On Settings only appearance changes, and only in this browser. - const readLine = () => `Read ${when(readAt)}.`; + const readLine = () => readAt ? `Read ${when(readAt)}.` : 'Reading…'; const none = 'none'; const QUEUE_STATES = ['queued', 'briefed', 'in-progress', 'in-review', 'waiting-on-jason', 'done', 'blocked', 'parked']; const QSTATE = { done: 'ok', blocked: 'danger', 'waiting-on-jason': 'attn', 'in-review': 'attn', 'in-progress': 'attn' }; @@ -697,14 +697,34 @@

    Credentials ${creds.length}

    Metadata only: service, account, role and date. Console never reads a token, a token file or a variable.

    ${creds.length ? `
    ${['Service', 'Account', 'Role', 'Date', 'State'].map(h => ``).join('')}${credRows}
    ${h}
    ` : empty('No credentials are named.', 'A credential shows here when a role instance or tracker sync names one.')}
    `; } - // Appearance mirrors the command bar's two selects, so app.js keeps the one copy of the rule. function appearance() { - const p = $('palette'), m = $('mode'); - const pick = (id, label, src) => ``; - return `

    Appearance

    Stored in this browser only. The same control is in the command bar.

    ${pick('palette', 'Palette', p)}${pick('mode', 'Appearance', m)}
    `; + const palette = $('palette').value, mode = $('mode').value; + const segment = (name, options, selected) => `
    ${options.map(([value,label])=>``).join('')}
    `; + return `

    Theme

    System follows your device. The switch in the top bar flips between light and dark.

    ${segment('Theme', [['system','System'],['light','Light'],['dim','Dim'],['dark','Dark']],mode)}

    +

    Palette

    Colors for every page. Harbor is the default.

    ${Brand.palettes.map(p=>``).join('')}

    +

    Sidebar density

    How much space each sidebar row takes.

    ${segment('Density',[['comfortable','Comfortable'],['compact','Compact']],window.MosaicDisplay.get().density)}

    `; } + let browserStatusTimer; + function browserStatus(name, ok) { + const el = document.querySelector(`[data-status="${name}"]`); if (!el) return; + el.textContent = ok ? '✓ Saved in this browser.' : 'Could not save in this browser. The choice applies until you reload.'; + el.classList.toggle('warning', !ok); clearTimeout(browserStatusTimer); + if (ok) browserStatusTimer = setTimeout(()=>{if(el.isConnected)el.textContent='';},4000); + } + document.addEventListener('change', e => { + if (!e.target.closest?.('.settings-appearance')) return; + const {name,value}=e.target; + if (name==='density') browserStatus(name,window.MosaicDisplay.setDensity(value)); + if (name==='theme'||name==='palette') { const src=$(name==='theme'?'mode':'palette'); src.value=value; src.dispatchEvent(new Event('change',{bubbles:true})); } + }); + document.addEventListener('mosaic-theme-change', e => { + for (const [name,value] of [['theme',e.detail.mode],['palette',e.detail.palette]]) { + const input=[...document.querySelectorAll(`.settings-appearance input[name="${name}"]`)].find(i=>i.value===value); if(input)input.checked=true; + } + if (document.activeElement?.name==='theme'||document.activeElement?.name==='palette') browserStatus(document.activeElement.name,e.detail.stored); + }); // REQ-WEB-1: drafts survive polling/refusals; only an explicit submit writes. - let settingsSnapshot=null, settingsInputs=null, settingsSaving=false, settingsReceipt=''; + let settingsSnapshot=null, settingsInputs=null, settingsSaving=false, settingsReceipt='', settingInvalidKey=null; const inputKey=parts=>JSON.stringify(parts); // Row 167 (#1664): one snapshot for the launch form, the assistant forms and the token limit // reset. A read replaces it only while no form has a draft; every save and reset sets it from @@ -716,26 +736,26 @@ const v=takeSnapshot(value), modelTable=v.models||{}, limits=v.limits||{}, usage=v.usage||{}; const val=(parts,fallback)=>settingsInputs&&Object.hasOwn(settingsInputs,inputKey(parts))?settingsInputs[inputKey(parts)]:fallback; const disabled=!canSend||out()||settingsSaving?' disabled':''; - const field=(parts,label,count,current)=>``; + const field=(parts,label,count,current)=>`${txt(label)}${txt(current??0)} running`; const providers=new Set([...Object.keys(limits.providers||{}),...Object.values(modelTable).map(x=>x.provider)]); const pairs=new Map();for(const [provider,models]of Object.entries(limits.models||{}))for(const model of Object.keys(models))pairs.set(inputKey([provider,model]),[provider,model]);for(const m of Object.values(modelTable))pairs.set(inputKey([m.provider,m.model]),[m.provider,m.model]); const providerRows=[...providers].map(p=>field(['providers',p],p,limits.providers?.[p],usage.providers?.[p])).join(''); const modelRows=[...pairs.values()].map(([p,m])=>field(['models',p,m],`${p} / ${m}`,limits.models?.[p]?.[m],usage.models?.[p]?.[m])).join(''); - const table=Object.entries(modelTable).map(([key,m])=>`
    ${txt(key)}
    `).join(''); + const table=Object.entries(modelTable).map(([key,m])=>`${txt(key)}`).join(''); // Row 65 (mos-0840): each instance's model moved to the routing table below. - return `

    Agent limits

    Leave a limit blank for no limit. Zero stops new launches. Running sessions keep running when limits or models change.

    All sessions${field(['total'],'Total',limits.total,usage.total)}
    By provider
    ${providerRows}
    By provider and model
    ${modelRows}
    Model table${table}

    ${canSend?'Changes are checked and logged with your identity.':'Saving requires signed-in send mode.'}

    ${txt(settingsReceipt)}

    `; + return `

    Launch limits

    ${field(['total'],'All sessions',limits.total,usage.total)}${providerRows}${modelRows}
    ScopeLimitRunning now
    All sessions
    Provider
    Model

    Model names

    Which provider model each short name launches.

    ${table}
    NameProviderModel

    ${canSend?'Changes are checked and logged with your identity.':'Saving requires signed-in send mode.'}

    ${txt(settingsReceipt)}

    `; } function settingDraft(form){const values={};for(const el of form.querySelectorAll('[data-setting]'))values[el.dataset.setting]=el.value;return values;} - function settingPayload(){const v=settingsSnapshot, limits={providers:Object.create(null),models:Object.create(null)},models=structuredClone(v.models);for(const [encoded,text]of Object.entries(settingsInputs)){const [kind,p,m]=JSON.parse(encoded);if(kind==='table'){models[p][m]=text;continue;}if(text==='')continue;if(!/^\d+$/.test(text)||!Number.isSafeInteger(Number(text)))throw Error('Limits need whole numbers of zero or more.');const n=Number(text);if(kind==='total')limits.total=n;else if(kind==='providers')limits.providers[p]=n;else {limits.models[p]??=Object.create(null);limits.models[p][m]=n;}} + function settingPayload(){const v=settingsSnapshot, limits={providers:Object.create(null),models:Object.create(null)},models=structuredClone(v.models);for(const [encoded,text]of Object.entries(settingsInputs)){const [kind,p,m]=JSON.parse(encoded);if(kind==='table'){models[p][m]=text;continue;}if(text==='')continue;if(!/^\d+$/.test(text)||!Number.isSafeInteger(Number(text))){settingInvalidKey=encoded;throw Error('Limits need whole numbers of zero or more.');}const n=Number(text);if(kind==='total')limits.total=n;else if(kind==='providers')limits.providers[p]=n;else {limits.models[p]??=Object.create(null);limits.models[p][m]=n;}} // Row 125 (#1619): the form doesn't edit token limits; a save keeps them as read. if(v.limits?.tokens)limits.tokens=structuredClone(v.limits.tokens); return {revision:v.revision,limits,models}; } - document.addEventListener('input',e=>{const form=e.target.closest?.('#launch-settings-form');if(form)settingsInputs=settingDraft(form);}); - document.addEventListener('change',e=>{const form=e.target.closest?.('#launch-settings-form');if(form)settingsInputs=settingDraft(form);}); + document.addEventListener('input',e=>{const form=e.target.closest?.('#launch-settings-form');if(form){e.target.removeAttribute('aria-invalid');settingInvalidKey=null;settingsInputs=settingDraft(form);markSettingsDraft('limits',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=$('launch-settings-reload');if(discard)discard.hidden=false;}}); + document.addEventListener('change',e=>{const form=e.target.closest?.('#launch-settings-form');if(form){settingsInputs=settingDraft(form);markSettingsDraft('limits',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=$('launch-settings-reload');if(discard)discard.hidden=false;}}); document.addEventListener('click',e=>{if(e.target.id!=='launch-settings-reload')return;settingsInputs=null;settingsSnapshot=null;settingsReceipt='';last.delete('api:settings');render(true);}); document.addEventListener('submit',async e=>{ - if(e.target.id!=='launch-settings-form')return;e.preventDefault();if(!canSend||out()||settingsSaving)return;settingsInputs=settingDraft(e.target);let payload;try{payload=settingPayload();}catch(err){settingsReceipt=err.message;render(false);return;}settingsSaving=true;settingsReceipt='';render(false); + if(e.target.id!=='launch-settings-form')return;e.preventDefault();if(!canSend||out()||settingsSaving)return;settingsInputs=settingDraft(e.target);let payload;try{payload=settingPayload();}catch(err){settingsReceipt=err.message+' Draft kept.';render(false);return;}settingsSaving=true;settingsReceipt='';render(false); try{const response=await fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(response.type==='opaqueredirect'){settingsReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();if(response.ok&&/^[a-f0-9]{64}$/.test(result?.revision??'')){settingsInputs=null;settingsSnapshot=result;const prior=last.get('api:settings');if(prior)last.set('api:settings',{...prior,launch:result});settingsReceipt='Launch settings saved.';}else settingsReceipt=result?.sent==='unknown'?'Outcome unknown. Read current settings before trying again. Draft kept.':`${result?.message||'Settings refused.'} Draft kept.`;}} catch{settingsReceipt='Outcome unknown. Read current settings before trying again. Draft kept.';}finally{settingsSaving=false;if(!out())render(false);} }); @@ -746,7 +766,7 @@ function tokenLimits(rows, refused) { const title = '

    Token limits

    '; if (refused) return `
    ${title}

    Token limits unavailable. No report was read.

    `; - if (!rows.length) return `
    ${title}

    No token limits are set.

    `; + if (!rows.length) return `
    ${title}

    No token limits are set. This page can reset a limit but cannot set one.

    `; const can = canSend && !out() && !settingsSaving && /^[a-f0-9]{64}$/.test(settingsSnapshot?.revision ?? ''); const state = t => t.status === 'counted' ? `${txt(t.count)} (input ${txt(t.kinds?.input)}, output ${txt(t.kinds?.output)}, cache write ${txt(t.kinds?.cacheWrite)}, cache read ${txt(t.kinds?.cacheRead)}); unknown turns ${txt(t.unknownTurns)}` @@ -778,7 +798,7 @@ const lost = Number.isSafeInteger(value.proxy?.droppedBatches) ? value.proxy.droppedBatches : 0; const dropped = lost > 0 ? `

    ${txt(lost)} ${lost === 1 ? 'batch' : 'batches'} of proxy usage events could not be saved since the bus started. The events in a dropped batch are lost and are not in these totals.

    ` : ''; const proxy = value.proxy ? `

    Proxy-reported usage

    Optional proxy telemetry never enforces a quota. Status: ${txt(value.proxy.state)}. These counts cover drained events and may be incomplete.

    ${dropped}
    ${(value.proxy.byAccount || []).map(row => `${['input','output','cacheWrite','cacheRead','requests','failures'].map(k => ``).join('')}`).join('')}
    Proxy account IDInputOutputCache writeCache readRequestsFailures
    ${txt(row.accountId)}${txt(row[k])}
    ` : ''; - return `

    Token usage

    Best reading of session-editable transcripts, not proof. Unknown turns may have used more tokens. Account is unassigned until account tracking is configured.

    ${rows.join('')}
    SubjectInputOutputCache writeCache readUnknown turns
    ${orphans}${proxy}
    `; + return `

    Token usage

    Best reading of session-editable transcripts, not proof. Unknown turns may have used more tokens. Account is unassigned until account tracking is configured.

    ${rows.length===1&&['input','output','cacheWrite','cacheRead','unknownTurns'].every(k=>value.total[k]===0)?'

    No token use counted yet.

    ':`
    ${rows.join('')}
    SubjectInputOutputCache writeCache readUnknown turns
    `}${orphans}${proxy}
    `; } // Row 155 (#1649, Q169): each assistant instance's settings, its seat name and a stop. A save // sends only the fields that changed, with the read's revision. Drafts survive polling and @@ -787,15 +807,15 @@ const asShown=(entry,field)=>field==='definition'?entry.definition??'':entry[field]==null?'':JSON.stringify(entry[field],null,2); function assistantSection(value,names){ if(!value||value.refused)return ''; - const v=takeSnapshot(value);if(!v.assistants||!Object.keys(v.assistants).length)return ''; + const v=takeSnapshot(value);if(!v.assistants||!Object.keys(v.assistants).length)return '

    This business has no assistant instance.

    '; const disabled=!canSend||out()||assistantBusy?' disabled':''; const named=names?Object.fromEntries(names.map(r=>[r.instance,r.name])):null; const forms=Object.entries(v.assistants).map(([instance,entry])=>{ const d=assistantDrafts[instance]||{}, val=f=>Object.hasOwn(d,f)?d[f]:asShown(entry,f), k=esc(instance); const name=Object.hasOwn(nameDrafts,instance)?nameDrafts[instance]:named?.[instance]??''; - return `
    ${txt(instance)}
    ${named?'':' The current name could not be read.'}

    ${txt(assistantReceipts[instance]||'')}

    `; + return `

    Seat name

    The name people see for this seat.

    ${named?'':' The current name could not be read.'}

    Settings

    Harness, model and thinking are set in Routing.

    Leave empty to remove the tracker.

    ${txt(assistantReceipts[instance]||'')}

    Runs

    Stop ends the runs of your threads. The assistant starts again when you next write to it.

    `; }).join(''); - return `

    Assistant

    The definition stays an assistant one. Holder and credentials stay hand edits. Stop ends the runs of your threads; the assistant starts again when you next write to it.

    ${forms}

    ${canSend?'Changes are checked and logged with your identity.':'Changes require signed-in send mode.'}

    `; + return `
    ${forms}
    `; } function assistantPayload(instance,form){ const entry=settingsSnapshot.assistants[instance], patch={}; @@ -818,7 +838,7 @@ catch{assistantReceipts[instance]=unknownAssistant;}finally{assistantBusy=false;if(!out())render(false);} } const assistantForm=el=>el?.closest?.('.assistant-form'); - for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=assistantForm(e.target);if(!form)return;const instance=form.dataset.instance,field=e.target.dataset.assistantField;if(field==='name')nameDrafts[instance]=e.target.value;else if(field)assistantDrafts[instance]={...Object.fromEntries(['definition','vars','tracker'].map(f=>[f,form.querySelector(`[data-assistant-field="${f}"]`).value]))};}); + for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=assistantForm(e.target);if(!form)return;const instance=form.dataset.instance,field=e.target.dataset.assistantField;if(field==='name')nameDrafts[instance]=e.target.value;else if(field)assistantDrafts[instance]={...Object.fromEntries(['definition','vars','tracker'].map(f=>[f,form.querySelector(`[data-assistant-field="${f}"]`).value]))};if(field){markSettingsDraft('assistant',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=form.querySelector('[data-assistant-discard]');if(discard)discard.hidden=false;}}); document.addEventListener('submit',async e=>{ const form=assistantForm(e.target);if(!form||e.target!==form)return;e.preventDefault();if(!canSend||out()||assistantBusy)return;const instance=form.dataset.instance;let payload; try{payload=assistantPayload(instance,form);}catch(err){assistantReceipts[instance]=err.message;render(false);return;} @@ -826,6 +846,7 @@ }); document.addEventListener('click',async e=>{ const form=assistantForm(e.target);if(!form||!canSend||out()||assistantBusy)return;const instance=form.dataset.instance; + if(e.target.dataset.assistantDiscard!==undefined){delete assistantDrafts[instance];delete nameDrafts[instance];delete assistantReceipts[instance];settingsSnapshot=null;last.delete('api:settings');render(true);return;} if(e.target.dataset.assistantName!==undefined){const name=form.querySelector('[data-assistant-field="name"]').value.trim(); await assistantPost('/api/name',{instance,name},instance,result=>{if(typeof result?.name!=='string')return unknownAssistant;delete nameDrafts[instance];const prior=last.get('names');if(prior)last.set('names',{...prior,rows:[...prior.rows.filter(r=>r.instance!==result.instance),{instance:result.instance,name:result.name,at:result.at}]});return `Seat name set to ${result.name}.`;});} else if(e.target.dataset.assistantStop!==undefined)await assistantPost('/api/assistant-stop',{instance},instance,result=>Array.isArray(result?.stopped)?`Stopped ${plural(result.stopped.length,'run')}.`:unknownAssistant); @@ -869,8 +890,8 @@ const unknownInstance='Outcome unknown. Read the role instances again before trying. Draft kept.'; // The answer replaces the view the next render draws, so it must have the read's whole shape. const instanceAnswer=r=>/^[a-f0-9]{64}$/.test(r?.revision??'')&&typeof r.restart==='boolean'&&[r.instances,r.definitions].every(o=>o&&typeof o==='object'&&!Array.isArray(o)); - for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=e.target?.closest?.('.instance-form');if(form)instanceDrafts[form.dataset.op]=instanceFields(form);}); - document.addEventListener('click',e=>{if(e.target.id!=='instances-reload')return;instanceDrafts={add:null,change:null};instanceView=null;instanceReceipt='';last.delete('instances');render(true);}); + for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=e.target?.closest?.('.instance-form');if(form){instanceDrafts[form.dataset.op]=instanceFields(form);markSettingsDraft('agents',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=form.querySelector('[data-instance-discard]');if(discard)discard.hidden=false;}}); + document.addEventListener('click',e=>{if(e.target.id!=='instances-reload' && e.target.dataset?.instanceDiscard===undefined)return;instanceDrafts={add:null,change:null};instanceView=null;instanceReceipt='';last.delete('instances');render(true);}); document.addEventListener('submit',async e=>{ const form=e.target?.closest?.('.instance-form');if(!form||e.target!==form)return;e.preventDefault();if(!(canSend || isTester)||out()||instanceBusy||!instanceView)return; const op=form.dataset.op;instanceDrafts[op]=instanceFields(form);let payload; @@ -891,7 +912,7 @@ const ROUTE_CELLS=[['harness','Harness'],['model','Model'],['thinking','Thinking'],['fallback.harness','Fallback harness'],['fallback.model','Fallback model'],['fallback.thinking','Fallback thinking']]; const routeCells=r=>({harness:r.harness??'',model:r.model??'',thinking:r.thinking??'','fallback.harness':r.fallback?.harness??'','fallback.model':r.fallback?.model??'','fallback.thinking':r.fallback?.thinking??''}); const sameCells=(a,b)=>ROUTE_CELLS.every(([k])=>a[k]===b[k]); - function routesSection(view){ + function routesSection(view,instanceInfo){ const title='

    Routing

    '; if(!view)return `
    ${title}

    The routes could not be read, so there is nothing to change. Read again to retry; they come from the bus host with your identity.

    `; if(!routesDraft)routesView=view; @@ -904,9 +925,9 @@ const harness=(key)=>select(name,key,v.harnesses,c[key],'not switched on'); const model=(key)=>select(name,key,v.models,c[key],'not in the model table'); const thinking=(key,h)=>select(name,key,levelsOf(c[h]),c[key],c[h]?`not applied by ${c[h]}`:'no harness'); - return `${txt(name)}${harness('harness')}${model('model')}${thinking('thinking','harness')}${harness('fallback.harness')}${model('fallback.model')}${thinking('fallback.thinking','fallback.harness')}`;}).join(''); + return `${txt(name)}${instanceInfo?.instances?.[name]?.definition?`${txt(instanceInfo.instances[name].definition)}`:''}${harness('harness')}${model('model')}${thinking('thinking','harness')}${harness('fallback.harness')}${model('fallback.model')}${thinking('fallback.thinking','fallback.harness')}`;}).join(''); const off=v.harnesses.length?'':'

    No harness is switched on in the business file\'s plugins.harness, so every launch refuses harness-off and a save that changes a harness refuses too. mosaic plugins set switches one on.

    '; - return `
    ${title}

    Each instance's harness, model and thinking, and the fallback a launch takes when the primary harness fails its preflight. A fallback sets all three or none. Running sessions keep their route; the next launch reads the change.

    ${off}
    ${ROUTE_CELLS.map(([,l])=>``).join('')}${rows}
    Instance${l}

    ${canSend || isTester?'Changes are checked and logged with your identity.':'Saving requires signed-in send mode.'}

    ${txt(routesReceipt)}

    `; + return `
    ${title}${off}
    ${ROUTE_CELLS.map(([,l])=>``).join('')}${rows}
    AgentPrimaryFallback
    ${l.replace('Fallback ','')}

    ${canSend || isTester?'Changes are checked and logged with your identity.':'Saving requires signed-in send mode.'}

    ${txt(routesReceipt)}

    `; } function routesFields(form){const draft=Object.fromEntries(Object.keys(routesView.instances).map(name=>[name,routeCells(routesView.instances[name])]));for(const el of form.querySelectorAll('[data-route]')){const [name,key]=JSON.parse(el.dataset.route);if(draft[name])draft[name][key]=el.value;}return draft;} // The changed rows only. A fallback with all three cells empty is cleared; one with some set goes @@ -921,9 +942,10 @@ } const unknownRoutes='Outcome unknown. Read the routes again before trying. Draft kept.'; const routesAnswer=r=>/^[a-f0-9]{64}$/.test(r?.revision??'')&&Array.isArray(r.harnesses)&&Array.isArray(r.models)&&[r.levels,r.instances].every(o=>o&&typeof o==='object'&&!Array.isArray(o)); - for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=e.target?.closest?.('#routes-form');if(!form||!routesView)return;routesDraft=routesFields(form); + for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=e.target?.closest?.('#routes-form');if(!form||!routesView)return;routesDraft=routesFields(form);markSettingsDraft('routing',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=$('routes-reload');if(discard)discard.hidden=false; // A harness change redraws the row so its thinking cell offers that harness's levels. if(kind==='change'&&/harness"\]$/.test(e.target.dataset?.route??''))render(false);}); + document.addEventListener('click',e=>{if(e.target.matches?.('.fallback-toggle'))e.target.closest('tr')?.classList.add('fallback-open');}); document.addEventListener('click',e=>{if(e.target.id!=='routes-reload')return;routesDraft=null;routesView=null;routesReceipt='';last.delete('routes');render(true);}); document.addEventListener('submit',async e=>{ if(e.target.id!=='routes-form')return;e.preventDefault();if(!(canSend || isTester)||out()||routesBusy||!routesView)return; @@ -936,7 +958,7 @@ }); // Row 194 (#1692, D7): the Agents section lives in agents.js (window.MosaicAgents) and draws from // the same instances read. A refresh drops that read so the next render asks the bus again. - const agentsSection=view=>window.MosaicAgents?window.MosaicAgents.section(view,{txt,esc,canSend,isTester,out,signOut,render:()=>render(false),refresh:()=>{last.delete('instances');render(false);}}):''; + const agentsSection=view=>{ if(view&&!instanceDrafts.add&&!instanceDrafts.change)instanceView=view; return window.MosaicAgents?window.MosaicAgents.section(view,{txt,esc,canSend,isTester,out,signOut,instanceDrafts,instanceReceipt,instanceBusy,render:()=>render(false),refresh:()=>{last.delete('instances');render(false);}}):''; }; // Tester management is deliberately separate from the human's assistant/settings forms. function testerNames(names, instances) { if (!instances || !names) return ''; @@ -959,26 +981,32 @@ return `Seat name set to ${result.name}.`; }); }); - async function settingsView(get) { - const s = await get.api('settings'), n = s.notifier || {}; - let usage, names = null; - try { [usage] = await get('usage'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } - try { names = await get('names'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; /* the section says the name could not be read */ } - let instances = null; - try { [instances] = await get('instances'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } - let routes = null; - try { [routes] = await get('routes'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } - let limitRows = [], limitsRefused = false; - try { limitRows = await get('limits'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; limitsRefused = true; } - if (isTester) return `${head('Settings', `${readLine()} Tester management.`)}${routesSection(routes)}${instancesSection(instances)}${agentsSection(instances)}${testerNames(names, instances)}`; - const notify = typeof n.binding === 'string' - ? `
    Binding
    ${txt(n.binding)}

    The binding name only. Its channels, server and user ids stay in the binding file.

    ` - : empty('No notifier binding to show.', `${n.refused ? `${txt(n.refused)}: ` : ''}${txt(n.message || 'the notifier settings could not be read')}`); - return `${head('Settings', `${readLine()} Agent limits and appearance.`)}${appearance()}${launchForm(s.launch)}${routesSection(routes)}${assistantSection(s.launch, names)}${instancesSection(instances)}${agentsSection(instances)}${tokenLimits(limitRows, limitsRefused)}${tokenUsage(usage)} -

    Sidebar display

    Choose how this browser shows the sidebar.

    Sidebar display

    Model proxy

    Manage this instance’s model accounts, priorities and client key IDs.

    Open model proxy settings
    -

    Notifications

    ${notify}
    -

    About

    Address
    ${txt(s.address) || 'unknown'}
    Release
    ${s.release ? `${txt(s.release)}` : 'unknown: no RELEASE file was read'}
    Business
    ${txt(s.business) || none}
    Board
    ${txt(s.board) || 'unknown'}
    `; + const settingsPages = [['appearance','Appearance'],['limits','Launch limits'],['routing','Routing'],['agents','Agents'],['assistant','Assistant'],['tokens','Token use'],['model-proxy','Model proxy'],['about','About']]; + function markSettingsDraft(page,dirty){const link=document.querySelector(`#settings-nav a[href="#/settings/${page}"]`);if(link && dirty && !link.querySelector('.settings-dot'))link.insertAdjacentHTML('beforeend','unsaved changes');} + function settingsShell(page, body, helper='') { + const pages=isTester ? [['appearance','Appearance'],['routing','Routing'],['agents','Agents'],['names','Seat names']] : settingsPages; + const label=pages.find(([id])=>id===page)?.[1] || 'Appearance'; + const links=pages.map(([id,name],i)=>`${i===0?'
    Your browser
    ':i===1?'
    This instance
    ':''}${name}${(id==='routing'&&routesDraft)||(id==='limits'&&settingsInputs)||(id==='assistant'&&(Object.keys(assistantDrafts).length||Object.keys(nameDrafts).length))||(id==='agents'&&(instanceDrafts.add||instanceDrafts.change))?'unsaved changes':''}`).join(''); + return `${head('Settings','Your browser and this instance.')}

    ${label}

    ${helper}

    ${page!=='appearance'&&!canSend&&!isTester?'

    Read only. Saving requires signed-in send mode.

    ':''}${body}
    `; } + async function settingsView(get, page='appearance') { + if (page==='appearance') return settingsShell(page,appearance(),'These choices apply in this browser only.'); + if (page==='model-proxy') { await configRead; return settingsShell(page,window.MosaicProxy.markup,'Accounts used by this instance, their priority, and the client keys assigned to agents.'); } + const s = await get.api('settings'), n = s.notifier || {}; + let usage, names = null, instances = null, routes = null, limitRows = [], limitsRefused = false; + if (page==='tokens') { try { [usage] = await get('usage'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } try { limitRows = await get('limits'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; limitsRefused = true; } } + if (page==='assistant'||page==='names') { try { names = await get('names'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } } + if (page==='agents'||page==='names'||page==='routing') { try { [instances] = await get('instances'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } } + if (page==='routing') { try { [routes] = await get('routes'); } catch (err) { if (err.status === 403 || err.code === 'signed-out') throw err; } } + if (page==='tokens' && s.launch && !s.launch.refused) takeSnapshot(s.launch); + const notify = typeof n.binding==='string' ? `${txt(n.binding)}` : n.refused ? `Could not be read: ${txt(n.refused)}` : 'None set'; + const contents={limits:()=>launchForm(s.launch),routing:()=>routesSection(routes,instances),agents:()=>agentsSection(instances),assistant:()=>assistantSection(s.launch,names),tokens:()=>tokenLimits(limitRows,limitsRefused)+tokenUsage(usage),names:()=>testerNames(names,instances),about:()=>`
    Address
    ${txt(s.address)||'unknown'}
    Release
    ${txt(s.release)||'unknown'}
    Business
    ${txt(s.business)||none}
    Board
    ${txt(s.board)||'unknown'}
    Notifier binding
    ${notify}
    `, 'model-proxy':()=>'
    Open model proxy settings
    '}; + const helpers={limits:'Leave a limit blank for no limit. Zero stops new launches. Running sessions keep running when limits or models change.',routing:"Each agent’s harness, model and thinking, and the fallback a launch takes when the primary harness fails its preflight. A fallback sets all three or none. Running sessions keep their route. The next launch reads the change.",agents:'Each agent with its definition, launch membership and runs. A launch refuses until the agent has a route in Routing.',assistant:'The definition stays an assistant one. Holder and credentials stay hand edits.',tokens:'Token limits the bus checks, and token use read from session transcripts.'}; + return settingsShell(page,contents[page](),`${get.oldest()?`Read ${when(get.oldest())}.`: 'Reading…'} ${helpers[page]||''}`); + } + let settingsFocusDisclosure=false; + document.addEventListener('click', e=>{const b=e.target.closest?.('#settings-disclosure');if(b){b.setAttribute('aria-expanded',String(b.getAttribute('aria-expanded')!=='true'));return;} if(e.target.closest?.('#settings-nav a')) { const b=$('settings-disclosure'); if(b?.getAttribute('aria-expanded')==='true') {b.setAttribute('aria-expanded','false');settingsFocusDisclosure=true;b.focus();} }}); + document.addEventListener('keydown', e=>{if(e.key==='Escape' && $('settings-disclosure')?.getAttribute('aria-expanded')==='true'){e.preventDefault();$('settings-disclosure').setAttribute('aria-expanded','false');$('settings-disclosure').focus();}}); // Trail const GROUPS = [['all', 'All'], ['request', 'Requests'], ['decision', 'Decisions'], ['launch', 'Launches'], ['task', 'Task changes'], ['review', 'Review']]; @@ -1206,7 +1234,7 @@ if (a === 'queue' && n === 1) return queueView(get, q); if (a === 'queue' && n === 2) return /^[1-9]\d{0,5}$/.test(b) ? queueRowView(get, b) : notFound(`${txt(b)} is not a queue row id.`); if (a === 'business' && n === 1) return businessView(get); - if (a === 'settings' && n === 1) return settingsView(get); + if (a === 'settings' && (n === 1 || (n === 2 && [...settingsPages.map(p=>p[0]),'names'].includes(b)))) return settingsView(get, b || 'appearance'); if (a === 'docs' && n === 1) return docsView(get); if (a === 'docs' && n === 3) return docView(get, b, c, opts); if (a === 'trail' && n === 3 && b === 'task') return TASK.test(c) ? trailView(get, b, c, q) : notFound(`${txt(c)} is not a task reference.`); @@ -1214,7 +1242,7 @@ if (a === 'trail' && n === 3 && b === 'message') return SAFE.test(c) ? trailView(get, b, c, q) : notFound(`${txt(c)} is not a message id.`); return notFound(); } - let gen = 0, shown = null, timer; + let gen = 0, shown = null, timer, proxyCleanup=null; const paused = () => $('pause')?.getAttribute('aria-pressed') === 'true'; // A file open in the editor is never refreshed from under its draft; Reload is the person's to press. function schedule() { clearTimeout(timer); if (!paused() && !out() && !routeOf().startsWith('/docs/')) timer = setTimeout(() => render(false), 10000); } @@ -1224,6 +1252,7 @@ const a = document.activeElement, view = $('bus-view'); return { 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, field: view.contains(a) ? a.dataset?.field : null, caret: view.contains(a) && a.tagName === 'TEXTAREA' ? [a.selectionStart, a.selectionEnd, a.scrollTop] : null, send: view.contains(a) && a.hasAttribute?.('data-send'), decide: view.contains(a) ? a.dataset?.decide ?? (a.id === 'decide-status' ? 'status' : null) : null, open: [...view.querySelectorAll('details[id]')].filter(d => d.open).map(d => d.id), status: $('copy-status')?.textContent || '', @@ -1235,7 +1264,9 @@ const el = [...$('bus-view').querySelectorAll('a[href],[data-copy],[data-retry],[data-mirror],[data-field],[data-send]')].find(e => k.href ? e.getAttribute('href') === k.href : k.copy ? e.dataset.copy === k.copy : k.mirror ? e.dataset.mirror === k.mirror : k.field ? e.dataset.field === k.field : k.send ? e.hasAttribute('data-send') : k.retry && e.hasAttribute('data-retry')); // Row 252: the answer panel's buttons and its status line. const dec = k.decide ? $('bus-view').querySelector(k.decide === 'status' ? '#decide-status' : `[data-decide="${k.decide}"]`) : null; - if (dec) dec.focus({ preventScroll: true }); + const choice=k.settingsChoice && [...$('bus-view').querySelectorAll('input[type=radio]')].find(x=>x.name===k.settingsChoice[0]&&x.value===k.settingsChoice[1]); + 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)) { el.focus({ preventScroll: true }); if (k.caret && el.tagName === 'TEXTAREA') { el.setSelectionRange(k.caret[0], k.caret[1]); el.scrollTop = k.caret[2]; } @@ -1247,6 +1278,7 @@ clearTimeout(timer); if (out()) return; const route = routeOf(), [path, query = ''] = route.split('?'), board = path === '/' || path === '' || path === '/board'; + if (path !== '/settings/model-proxy' && proxyCleanup) {proxyCleanup();proxyCleanup=null;} // Leaving a decision discards its confirmation immediately, including a preview in flight. if (answer && (navigated || path !== `/inbox/${answer.id}`)) answer = null; const g = ++gen; @@ -1260,9 +1292,7 @@ document.querySelectorAll('.rail a').forEach(a => { const target = a.getAttribute('href').slice(1); const active = target === '/projects' ? /^\/(projects|chat)(\/|$)/.test(path) : target === '/' ? path === '/' : path === target; if (active) a.setAttribute('aria-current', 'page'); else a.removeAttribute('aria-current'); }); const chatPath = path === '/projects' ? '/chat' : /^\/projects\/(threads|rooms)\//.test(path) ? '/chat' + path.slice('/projects'.length) : /^\/projects\/[^/]+$/.test(path) ? '/chat/projects/' + path.slice('/projects/'.length) : path; window.MosaicChat?.leave(chatPath); - if (path === '/settings/display' && window.MosaicDisplay) { - window.MosaicDisplay.render($('bus-view'), navigated); shown = route; return; - } + if (path === '/settings/display') { location.replace('#/settings/appearance'); return; } if (chatPath === '/chat' || chatPath.startsWith('/chat/') || /^\/projects\/[0-9a-f-]+\/settings$/i.test(chatPath)) { // Row 177 (#1675): the tester Console writes to its own threads. const focusedHeading = document.activeElement === $('bus-view').querySelector('h1'); @@ -1305,11 +1335,13 @@ sections(path); schedule(); return; } + if (path === '/settings/model-proxy' && shown === route && !navigated) return; + if (($('agent-dialog')?.open || document.querySelector('.agent-more[aria-expanded=true]')) && !navigated) { schedule(); return; } if (navigated || shown !== route) { unmountEditor(); $('bus-view').innerHTML = loadingView(SOURCES[path.split('/')[1]]); } let html, state = 'fresh'; const live = reader(true); try { - if (path !== '/messages') { + if (path !== '/messages' && !['/settings','/settings/appearance','/settings/model-proxy'].includes(path)) { try { await live('messages'); } catch (err) { messageCount = null; if (err.status === 403 || err.code === 'signed-out') throw err; } } @@ -1327,13 +1359,14 @@ unmountEditor(); $('bus-view').innerHTML = html; shown = route; if (path.startsWith('/docs/')) paintDoc(); + if (path === '/settings/model-proxy') proxyCleanup=window.MosaicProxy.mount(); sections(path); const h1 = $('bus-view').querySelector('h1'); document.title = `${h1 ? h1.textContent : 'Console'} · Mosaic Console`; if (k) restore(k); // Message on the Board (row 95) lands in the form it opened, addressed to the role. else if (focusSend && $('send-body')) { $('send-body').focus(); announce(`Message to ${draft.to}`); } - else if (navigated && h1) { h1.focus(); announce(h1.textContent); } + else if (navigated && h1) { const target=settingsFocusDisclosure&&path.startsWith('/settings/') ? $('settings-disclosure') : path.startsWith('/settings/') ? ($('settings-page-title')||h1) : h1; settingsFocusDisclosure=false; target.focus(); announce(target.textContent); } focusSend = false; schedule(); } @@ -1490,7 +1523,7 @@ } if (!canSend && !isTester && !ssoOn) return; const path = routeOf().split('?')[0]; - if (path.startsWith('/chat')||path.startsWith('/projects')||path.startsWith('/inbox')||path==='/settings'||path.startsWith('/docs/')) render(false); else if (path === '/' || path === '') paintHeld(heldErr); + if (path.startsWith('/chat')||path.startsWith('/projects')||path.startsWith('/inbox')||path.startsWith('/settings')||path.startsWith('/docs/')) render(false); else if (path === '/' || path === '') paintHeld(heldErr); }).catch(() => {}); // This context comes from the conversations renderer after its authorized read. let projectContext = null; diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index 11336c2c8..859f2ed7b 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -1,51 +1,128 @@ -/* Browser-local sidebar display preferences. No project or authority data is stored here. */ +if (location.pathname === '/settings/model-proxy' && !location.hash) location.hash = '#/settings/model-proxy'; +/* Browser-local sidebar density. No authority or project data is stored here. */ (() => { - const key = 'mosaic-sidebar-display-v1'; - const defaults = () => ({ version: 1, density: 'comfortable', order: 'title-first' }); - const valid = x => x && x.version === 1 && ['comfortable', 'compact'].includes(x.density) && ['title-first', 'contact-first'].includes(x.order) && Object.keys(x).sort().join(',') === 'density,order,version'; - let saved = defaults(); - try { const value = JSON.parse(localStorage.getItem(key)); if (valid(value)) saved = value; } catch { /* inaccessible or invalid storage uses defaults */ } - let draft = { ...saved }, pending = null, dirty = false; - const apply = () => { document.documentElement.dataset.sidebarDensity = saved.density; document.documentElement.dataset.sidebarOrder = saved.order; document.dispatchEvent(new CustomEvent('mosaic-display-change', { detail: { ...saved } })); }; + const key='mosaic-sidebar-display-v1'; + const defaults=()=>({version:1,density:'comfortable',order:'title-first'}); + const valid=x=>x&&x.version===1&&['comfortable','compact'].includes(x.density)&&['title-first','contact-first'].includes(x.order)&&Object.keys(x).sort().join(',')==='density,order,version'; + let saved=defaults(); + try {const value=JSON.parse(localStorage.getItem(key));if(valid(value))saved=value;} catch {} + const apply=()=>{document.documentElement.dataset.sidebarDensity=saved.density;document.documentElement.dataset.sidebarOrder=saved.order;document.dispatchEvent(new CustomEvent('mosaic-display-change',{detail:{...saved}}));}; apply(); - function save() { - try { localStorage.setItem(key, JSON.stringify(draft)); saved = { ...draft }; dirty = false; apply(); return true; } - catch { return false; } + window.MosaicDisplay={get:()=>({...saved}),setDensity(density){if(!['comfortable','compact'].includes(density))return false;saved={...saved,density};apply();try{localStorage.setItem(key,JSON.stringify(saved));return true;}catch{return false;}}}; +})(); + +// P4 page: credentials and OAuth state exist only during the current operation. +// No browser storage, request/body logging, key reveal, or automatic write retry. +(() => { + 'use strict'; + const markup = '

    Reading accounts…

    \n\n

    Accounts

    \n

    Higher priority is used first. Account names are stable identifiers; credential values are never displayed.

    \n
    AccountProviderStatusPriority
    \n

    Sign in to an account

    \n
    Subscription account
    \n

    \n

    \n
    Finish sign-in

    If the sign-in tab does not return, copy its full address and paste it here.

    \n

    Add an API key

    \n
    z.ai

    The key is sent once and cleared from this field. It will never be shown again.

    \n

    Client keys

    Only key IDs are shown. Hire and fire manage agent keys.

    \n
    Key IDManaged byAgentIssuedState
    \n'; + function mount() { + const $ = id => document.getElementById(id); + let canWrite = false, login = null, poll = null, busy = false; + const message = (text, loginOnly = false) => { $(loginOnly ? 'proxy-login-message' : 'proxy-message').textContent = text; }; + const cell = value => { const td = document.createElement('td'); td.textContent = value ?? '—'; return td; }; + async function call(path, args) { + const response = await fetch('/api/proxy/' + path, { cache: 'no-store', credentials: 'same-origin', + method: args === undefined ? 'GET' : 'POST', + ...(args === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(args) }), + }); + const value = await response.json(); + if (!response.ok) { + if (response.status === 401) throw new Error('Sign in to the Console again.'); + if (value.error === 'not-configured') throw new Error('The model proxy is not configured for this instance.'); + if (value.error === 'login-state-unknown') throw new Error('This sign-in has ended. Start a new sign-in.'); + if (value.error === 'apikey-invalid') throw new Error('Enter a nonempty API key, with no spaces or line breaks.'); + throw new Error('The operation could not be confirmed. Nothing was retried. Refresh before trying again.'); + } + return value; + } + function endLogin() { + clearTimeout(poll); poll = null; login = null; + $('proxy-authorize').removeAttribute('href'); $('proxy-authorize').hidden = true; + $('proxy-login-submit').elements.redirect_url.value = ''; } - function status(message) { const el = document.getElementById('display-status'); if (el) el.textContent = message; } - function render(container, navigated) { - container.innerHTML = `

    Sidebar display

    These choices apply in this browser.

    Density
    Sidebar order

    Sidebar ordering is not available yet.

    Preview uses the current sidebar destinations.

    `; - const form = document.getElementById('display-form'); - for (const name of ['density', 'order']) form.elements[name].value = draft[name]; - const preview = document.getElementById('display-preview'); - preview.textContent = [...document.querySelectorAll('#sections .s1-section')].map(el => el.textContent.trim()).join(' · '); - form.addEventListener('change', () => { draft = { version: 1, density: form.elements.density.value, order: saved.order }; dirty = JSON.stringify(draft) !== JSON.stringify(saved); status(dirty ? 'Unsaved changes.' : ''); }); - form.addEventListener('submit', e => { e.preventDefault(); if (!dirty) { status('No display changes to save.'); return; } status(save() ? 'Sidebar display saved.' : 'Could not save to local browser storage. Your choices are kept. Try Save again, edit, or discard when leaving.'); }); - document.title = 'Sidebar display · Mosaic Console'; - if (navigated) container.querySelector('h1').focus(); + async function status() { + if (!login) return; + const active = login; + try { + const result = await call('login/status', { state: active.state }); + if (active !== login) return; + if (result.status === 'wait') { message('Waiting for account sign-in…', true); poll = setTimeout(status, 2000); return; } + endLogin(); + if (result.status === 'ok') { message('Account signed in.', true); await refresh(); } + else message(result.reason === 'login-timeout' ? 'Sign-in timed out. Start again.' : 'Account sign-in failed. Start again.', true); + } catch (error) { if (active === login) { endLogin(); message(error.message, true); } } } - const dialog = document.createElement('dialog'); dialog.className = 'display-dialog'; - dialog.setAttribute('aria-labelledby', 'display-leave-title'); - dialog.innerHTML = '

    Unsaved sidebar display

    Your choices are kept while you decide.

    '; - document.body.append(dialog); - let current = location.hash || '#/'; - window.addEventListener('hashchange', e => { - const destination = location.hash || '#/'; - if (current === '#/settings/display' && destination !== current && dirty) { - e.stopImmediatePropagation(); pending = destination; history.replaceState(null, '', current); document.getElementById('display-leave-status').textContent = ''; dialog.showModal(); dialog.querySelector('[data-choice=save]').focus(); return; - } - current = destination; + async function refresh() { + const [accounts, keys] = await Promise.all([call('accounts'), call('keys')]); + const rows = accounts.accounts.map(account => { + const row = document.createElement('tr'); + row.append(cell(account.displayName), cell(account.provider), cell(account.status)); + const td = document.createElement('td'), form = document.createElement('form'); + const input = document.createElement('input'); input.type = 'number'; input.min = '-1000'; input.max = '1000'; input.step = '1'; input.value = account.priority; + input.setAttribute('aria-label', `Priority for ${account.displayName}`); input.disabled = !canWrite; + const save = document.createElement('button'); save.type = 'submit'; save.textContent = 'Set priority'; save.disabled = !canWrite; save.hidden = !canWrite; + form.append(input, save); form.addEventListener('submit', async event => { + event.preventDefault(); if (!canWrite || busy || !input.checkValidity()) return; + busy = true; save.disabled = true; + try { await call('priority/set', { accountId: account.accountId, priority: Number(input.value) }); message('Priority saved.'); await refresh(); } + catch (error) { message(error.message); } + finally { busy = false; save.disabled = !canWrite; } + }); + td.append(form); row.append(td); return row; + }); + $('proxy-accounts').replaceChildren(...rows); + if (!rows.length) { const row = document.createElement('tr'); const td = cell('No accounts configured.'); td.colSpan = 4; row.append(td); $('proxy-accounts').append(row); } + $('proxy-keys').replaceChildren(...keys.keys.map(key => { + const row = document.createElement('tr'); row.append(cell(key.keyId), cell(key.management), cell(key.agent), cell(key.issuedAt), cell(key.state)); return row; + })); + } + $('proxy-refresh').addEventListener('click', () => refresh().then(() => message('Accounts and client keys refreshed.')).catch(e => message(e.message))); + $('proxy-login-start').addEventListener('submit', async event => { + event.preventDefault(); if (!canWrite || busy || login) return; + busy = true; + try { + login = await call('login/start', { provider: event.currentTarget.elements.provider.value }); + $('proxy-authorize').href = login.url; $('proxy-authorize').hidden = false; + window.open(login.url, '_blank', 'noopener,noreferrer'); + message('Complete account sign-in in the new tab, or use the sign-in link.', true); + poll = setTimeout(status, 2000); + } catch (error) { message(error.message, true); } + finally { busy = false; } + }); + $('proxy-login-submit').addEventListener('submit', async event => { + event.preventDefault(); if (!canWrite || busy || !login) return; + const input = event.currentTarget.elements.redirect_url, redirect_url = input.value; input.value = ''; + busy = true; + try { await call('login/submit', { redirect_url }); message('Address submitted. Waiting for sign-in confirmation…', true); } + catch (error) { message(error.message, true); } + finally { busy = false; } + }); + $('proxy-login-cancel').addEventListener('click', async () => { + if (!canWrite || busy || !login) return; + busy = true; clearTimeout(poll); + try { await call('login/cancel', { state: login.state }); endLogin(); message('Sign-in cancelled.', true); } + catch (error) { endLogin(); message(error.message, true); } + finally { busy = false; } }); - dialog.addEventListener('cancel', e => { e.preventDefault(); dialog.close(); pending = null; document.querySelector('#display-form input')?.focus(); }); - dialog.addEventListener('click', e => { - const choice = e.target.dataset.choice; if (!choice) return; - if (choice === 'save' && !save()) { document.getElementById('display-leave-status').textContent = 'Could not save to local browser storage. Your choices are kept. Retry, keep editing, or discard.'; return; } - if (choice === 'discard') { draft = { ...saved }; dirty = false; } - dialog.close(); - if (choice === 'edit') { pending = null; document.querySelector('#display-form input')?.focus(); return; } - const destination = pending; pending = null; if (choice === 'save') sessionStorageNotice(); location.hash = destination; + $('proxy-apikey').addEventListener('submit', async event => { + event.preventDefault(); if (!canWrite || busy) return; + const input = event.currentTarget.elements.key, key = input.value; input.value = ''; + busy = true; + try { await call('apikey/add', { provider: 'z.ai', key }); message('API key added.'); await refresh(); } + catch (error) { message(error.message); } + finally { busy = false; } }); - function sessionStorageNotice() { const a = document.getElementById('display-announcement'); if (a) a.textContent = 'Sidebar display saved.'; } - document.addEventListener('mosaic-signed-out', () => { draft = { ...saved }; dirty = false; pending = null; if (dialog.open) dialog.close(); }); - window.MosaicDisplay = { render }; + const cleanup = () => { clearTimeout(poll); login = null; const redirect=$('proxy-login-submit')?.elements.redirect_url, key=$('proxy-apikey')?.elements.key; if(redirect)redirect.value='';if(key)key.value=''; }; + window.addEventListener('pagehide', cleanup, {once:true}); + fetch('/api/config', { cache: 'no-store' }).then(r => r.json()).then(config => { + canWrite = config.send === true && config.tester !== true && config.user !== true; + document.querySelectorAll('[data-write]').forEach(fieldset => { fieldset.disabled = !canWrite; }); + $('proxy-readonly').hidden = canWrite; + if (!canWrite) document.querySelectorAll('[aria-labelledby=proxy-signin-title],[aria-labelledby=proxy-apikey-title]').forEach(el=>el.hidden=true); + return refresh(); + }).then(() => message('Accounts and client keys loaded.')).catch(error => { message(error.message); if(error.message==='The model proxy is not configured for this instance.') { $('proxy-message').classList.add('empty'); $('proxy-readonly').hidden=true; document.querySelectorAll('.settings-model-proxy .panel, #proxy-refresh').forEach(el=>el.hidden=true); } }); + return cleanup; + } + window.MosaicProxy={markup,mount}; })(); diff --git a/packages/webui/src/public/index.html b/packages/webui/src/public/index.html index a16a16f95..7836d65c7 100644 --- a/packages/webui/src/public/index.html +++ b/packages/webui/src/public/index.html @@ -7,11 +7,12 @@ +
    Mosaic Stack

    -
    Processing unavailable
    +
    Processing unavailable
    diff --git a/packages/webui/src/public/proxy.html b/packages/webui/src/public/proxy.html index c134b1b50..7836d65c7 100644 --- a/packages/webui/src/public/proxy.html +++ b/packages/webui/src/public/proxy.html @@ -1,26 +1,44 @@ - -Model proxy · Settings · Mosaic Console - - - -
    MosaicConsoleBack to Settings
    -
    -

    Settings

    Model proxy

    Accounts used by this instance, their priority, and the client keys assigned to agents.

    -

    Reading accounts…

    - -

    Accounts

    -

    Higher priority is used first. Account names are stable identifiers; credential values are never displayed.

    -
    AccountProviderStatusPriority
    -

    Sign in to an account

    -
    Subscription account
    -

    -

    -
    Finish sign-in

    If the sign-in tab does not return, copy its full address and paste it here.

    -

    Add an API key

    -
    z.ai

    The key is sent once and cleared from this field. It will never be shown again.

    -

    Client keys

    Only key IDs are shown. Hire and fire manage agent keys.

    -
    Key IDManaged byAgentIssuedState
    -

    Usage

    Usage reporting will appear here when its view is available.

    -
    +Dashboard · Mosaic Console + + + + + + + + +
    Mosaic Stack + +

    +
    Processing unavailable
    + +
    +
    + +

    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.
    +

    Processing

    +Processing

    Reading processing state.

    + + +

    Processing controls are unavailable here. Use mosaic halt or mosaic resume from the instance CLI.

    +

    Needs your input

    Not available yet

    Open Inbox →
    + + + +

    Waiting on you 0

    Loading sessions…

    +
    Seen 0
    +

    All sessions 0

    Select an agent to inspect. Arrow keys move between agents; Enter opens the inspector. Scroll the table for all columns.

    Loading sessions…
    + +
    + +
    Mosaic Stack
    +
    +

      ↑↓ move · Enter open · Esc close

      + diff --git a/packages/webui/src/public/shell.css b/packages/webui/src/public/shell.css index 82d73bd23..bd145e3c6 100644 --- a/packages/webui/src/public/shell.css +++ b/packages/webui/src/public/shell.css @@ -225,3 +225,71 @@ body.on-bus #board-refused{display:none} a{ text-underline-offset: .15em } button:disabled,[aria-disabled=true]{cursor:not-allowed} @media (max-width:759px){.tree{width:100%;overscroll-behavior:contain;scrollbar-gutter:stable}#console-nav>*{flex:0 0 auto}} +/* Settings uses the same shell and palette tokens as the rest of the Console. */ +.settings-layout{display:grid;grid-template-columns:220px minmax(0,1fr);gap:32px;align-items:start} +#settings-nav{display:flex;flex-direction:column} +.settings-group{font-size:12px;font-weight:600;color:var(--muted);margin:0 0 8px} +.settings-group:not(:first-child){margin-top:16px} +#settings-nav a{min-height:44px;padding:11px 16px;border-left:3px solid transparent;border-radius:var(--r);color:var(--text);text-decoration:none;font-size:14px;font-weight:500} +#settings-nav a:hover,#settings-nav a[aria-current=page]{background:var(--raised)} +#settings-nav a[aria-current=page]{border-left-color:var(--action);color:var(--strong);font-weight:600} +.settings-dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--warning);margin-left:8px} +#settings-disclosure{display:none} +.settings-content{min-width:0} +.settings-content>h2{font-size:23px;line-height:1.3;margin:0;color:var(--strong)} +.settings-helper{font-size:14px;color:var(--muted);margin:0 0 16px} +.settings-content .panel{margin:0 0 16px;padding:16px} +.settings-content .panel h3{font-size:16px;margin:0;color:var(--strong)} +.settings-content .panel>p{margin:4px 0 12px;color:var(--muted);font-size:14px} +.settings-content input:not([type=radio]):not([type=checkbox]),.settings-content select,.settings-content textarea{min-height:44px;max-width:100%;border:1px solid var(--border);border-radius:var(--r);background:var(--canvas);color:var(--text);font:inherit;padding:8px 12px} +.settings-content input:disabled,.settings-content select:disabled,.settings-content textarea:disabled{background:var(--raised);border-color:var(--line);color:var(--muted)} +.settings-content button,.settings-content summary{min-height:44px;min-width:44px;border:1px solid var(--border);border-radius:var(--r);background:var(--surface);color:var(--text);padding:8px 18px;font:inherit;cursor:pointer} +.settings-content button[type=submit]{background:var(--accent-fill);color:var(--on-accent);border-color:var(--accent-fill)} +.settings-content :is(button,input,select,textarea,a,summary):focus-visible,#settings-nav a:focus-visible,#settings-disclosure:focus-visible{outline:2px solid var(--focus);outline-offset:2px} +.settings-segments{display:inline-flex;max-width:100%;border:1px solid var(--border);border-radius:var(--r);overflow:hidden} +.settings-segments label{position:relative;display:block} +.settings-segments input,.palette-tile input{position:absolute;opacity:0;width:1px;height:1px} +.settings-segments span{display:grid;place-items:center;min-height:44px;min-width:104px;padding:0 14px;border-right:1px solid var(--border);cursor:pointer;font-size:14px} +.settings-segments label:last-child span{border:0}.settings-segments input:checked+span{background:var(--action);color:var(--onAction);font-weight:600}.settings-segments input:focus-visible+span,.palette-tile input:focus-visible+.palette-content{outline:2px solid var(--focus);outline-offset:-3px} +.settings-segments input:hover:not(:checked)+span{background:var(--raised)} +.settings-appearance .panel:last-child .settings-segments span{min-width:140px} +.palette-grid{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px} +.palette-tile{position:relative;min-width:0;cursor:pointer} +.palette-content{position:relative;display:flex;min-height:72px;flex-direction:column;justify-content:center;gap:5px;padding:8px 16px;border:1px solid var(--line);border-radius:var(--r);font-size:14px} +.palette-content:hover{border-color:var(--border)}.palette-tile input:checked+.palette-content{border:2px solid var(--action);background:var(--raised);padding:7px 15px;color:var(--strong)} +.palette-check{display:none;position:absolute;right:9px;top:5px;color:var(--action);font-size:19px}.palette-tile input:checked+.palette-content .palette-check{display:block} +.palette-swatches{display:flex;gap:6px}.palette-swatches i{display:block;width:16px;height:16px;border-radius:50%;background:var(--swatch-canvas);border:1px solid var(--line)}.palette-swatches i:nth-child(2){background:var(--swatch-action);border:0}.palette-swatches i:nth-child(3){background:var(--swatch-accent);border:0} +.settings-browser-status{color:var(--success)!important;margin:0!important}.settings-browser-status:not(:empty){margin-top:10px!important}.settings-browser-status.warning{color:var(--warning)!important} +.settings-readonly{padding:12px 16px;background:var(--raised);border-radius:var(--r)} +@media(max-width:959px) and (min-width:760px){.settings-layout{grid-template-columns:180px minmax(0,1fr);gap:24px}} +@media(max-width:759px){.settings-layout{display:block}.settings-layout>div:first-child{margin-bottom:20px}#settings-disclosure{width:100%;min-height:44px;display:flex;align-items:center;gap:12px;padding:6px 12px;border:1px solid var(--border);border-radius:var(--r);background:var(--surface);color:var(--text);text-align:left}#settings-disclosure small{color:var(--muted)}#settings-disclosure span{margin-left:auto}#settings-disclosure[aria-expanded=false]+#settings-nav{display:none}#settings-nav{padding:12px 0}.settings-content>h2{font-size:21px}.palette-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:11px}.palette-content{min-height:64px;padding:7px}.palette-tile input:checked+.palette-content{padding:6px}.settings-segments{display:flex;width:100%}.settings-segments label{flex:1;min-width:0}.settings-segments span,.settings-appearance .panel:last-child .settings-segments span{min-width:0;padding:0 4px}.settings-content .table-wrap{max-width:100%}} +.settings-content [aria-invalid=true]{border:2px solid var(--danger)!important} +.fallback-toggle{display:none} +@media(max-width:759px){ + .settings-actions.has-draft{position:fixed;z-index:20;bottom:0;left:0;right:0;display:flex;gap:8px;align-items:center;padding:12px;background:var(--surface);border-top:1px solid var(--line)} + .settings-actions.has-draft button{flex:1}.settings-actions.has-draft p{display:none}.settings-content:has(.settings-actions.has-draft){padding-bottom:90px} + #routes-table,#routes-table tbody,#routes-table tr,#routes-table th,#routes-table td{display:block;width:100%}#routes-table thead{display:none}#routes-table tr{border:1px solid var(--line);border-radius:var(--r);margin:0 0 12px;padding:12px}#routes-table td{border:0;padding:4px 0}#routes-table td::before{content:attr(data-label);display:block;color:var(--muted);font-size:12px}#routes-table select{width:100%}.fallback-toggle{display:block;width:100%}.route-row:not(.fallback-open) .fallback-cell select,.route-row:not(.fallback-open) .fallback-cell:not(:nth-of-type(4)){display:none}.route-row.fallback-open .fallback-toggle{display:none} +} +.agent-actions{position:relative;white-space:nowrap}.agent-actions .agent-more{padding:0;margin-left:6px}.agent-menu{position:absolute;right:0;z-index:10;min-width:180px;background:var(--surface);border:1px solid var(--line);border-radius:var(--r);box-shadow:0 6px 18px var(--shadow,transparent)}.agent-menu[hidden]{display:none}.agent-menu button{display:block;width:100%;border:0;text-align:left;background:transparent}.agent-menu button:hover,.agent-menu button:focus{background:var(--raised)}.agent-danger{color:var(--danger)!important}.hiring-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px 20px}.hiring-grid>div{display:flex;align-items:center;justify-content:space-between}.hiring-grid button[role=switch]{border:0;background:transparent;padding:10px 0}.switch-track{display:block;width:44px;height:24px;background:var(--raised);border:1px solid var(--border);border-radius:12px;position:relative}.switch-track:after{content:'';position:absolute;top:3px;left:3px;width:16px;height:16px;background:var(--muted);border-radius:50%}[aria-checked=true]>.switch-track{background:var(--action)}[aria-checked=true]>.switch-track:after{left:23px;background:var(--onAction)} +@media(max-width:759px){.hiring-grid{grid-template-columns:1fr}} +.settings-content.readonly :is(button[type=submit],button[data-limit-reset],#routes-reload,#launch-settings-reload,[data-assistant-name],[data-assistant-stop]){display:none} +.settings-content input::placeholder,.settings-content textarea::placeholder{color:var(--muted)} +.settings-success{color:var(--success)} +.settings-content fieldset{border:0;padding:0;margin:12px 0;min-width:0}.settings-content legend{color:var(--muted);font-size:12px;font-weight:600}.settings-content .filters{gap:12px}.settings-content label{min-width:0}.settings-content label:has(input[type=number]){display:flex;align-items:center;gap:12px;flex-wrap:wrap}.settings-content input[type=number]{width:120px}.settings-content .settings-actions{display:flex;gap:8px;align-items:center;flex-wrap:wrap} +@media(max-width:759px){#agents-table,#agents-table tbody,#agents-table tr,#agents-table td,#agents-table th{display:block;width:100%}#agents-table thead{display:none}#agents-table tr{border:1px solid var(--line);border-radius:var(--r);margin-bottom:12px;padding:12px}#agents-table td{border:0;padding:4px}.agent-actions{white-space:normal}.agent-menu{right:0}} +#agents-table tbody th,#routes-table tbody th{text-transform:none;font-size:14px;font-weight:600;color:var(--strong)} +@media(max-width:759px){.settings-content .routing-panel{border:0;background:transparent;padding:0}.routing-panel .table-wrap{border:0;overflow:visible}.routing-panel #routes-table tr{display:grid;grid-template-columns:1fr 1fr;gap:0 10px;background:var(--surface)}.routing-panel #routes-table th,.routing-panel #routes-table td:first-of-type,.routing-panel #routes-table .fallback-cell:first-of-type{grid-column:1/-1}.routing-panel #routes-table td:nth-of-type(4){grid-column:1/-1}.routing-panel #routes-table td:nth-of-type(4)::before{content:'Fallback: None'}.routing-panel #routes-table .fallback-open td:nth-of-type(4)::before{content:'Fallback harness'}} +.settings-content label:has(>input[type=checkbox]){display:inline-flex;align-items:center;gap:8px;min-height:44px;padding:0 8px} +.settings-content .instance-form textarea,.settings-content .assistant-form textarea{display:block;width:100%} +.route-definition{display:none}.settings-spinner{display:inline-block;width:16px;height:16px;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;vertical-align:middle;animation:settings-spin .8s linear infinite}@keyframes settings-spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.settings-spinner{animation:none}} +@media(max-width:759px){#routes-table .route-definition{display:inline;float:right;color:var(--muted);font-size:12px;font-weight:400}} +/* Settings forms: align controls across rows without changing their write paths. */ +#settings-page-title:focus{outline:none} +.settings-limits-table,.settings-model-table{width:100%;table-layout:fixed;border-collapse:collapse} +.settings-limits-table col:first-child{width:45%}.settings-limits-table col:nth-child(2){width:144px}.settings-model-table col:first-child{width:25%}.settings-model-table col:nth-child(2),.settings-model-table col:nth-child(3){width:37.5%} +.settings-limits-table :is(th,td),.settings-model-table :is(th,td){padding:8px;text-align:left;vertical-align:middle}.settings-limits-table tbody th,.settings-model-table tbody th{text-transform:none;font-size:14px;font-weight:500;color:var(--text)}.settings-limits-table .limit-group th{padding-top:14px;color:var(--muted);font-size:12px;font-weight:600}.settings-model-table input{width:100%} +.settings-content .instance-form .filters{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) auto;gap:var(--gap);align-items:end}.settings-content .instance-form .filters>label:not(:has(input[type=checkbox])){display:flex;flex-direction:column;gap:6px}.settings-content .instance-form .filters>label:not(:has(input[type=checkbox])) :is(input,select){width:100%}.settings-content .instance-form .filters>label:has(input[type=checkbox]){display:flex;gap:8px;align-items:center;min-height:44px;white-space:nowrap}.settings-content .instance-form details{margin:var(--gap) 0}.hiring-grid>div{justify-content:flex-start;gap:var(--gap)} +@media(max-width:759px){.settings-content .instance-form .filters{grid-template-columns:1fr}.settings-limits-table,.settings-limits-table tbody,.settings-limits-table tr,.settings-limits-table th,.settings-limits-table td,.settings-model-table,.settings-model-table tbody,.settings-model-table tr,.settings-model-table th,.settings-model-table td{display:block;width:100%}.settings-limits-table colgroup,.settings-model-table colgroup,.settings-limits-table thead,.settings-model-table thead{display:none}.settings-limits-table tbody tr:not(.limit-group){display:grid;grid-template-columns:120px 1fr;gap:0 12px;border-bottom:1px solid var(--line)}.settings-limits-table tbody tr:not(.limit-group)>th{grid-column:1/-1}.settings-limits-table :is(th,td),.settings-model-table :is(th,td){padding:6px 0}.settings-model-table tbody tr{padding:8px 0;border-bottom:1px solid var(--line)}.settings-model-table td:before{display:block;color:var(--muted);font-size:12px}.settings-model-table td:nth-of-type(1):before{content:'Provider'}.settings-model-table td:nth-of-type(2):before{content:'Model'}#routes-table .route-row:not(.fallback-open) td.fallback-cell:nth-of-type(n+5){display:none}} + +/* Agent menus must extend beyond the table without being clipped by its scroll region. */ +.settings-agents .table-wrap{overflow:visible} diff --git a/packages/webui/src/public/tokens.css b/packages/webui/src/public/tokens.css index 428331d6c..1f8be0d7d 100644 --- a/packages/webui/src/public/tokens.css +++ b/packages/webui/src/public/tokens.css @@ -830,3 +830,59 @@ @media(prefers-color-scheme:dark){:root[data-palette="harbor"]:not([data-mode="light"]):not([data-mode="dim"]){--nav-surface:#10141c;--line-soft:#333b47;--accent-fill:#276bd8;--on-accent:#ffffff;--logo-a:#3691f2;--logo-b:#4a9af5;--logo-c:#3691f2;--logo-d:#1b3e79}} :root[data-palette="harbor"][data-mode="light"]{--nav-surface:#f7f9fc;--accent-fill:#2266bf;--on-accent:#ffffff} @media(prefers-color-scheme:light){:root[data-palette="harbor"]:not([data-mode]){--nav-surface:#f7f9fc;--accent-fill:#2266bf;--on-accent:#ffffff}} + +/* Palette previews use the same per-mode colors as the page tokens. */ +:root[data-mode="light"] [data-swatch="harbor"]{--swatch-canvas:#f1f5fa;--swatch-action:#2266bf;--swatch-accent:#8d5e20} +:root[data-mode="light"] [data-swatch="carmine"]{--swatch-canvas:#f7f3f3;--swatch-action:#b92740;--swatch-accent:#2e706c} +:root[data-mode="light"] [data-swatch="atlantic"]{--swatch-canvas:#f3f6f7;--swatch-action:#19719a;--swatch-accent:#257467} +:root[data-mode="light"] [data-swatch="terracotta"]{--swatch-canvas:#f7f4f3;--swatch-action:#a74f2a;--swatch-accent:#356f88} +:root[data-mode="light"] [data-swatch="aubergine"]{--swatch-canvas:#f5f4f6;--swatch-action:#88469b;--swatch-accent:#77672c} +:root[data-mode="light"] [data-swatch="mineral"]{--swatch-canvas:#f3f6f6;--swatch-action:#2a7469;--swatch-accent:#9f414f} +:root[data-mode="light"] [data-swatch="cobalt"]{--swatch-canvas:#f3f3f7;--swatch-action:#1c3bc4;--swatch-accent:#79671b} +:root[data-mode="light"] [data-swatch="rosewood"]{--swatch-canvas:#f6f3f5;--swatch-action:#a53b72;--swatch-accent:#416c95} +:root[data-mode="light"] [data-swatch="graphite"]{--swatch-canvas:#f5f5f5;--swatch-action:#616975;--swatch-accent:#5e6978} +:root[data-mode="light"] [data-swatch="grove"]{--swatch-canvas:#f4f6f5;--swatch-action:#377752;--swatch-accent:#9c444a} +:root[data-mode="dim"] [data-swatch="harbor"]{--swatch-canvas:#242d38;--swatch-action:#8ab4ea;--swatch-accent:#e1b47a} +:root[data-mode="dim"] [data-swatch="carmine"]{--swatch-canvas:#372528;--swatch-action:#e996a4;--swatch-accent:#8bd0cb} +:root[data-mode="dim"] [data-swatch="atlantic"]{--swatch-canvas:#243238;--swatch-action:#73c3e8;--swatch-accent:#83d8ca} +:root[data-mode="dim"] [data-swatch="terracotta"]{--swatch-canvas:#362b26;--swatch-action:#e2a68d;--swatch-accent:#89bcd1} +:root[data-mode="dim"] [data-swatch="aubergine"]{--swatch-canvas:#312933;--swatch-action:#cba4d6;--swatch-accent:#d3c388} +:root[data-mode="dim"] [data-swatch="mineral"]{--swatch-canvas:#273432;--swatch-action:#87d4c8;--swatch-accent:#e0b3ba} +:root[data-mode="dim"] [data-swatch="cobalt"]{--swatch-canvas:#242838;--swatch-action:#94a5f0;--swatch-accent:#e1ce7a} +:root[data-mode="dim"] [data-swatch="rosewood"]{--swatch-canvas:#34272e;--swatch-action:#dc9ebe;--swatch-accent:#95b3d0} +:root[data-mode="dim"] [data-swatch="graphite"]{--swatch-canvas:#2d2e2f;--swatch-action:#b1b6be;--swatch-accent:#afb6c0} +:root[data-mode="dim"] [data-swatch="grove"]{--swatch-canvas:#29332d;--swatch-action:#8fcca9;--swatch-accent:#ddb1b4} +:root[data-mode="dark"] [data-swatch="harbor"]{--swatch-canvas:#141821;--swatch-action:#64b5ff;--swatch-accent:#e1b47a} +:root[data-mode="dark"] [data-swatch="carmine"]{--swatch-canvas:#1b1214;--swatch-action:#e2788a;--swatch-accent:#8bd0cb} +:root[data-mode="dark"] [data-swatch="atlantic"]{--swatch-canvas:#12191c;--swatch-action:#73c3e8;--swatch-accent:#83d8ca} +:root[data-mode="dark"] [data-swatch="terracotta"]{--swatch-canvas:#1b1513;--swatch-action:#de9a7c;--swatch-accent:#89bcd1} +:root[data-mode="dark"] [data-swatch="aubergine"]{--swatch-canvas:#18141a;--swatch-action:#bf8ecc;--swatch-accent:#d3c388} +:root[data-mode="dark"] [data-swatch="mineral"]{--swatch-canvas:#141a19;--swatch-action:#87d4c8;--swatch-accent:#d18f99} +:root[data-mode="dark"] [data-swatch="cobalt"]{--swatch-canvas:#12141c;--swatch-action:#798eec;--swatch-accent:#e1ce7a} +:root[data-mode="dark"] [data-swatch="rosewood"]{--swatch-canvas:#1a1417;--swatch-action:#d487af;--swatch-accent:#8eaecd} +:root[data-mode="dark"] [data-swatch="graphite"]{--swatch-canvas:#161718;--swatch-action:#a6acb5;--swatch-accent:#a4abb7} +:root[data-mode="dark"] [data-swatch="grove"]{--swatch-canvas:#141917;--swatch-action:#8fcca9;--swatch-accent:#cd8e92} +@media(prefers-color-scheme:light){ +:root:not([data-mode]) [data-swatch="harbor"]{--swatch-canvas:#f1f5fa;--swatch-action:#2266bf;--swatch-accent:#8d5e20} +:root:not([data-mode]) [data-swatch="carmine"]{--swatch-canvas:#f7f3f3;--swatch-action:#b92740;--swatch-accent:#2e706c} +:root:not([data-mode]) [data-swatch="atlantic"]{--swatch-canvas:#f3f6f7;--swatch-action:#19719a;--swatch-accent:#257467} +:root:not([data-mode]) [data-swatch="terracotta"]{--swatch-canvas:#f7f4f3;--swatch-action:#a74f2a;--swatch-accent:#356f88} +:root:not([data-mode]) [data-swatch="aubergine"]{--swatch-canvas:#f5f4f6;--swatch-action:#88469b;--swatch-accent:#77672c} +:root:not([data-mode]) [data-swatch="mineral"]{--swatch-canvas:#f3f6f6;--swatch-action:#2a7469;--swatch-accent:#9f414f} +:root:not([data-mode]) [data-swatch="cobalt"]{--swatch-canvas:#f3f3f7;--swatch-action:#1c3bc4;--swatch-accent:#79671b} +:root:not([data-mode]) [data-swatch="rosewood"]{--swatch-canvas:#f6f3f5;--swatch-action:#a53b72;--swatch-accent:#416c95} +:root:not([data-mode]) [data-swatch="graphite"]{--swatch-canvas:#f5f5f5;--swatch-action:#616975;--swatch-accent:#5e6978} +:root:not([data-mode]) [data-swatch="grove"]{--swatch-canvas:#f4f6f5;--swatch-action:#377752;--swatch-accent:#9c444a} +} +@media(prefers-color-scheme:dark){ +:root:not([data-mode]) [data-swatch="harbor"]{--swatch-canvas:#141821;--swatch-action:#64b5ff;--swatch-accent:#e1b47a} +:root:not([data-mode]) [data-swatch="carmine"]{--swatch-canvas:#1b1214;--swatch-action:#e2788a;--swatch-accent:#8bd0cb} +:root:not([data-mode]) [data-swatch="atlantic"]{--swatch-canvas:#12191c;--swatch-action:#73c3e8;--swatch-accent:#83d8ca} +:root:not([data-mode]) [data-swatch="terracotta"]{--swatch-canvas:#1b1513;--swatch-action:#de9a7c;--swatch-accent:#89bcd1} +:root:not([data-mode]) [data-swatch="aubergine"]{--swatch-canvas:#18141a;--swatch-action:#bf8ecc;--swatch-accent:#d3c388} +:root:not([data-mode]) [data-swatch="mineral"]{--swatch-canvas:#141a19;--swatch-action:#87d4c8;--swatch-accent:#d18f99} +:root:not([data-mode]) [data-swatch="cobalt"]{--swatch-canvas:#12141c;--swatch-action:#798eec;--swatch-accent:#e1ce7a} +:root:not([data-mode]) [data-swatch="rosewood"]{--swatch-canvas:#1a1417;--swatch-action:#d487af;--swatch-accent:#8eaecd} +:root:not([data-mode]) [data-swatch="graphite"]{--swatch-canvas:#161718;--swatch-action:#a6acb5;--swatch-accent:#a4abb7} +:root:not([data-mode]) [data-swatch="grove"]{--swatch-canvas:#141917;--swatch-action:#8fcca9;--swatch-accent:#cd8e92} +} diff --git a/packages/webui/tests/agents-browser.test.mjs b/packages/webui/tests/agents-browser.test.mjs index f85722ca9..183e1b7e6 100644 --- a/packages/webui/tests/agents-browser.test.mjs +++ b/packages/webui/tests/agents-browser.test.mjs @@ -24,34 +24,29 @@ test('row 194 T16 Settings Agents: unavailable read-only, launch follows its req const port=web.address().port; const wait=expr=>b.evaluate(`(async()=>{for(let n=0;n<400;n++){if(${expr})return true;await new Promise(r=>setTimeout(r,30));}throw Error('wait failed: '+${JSON.stringify(expr)});})()`); const receipt=()=>b.evaluate('document.querySelector("#agents-receipt").textContent'); - const click=sel=>b.evaluate(`(()=>{document.querySelector(${JSON.stringify(sel)}).click();return true;})()`); + const click=sel=>b.evaluate(`(()=>{const e=document.querySelector(${JSON.stringify(sel)});if(e.closest('.agent-menu')?.hidden)e.closest('.agent-menu').previousElementSibling.click();e.click();return true;})()`); // Read-only: the table, the unavailable line, every action disabled, nothing injected. - await b.navigate(`http://127.0.0.1:${port}/#/settings`); + await b.navigate(`http://127.0.0.1:${port}/#/settings/agents`); await wait('!!document.querySelector("#agents-table")'); assert.deepEqual(await b.evaluate("[...document.querySelectorAll('#agents-table tbody tr')].map(r=>[...r.querySelectorAll('th,td')].slice(0,5).map(c=>c.textContent))"),[ - ['coder','coder','yes','no','run-1 still running after fire: run-0'],[hostile,'coder','no','yes',`none still running after fire: ${hostile}`],['assistant','assistant','no','no','none'],['bean','companion','no','no','none'], + ['coder','coder','Yes','No','run-1 still running after fire: run-0'],[hostile,'coder','No','Yes',`None still running after fire: ${hostile}`],['assistant','assistant','No','No','None'],['bean','companion','No','No','None'], ]); assert.equal(await b.evaluate('window.injected===true'),false); // D7 (S6): a run a fire's stop left alive is flagged beside the running runs, as text. assert.deepEqual(await b.evaluate("[...document.querySelectorAll('#agents-table .agent-alive code')].map(c=>c.textContent)"),['run-0',hostile]); - assert.equal(await b.evaluate('document.querySelector("#agents-unavailable").textContent'),'Agent actions are unavailable here. Use mosaic business instance from the instance CLI.'); - assert.equal(await b.evaluate('[...document.querySelectorAll("#agents-section button,#agents-section input,#agents-section select")].every(e=>e.disabled)'),true); - assert.equal(await b.evaluate('document.querySelectorAll("#agents-section [data-agent-action]").length>0'),true); - // The protected assistant has no Delete; the kept instance offers Unkeep; reviewer is no-hire. - assert.equal(await b.evaluate('!!document.querySelector(\'[data-agent-action="delete"][data-agent-name="assistant"]\')'),false); - // A creative instance isn't protected (the human changes it). This listing marks bean endProtected, - // as a non-human reader's does, so the page hides its Delete; row 256's test below has the human's. - assert.equal(await b.evaluate('!!document.querySelector(\'[data-agent-action="delete"][data-agent-name="bean"]\')'),false); - assert.equal(await b.evaluate('!!document.querySelector(\'[data-agent-action="launch"][data-agent-name="bean"]\')'),true); - assert.equal(await b.evaluate(`document.querySelector('[data-agent-action="unkeep"]').dataset.agentName`),hostile); - assert.equal(await b.evaluate(`document.querySelector('[data-agent-action="hire"]').dataset.agentName`),'reviewer'); + assert.match(await b.evaluate('document.querySelector(".settings-readonly").textContent'),/Read only/); + assert.equal(await b.evaluate('document.querySelectorAll("#agents-section [data-agent-action],#agents-section .agent-more").length'),0); assert.match(await b.evaluate('document.querySelector("#agents-section").textContent'),/Retired names, never reused: old-coder\./); // Send mode: a launch posts once, shows the request and follows it to its close. - await b.navigate(`http://127.0.0.1:${port}/?send=1#/settings`); + await b.navigate(`http://127.0.0.1:${port}/?send=1#/settings/agents`); await wait(`document.querySelector('[data-agent-action="launch"][data-agent-name="coder"]')?.disabled===false`); - assert.equal(await b.evaluate('!!document.querySelector("#agents-unavailable")'),false); + assert.equal(await b.evaluate('!!document.querySelector(".settings-readonly")'),false); + assert.equal(await b.evaluate(`!!document.querySelector('[data-agent-dialog="delete"][data-agent-name="assistant"]')`),false); + assert.equal(await b.evaluate(`!!document.querySelector('[data-agent-dialog="delete"][data-agent-name="bean"]')`),false); + assert.equal(await b.evaluate(`document.querySelector('[data-agent-action="unkeep"]').dataset.agentName`),hostile); + assert.equal(await b.evaluate(`document.querySelector('[data-agent-action="hire"]').dataset.agentName`),'reviewer'); await b.evaluate(`replies.push([200,{request:'${ID}',at:'2026-10-20T00:00:00Z'}]);polls.push([200,{request:'${ID}',action:'launch',instance:'coder',state:'taken',done:null,cancelled:null}],[200,{request:'${ID}',action:'launch',instance:'coder',state:'closed',done:{run:'run-2',transaction:null,refusal:null},cancelled:null}]);true`); await click('[data-agent-action="launch"][data-agent-name="coder"]'); await wait('!!document.querySelector("#agents-pending")'); @@ -63,45 +58,46 @@ test('row 194 T16 Settings Agents: unavailable read-only, launch follows its req assert.equal(await b.evaluate('!!document.querySelector("#agents-pending")'),false); // Regenerate and delete: the first click only asks; Cancel asks nothing; the confirm posts. - await click('[data-agent-action="regenerate"][data-agent-name="coder"]'); - await wait('!!document.querySelector("[data-agent-confirmed]")'); - assert.match(await b.evaluate('document.querySelector(".agent-confirm").textContent'),/Regenerate coder\?/); - await click('[data-agent-cancel]'); - await wait('!document.querySelector("[data-agent-confirmed]")'); - await click('[data-agent-action="delete"][data-agent-name="coder"]'); - await wait('!!document.querySelector("[data-agent-confirmed]")'); - assert.match(await b.evaluate('document.querySelector(".agent-confirm").textContent'),/Its evidence and its workspace under \.retired stay\./); + await click('[data-agent-dialog="regenerate"][data-agent-name="coder"]'); + await wait('document.querySelector("#agent-dialog")?.open'); + assert.match(await b.evaluate('document.querySelector("#agent-dialog").textContent'),/Regenerate coder\?/); + await click('#agent-dialog-cancel'); + await wait('!document.querySelector("#agent-dialog").open'); + await click('[data-agent-dialog="delete"][data-agent-name="coder"]'); + await wait('document.querySelector("#agent-dialog")?.open'); + assert.match(await b.evaluate('document.querySelector("#agent-dialog").textContent'),/Its evidence and its workspace under \.retired stay\./); assert.equal(await b.evaluate('posts.length'),1,'asking posts nothing'); await b.evaluate(`replies.push([200,{request:'${ID}',at:'x'}]);polls.push([200,{request:'${ID}',action:'delete',instance:'coder',state:'closed',done:{run:null,transaction:'t-9',refusal:null},cancelled:null}]);true`); - await click('[data-agent-confirmed]'); + await click('#agent-dialog-confirm'); await wait('document.querySelector("#agents-receipt")?.textContent==="Deleted coder."'); assert.deepEqual(await b.evaluate('posts.at(-1)'),['/api/instances',{revision:REV,instance:'coder',op:'delete'}]); // sage-1610 (b): a delete that closes with a tracker bot names it for removal in Vikunja; a bot // name outside the pattern is not shown. for (const [bot,text] of [['bot-acme-coder','Deleted coder. Remove the Vikunja bot user bot-acme-coder and any token it holds by hand in Vikunja.'],[hostile,'Deleted coder.']]) { await b.evaluate(`replies.push([200,{request:'${ID}',at:'x'}]);polls.push([200,{request:'${ID}',action:'delete',instance:'coder',state:'closed',done:{run:null,transaction:'t-9',refusal:null,bot:${JSON.stringify(bot)}},cancelled:null}]);true`); - await click('[data-agent-action="delete"][data-agent-name="coder"]'); - await wait('!!document.querySelector("[data-agent-confirmed]")'); - await click('[data-agent-confirmed]'); + await click('[data-agent-dialog="delete"][data-agent-name="coder"]'); + await wait('document.querySelector("#agent-dialog")?.open'); + await click('#agent-dialog-confirm'); await wait(`document.querySelector("#agents-receipt")?.textContent===${JSON.stringify(text)}`); } assert.equal(await b.evaluate('window.injected===true'),false); // Create names whether the bus must restart, in the words bus.js uses for the same answer (M63). - const typeCreate=(field,value)=>b.evaluate(`(()=>{const e=document.querySelector('[data-agent-create="${field}"]');e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('change',{bubbles:true}));return true;})()`); - for (const [restart,text] of [[true,'Created rev-2. Restart needed: the running bus keeps the roles it loaded at start. The Console does not restart it.'],[false,'Created rev-2. No restart: the launcher reads the change at its next launch check.']]) { + const typeCreate=(field,value)=>b.evaluate(`(()=>{const e=document.querySelector('#instance-add-form [data-instance-field="${field}"]');e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('change',{bubbles:true}));return true;})()`); + for (const [restart,text] of [[true,'Added rev-2. Restart needed: the running bus keeps the roles it loaded at start. The Console does not restart it.'],[false,'Added rev-2. No restart: the launcher reads the change at its next launch check.']]) { await typeCreate('instance','rev-2'); await typeCreate('definition','reviewer'); await b.evaluate(`replies.push([200,{...${JSON.stringify(view)},transaction:'t-3',restart:${restart}}]);true`); - await b.evaluate('document.querySelector("#agent-create-form").requestSubmit();true'); - await wait(`document.querySelector("#agents-receipt")?.textContent===${JSON.stringify(text)}`); + await b.evaluate('document.querySelector("#instance-add-form").requestSubmit();true'); + await wait(`document.querySelector("#instances-receipt")?.textContent===${JSON.stringify(text)}`); assert.deepEqual(await b.evaluate('posts.at(-1)'),['/api/instances',{revision:REV,instance:'rev-2',op:'add',definition:'reviewer'}]); } // Terminate carries the typed reason; a closed refusal shows its reason. - await b.evaluate(`(()=>{const e=document.querySelector('[data-agent-reason="coder"]');e.value='done for today';e.dispatchEvent(new Event('input',{bubbles:true}));return true;})()`); + await b.evaluate(`replies.push([200,{request:'${ID}',runs:['run-1'],cancelled:[],taken:[]}]);polls.push([200,{request:'${ID}',action:'end',instance:'coder',state:'closed',done:{run:null,transaction:null,refusal:'not-held'},cancelled:null,reason:'the run no longer holds the instance'}]);true`); - await click('[data-agent-action="end"][data-agent-name="coder"]'); + await click('[data-agent-dialog="end"][data-agent-name="coder"]'); + await b.evaluate('document.querySelector("#agent-dialog-reason").value="done for today"'); await click('#agent-dialog-confirm'); await wait('document.querySelector("#agents-receipt")?.textContent==="coder: the run no longer holds the instance."'); assert.deepEqual(await b.evaluate('posts.at(-1)'),['/api/agent/terminate',{instance:'coder',reason:'done for today'}]); @@ -136,16 +132,16 @@ test('row 256 T7 T8 the human page offers Delete on a creative instance, the tes await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`const q=new URL(location.href).searchParams;const original=window.fetch;window.fetch=async(url,options={})=>{if(url==='/api/config')return new Response(JSON.stringify(q.has('tester')?{tester:true}:{send:true}));return original(url,options);};`}); const port=web.address().port; const wait=expr=>b.evaluate(`(async()=>{for(let n=0;n<400;n++){if(${expr})return true;await new Promise(r=>setTimeout(r,30));}throw Error('wait failed: '+${JSON.stringify(expr)});})()`); - const del=name=>`document.querySelector('[data-agent-action="delete"][data-agent-name="${name}"]')`; + const del=name=>`document.querySelector('[data-agent-dialog="delete"][data-agent-name="${name}"]')`; // T7: the human's page. - await b.navigate(`http://127.0.0.1:${port}/?human=1#/settings`); + await b.navigate(`http://127.0.0.1:${port}/?human=1#/settings/agents`); await wait(`document.querySelector('[data-agent-action="launch"][data-agent-name="bean"]')?.disabled===false`); assert.equal(await b.evaluate(`${del('bean')}?.disabled`),false); assert.equal(await b.evaluate(`!!${del('assistant')}`),false); assert.equal(await b.evaluate(`!!${del('coder')}`),true); // T8: the tester's page, on the same listing. - await b.navigate(`http://127.0.0.1:${port}/?tester=1#/settings`); + await b.navigate(`http://127.0.0.1:${port}/?tester=1#/settings/agents`); await wait(`!!document.querySelector('#tester-banner')&&!!document.querySelector('[data-agent-action="launch"][data-agent-name="bean"]')`); - assert.equal(await b.evaluate(`document.querySelectorAll('[data-agent-action="delete"]').length`),0); + assert.equal(await b.evaluate(`document.querySelectorAll('[data-agent-dialog="delete"]').length`),0); }finally{await b.close();await close(web);} }); diff --git a/packages/webui/tests/dashboard-shell-browser.test.mjs b/packages/webui/tests/dashboard-shell-browser.test.mjs index 68c197b4d..9c7d641dd 100644 --- a/packages/webui/tests/dashboard-shell-browser.test.mjs +++ b/packages/webui/tests/dashboard-shell-browser.test.mjs @@ -37,9 +37,9 @@ test('avatar menu supports keyboard navigation and local or SSO sign out', {time await b.evaluate('document.querySelector("#avatar-button").focus();document.querySelector("#avatar-button").click()'); await b.key('Escape'); assert.equal(await b.evaluate('document.querySelector("#avatar-menu").hidden'),true); await b.key('ArrowDown'); - assert.equal(await b.evaluate('document.activeElement.textContent'),'Profile settings'); + assert.equal(await b.evaluate('document.activeElement.textContent'),'Settings'); assert.equal(await b.evaluate('document.querySelector("#local-sign-out").textContent.includes("Not signed in (local dev)")'),true); - await b.key('ArrowDown'); assert.equal(await b.evaluate('document.activeElement.id'),'palette'); + assert.equal(await b.evaluate('document.querySelectorAll("#avatar-menu select").length'),0); await b.key('Escape'); assert.equal(await b.evaluate('document.activeElement.id'),'avatar-button'); assert.equal(await b.evaluate('document.querySelector("#avatar-menu").hidden'),true); await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`window.__scenario['/api/config']={sso:true,send:false}`}); diff --git a/packages/webui/tests/instances-browser.test.mjs b/packages/webui/tests/instances-browser.test.mjs index 09cbe9077..7b6f31fd3 100644 --- a/packages/webui/tests/instances-browser.test.mjs +++ b/packages/webui/tests/instances-browser.test.mjs @@ -27,20 +27,21 @@ test('row 165 Settings: role instances read, add with a restart named, change wi const receipt=()=>b.evaluate('document.querySelector("#instances-receipt").textContent'); const set=(form,field,value)=>b.evaluate(`(()=>{const e=document.querySelector('#${form} [data-instance-field="${field}"]');if(e.type==='checkbox')e.checked=${JSON.stringify(value)};else e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('change',{bubbles:true}));return true;})()`); // Read-only: the table, the accepted definitions only, the hand-edit line, every control disabled. - await b.navigate(`http://127.0.0.1:${port}/#/settings`); - await wait('!!document.querySelector("#instances-table")'); - assert.deepEqual(await b.evaluate("[...document.querySelectorAll('#instances-table tbody tr')].map(r=>[...r.querySelectorAll('th,td')].map(c=>c.textContent))"),[ - ['chief','chief-of-staff','launcher','none'],['coder','coder','yes',JSON.stringify({note:hostile})],['assistant','assistant','no','none'], + await b.navigate(`http://127.0.0.1:${port}/#/settings/agents`); + await wait('!!document.querySelector("#agents-table")'); + assert.deepEqual(await b.evaluate("[...document.querySelectorAll('#agents-table tbody tr')].map(r=>[...r.querySelectorAll('th,td')].slice(0,3).map(c=>c.textContent))"),[ + ['chief','chief-of-staff','Launcher'],['coder','coder','Yes'],['assistant','assistant','No'], ]); assert.equal(await b.evaluate('window.injected===true'),false); - assert.deepEqual(await b.evaluate("[...document.querySelectorAll('#instance-add-form [data-instance-field=definition] option')].map(o=>o.value)"),['merge-gate','security-reviewer']); - assert.deepEqual(await b.evaluate("[...document.querySelectorAll('#instance-change-form [data-instance-field=instance] option')].map(o=>o.value)"),['chief','coder'],'an assistant changes in the Assistant section'); - assert.match(await b.evaluate('document.querySelector("#instances-title").parentElement.textContent'),/Definitions that declare credentials, a hand edit: coder \(gitea\), reviewer \(gitea, vikunja\)\./); - assert.equal(await b.evaluate('[...document.querySelectorAll(".instance-form button,.instance-form input,.instance-form select,.instance-form textarea")].every(e=>e.disabled)'),true); + assert.equal(await b.evaluate('document.querySelectorAll(".agent-more,.instance-form").length'),0); // Send mode: an add posts the read's revision and the fields, and the receipt names the restart. - await b.navigate(`http://127.0.0.1:${port}/?send=1#/settings`); + await b.navigate(`http://127.0.0.1:${port}/?send=1#/settings/agents`); await wait('document.querySelector("#instance-add-form button")?.disabled===false'); + assert.deepEqual(await b.evaluate("[...document.querySelectorAll('#instance-add-form [data-instance-field=definition] option')].map(o=>o.value)"),['','merge-gate','security-reviewer']); + assert.match(await b.evaluate('document.querySelector("#agents-section").textContent'),/Definitions that declare credentials are a hand edit: coder \(gitea\), reviewer \(gitea, vikunja\)\./); + assert.equal(await b.evaluate(`!!document.querySelector('[data-agent-edit="assistant"]')`),false); + await set('instance-add-form','instance','sec-1'); await set('instance-add-form','definition','security-reviewer'); await set('instance-add-form','launch',true); @@ -53,7 +54,7 @@ test('row 165 Settings: role instances read, add with a restart named, change wi assert.equal(await b.evaluate('[...document.querySelectorAll("button")].some(e=>/restart/i.test(e.textContent))'),false,'the page offers no restart'); // A change sends the new revision and only what changed; a launch-only change needs no restart. - await set('instance-change-form','instance','coder'); + await b.evaluate(`document.querySelector('[data-agent-edit="coder"]').click()`); await wait('!!document.querySelector("#instance-change-form")'); await set('instance-change-form','launch','no'); current={...view,revision:'c'.repeat(64)}; await b.evaluate(`replies.push([200,${JSON.stringify({...current,transaction:'t-2',restart:false})}]);true`); @@ -67,6 +68,7 @@ test('row 165 Settings: role instances read, add with a restart named, change wi await wait('document.querySelector("#instances-receipt")?.textContent==="Nothing changed."'); assert.equal(await b.evaluate('posts.length'),2); await set('instance-add-form','instance','gate-1'); + await set('instance-add-form','definition','merge-gate'); await set('instance-add-form','vars','{"model":"x"}'); await b.evaluate(`replies.push([400,{error:'organization-credentials-out-of-scope',message:'organization-credentials-out-of-scope: that definition declares credentials. Nothing changed.',sent:false}]);true`); await b.evaluate('document.querySelector("#instance-add-form").requestSubmit();true'); @@ -84,16 +86,16 @@ test('row 165 Settings: role instances read, add with a restart named, change wi assert.equal(await receipt(),'Outcome unknown. Read the role instances again before trying. Draft kept.'); assert.equal(await b.evaluate('posts.length'),4); assert.equal(await b.evaluate('document.querySelector("#instance-add-form [data-instance-field=instance]").value'),'gate-1'); - assert.equal(await b.evaluate('document.querySelectorAll("#instances-table tbody tr").length'),3); + assert.equal(await b.evaluate('document.querySelectorAll("#agents-table tbody tr:not(.agent-editor)").length'),3); // An unread view is one section's warning, not the page's empty state, and offers no form. // The same URL with a hash would be a same-document navigation, so load it with another query. A // location.reload() from evaluate returned before the reload committed; the next wait then ran on the // old document and the reload killed it (row 172: "Inspected target navigated or closed" under load). current=null; - await b.navigate(`http://127.0.0.1:${port}/?send=1&read=2#/settings`); - await wait('!!document.querySelector("#instances-title")?.parentElement.querySelector(".warn")'); - assert.equal(await b.evaluate('document.querySelector("#instances-title").parentElement.querySelector(".warn").textContent'),'The role instances could not be read, so there is nothing to add or change. Read again to retry; they come from the bus host with your identity.'); - assert.equal(await b.evaluate('document.querySelectorAll("#instances-title ~ .empty, .instance-form").length'),0); + await b.navigate(`http://127.0.0.1:${port}/?send=1&read=2#/settings/agents`); + await wait('!!document.querySelector("#agents-title")?.parentElement.querySelector(".warn")'); + assert.equal(await b.evaluate('document.querySelector("#agents-title").parentElement.querySelector(".warn").textContent'),'The agents could not be read, so there is nothing to act on. Read again to retry.'); + assert.equal(await b.evaluate('document.querySelectorAll("#agents-title ~ .empty, .instance-form").length'),0); }finally{await b.close();await close(web);} }); diff --git a/packages/webui/tests/limits-browser.test.mjs b/packages/webui/tests/limits-browser.test.mjs index b232a5d8d..7f76bfe0c 100644 --- a/packages/webui/tests/limits-browser.test.mjs +++ b/packages/webui/tests/limits-browser.test.mjs @@ -28,7 +28,7 @@ test('REQ-LIMIT-3 REQ-LIMIT-4 Settings shows token limits counted, not enforced const wait=expr=>b.evaluate(`(async()=>{for(let n=0;n<200;n++){if(${expr})return true;await new Promise(r=>setTimeout(r,30));}throw Error('wait failed: '+${JSON.stringify(expr)});})()`); const cells=()=>b.evaluate("[...document.querySelectorAll('#token-limits-table tbody tr')].map(row=>[...row.querySelectorAll('th,td')].map(c=>c.textContent))"); // Read-only: every status as its words, and Reset disabled. - await b.navigate(`http://127.0.0.1:${port}/#/settings`); + await b.navigate(`http://127.0.0.1:${port}/#/settings/tokens`); await wait('!!document.querySelector("#token-limits-table")'); assert.deepEqual(await cells(),[ ['tokens / instances / coder','100',SINCE,'120 (input 10, output 20, cache write 40, cache read 50); unknown turns 2','Reset'], @@ -41,13 +41,16 @@ test('REQ-LIMIT-3 REQ-LIMIT-4 Settings shows token limits counted, not enforced assert.equal(await b.evaluate('window.injected===true'),false); // Signed-in send mode: Reset posts the revision and that one path, and nothing else. A draft // typed before the reset stays, and its save carries the revision the reset returned (row 167). - await b.navigate(`http://127.0.0.1:${port}/?send=1#/settings`); + await b.navigate(`http://127.0.0.1:${port}/?send=1#/settings/tokens`); await wait('document.querySelector("[data-limit-reset]")?.disabled===false'); + await b.evaluate('location.hash="#/settings/limits"'); await wait('!!document.querySelector("#launch-settings-form")'); await b.evaluate(`(()=>{const e=[...document.querySelectorAll('[data-setting]')].find(e=>e.dataset.setting===${JSON.stringify(JSON.stringify(['total']))});e.value='3';e.dispatchEvent(new Event('input',{bubbles:true}));return true;})()`); + await b.evaluate('location.hash="#/settings/tokens"'); await wait('document.querySelector("[data-limit-reset]")?.disabled===false'); await b.evaluate('document.querySelectorAll("[data-limit-reset]")[1].click();true'); await wait('document.querySelector("#token-limits-receipt")?.textContent.includes("Limit reset.")'); assert.deepEqual(await b.evaluate('posts'),[{revision:'a'.repeat(64),reset:[['tokens','keys','k1']]}]); // A form save sends the token limits as read, so it never drops or edits them. + await b.evaluate('location.hash="#/settings/limits"'); await wait('!!document.querySelector("#launch-settings-form")'); assert.equal(await b.evaluate(`[...document.querySelectorAll('[data-setting]')].find(e=>e.dataset.setting===${JSON.stringify(JSON.stringify(['total']))}).value`),'3'); await b.evaluate('document.querySelector("#launch-settings-form").requestSubmit();true'); await wait('posts.length===2'); @@ -58,13 +61,13 @@ test('REQ-LIMIT-3 REQ-LIMIT-4 Settings shows token limits counted, not enforced // Row 126 (#1620): a daily quota row adds one line under the table. Its own query string makes // this a full load, and the next block's /#/settings one too. answer={revision:launch.revision,limits:launch.limits,tokens:[...TOKENS,{path:['tokens','daily','jason-max'],limit:40,since:SINCE,status:'counted',check:'daily-quota',count:3,kinds:{input:1,output:1,cacheWrite:0,cacheRead:1},unknownTurns:0}]}; - await b.navigate(`http://127.0.0.1:${port}/?daily=1#/settings`); + await b.navigate(`http://127.0.0.1:${port}/?daily=1#/settings/tokens`); await wait('!!document.querySelector("#token-limits-daily")'); assert.equal(await b.evaluate('document.querySelector("#token-limits-daily").textContent'),"Daily quotas count only this stack's own use of the account, not its use anywhere else."); assert.equal(await b.evaluate('document.querySelectorAll("#token-limits-daily").length'),1); // A limits answer the server refuses shows no rows and no count. answer={revision:launch.revision,limits:launch.limits}; - await b.navigate(`http://127.0.0.1:${port}/#/settings`); + await b.navigate(`http://127.0.0.1:${port}/#/settings/tokens`); await wait('document.querySelector("#token-limits-title")?.parentElement.textContent.includes("Token limits unavailable")'); assert.equal(await b.evaluate('document.querySelectorAll("#token-limits-table").length'),0); }finally{await b.close();await close(web);} @@ -79,12 +82,14 @@ test('Row 167 with an assistant draft open, a token limit reset gives the assist await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`window.posts=[];window.fixture=${JSON.stringify(withAssistant)};const original=window.fetch;window.fetch=async(url,options={})=>{if(url==='/api/config')return new Response(JSON.stringify({send:true}));if(url==='/api/settings'&&options.method==='POST'){posts.push(JSON.parse(options.body));return new Response(JSON.stringify({...fixture,revision:'bc'[posts.length-1].repeat(64)}));}return original(url,options);};`}); const q=sel=>`document.querySelector(${JSON.stringify(sel)})`; const wait=expr=>b.evaluate(`(async()=>{for(let n=0;n<200;n++){if(${expr})return true;await new Promise(r=>setTimeout(r,30));}throw Error('wait failed: '+${JSON.stringify(expr)});})()`); - await b.navigate(`http://127.0.0.1:${web.address().port}/#/settings`); - await wait(`${q('[data-limit-reset]')}?.disabled===false&&${q('.assistant-form button[type=submit]')}?.disabled===false`); + await b.navigate(`http://127.0.0.1:${web.address().port}/#/settings/assistant`); + await wait(`${q('.assistant-form button[type=submit]')}?.disabled===false`); await b.evaluate(`(()=>{const e=${q('.assistant-form [data-assistant-field="tracker"]')};e.value='{"project":"P19"}';e.dispatchEvent(new Event('input',{bubbles:true}));return true;})()`); + await b.evaluate('location.hash="#/settings/tokens"'); await wait('document.querySelector("[data-limit-reset]")?.disabled===false'); await b.evaluate('document.querySelectorAll("[data-limit-reset]")[1].click();true'); await wait('document.querySelector("#token-limits-receipt")?.textContent.includes("Limit reset.")'); assert.deepEqual(await b.evaluate('posts'),[{revision:'a'.repeat(64),reset:[['tokens','keys','k1']]}]); + await b.evaluate('location.hash="#/settings/assistant"'); await wait('!!document.querySelector(".assistant-form")'); assert.equal(await b.evaluate(`${q('.assistant-form [data-assistant-field="tracker"]')}.value`),'{"project":"P19"}'); await b.evaluate(`${q('.assistant-form')}.requestSubmit();true`); await wait(`${q('[data-assistant-receipt]')}?.textContent.includes("Assistant settings saved")`); diff --git a/packages/webui/tests/messages.test.mjs b/packages/webui/tests/messages.test.mjs index 5101ca532..322ccbed9 100644 --- a/packages/webui/tests/messages.test.mjs +++ b/packages/webui/tests/messages.test.mjs @@ -93,7 +93,7 @@ test('Messages nav count polls on Tasks and Board and clears on a Board refusal; messagesFailure='human-required'; await wait(`!${badge} && document.querySelector('#held')?.textContent.includes('refused')`); messagesFailure=null;await wait(`${badge}?.textContent==='4'`); - for(const [path,title] of [['queue','Queue'],['business','Business demo'],['settings','Settings']]){ + for(const [path,title] of [['queue','Queue'],['business','Business demo'],['settings/about','Settings']]){ await b.evaluate(`location.hash=${JSON.stringify('#/'+path)},true`); await wait(`document.querySelector('#bus-view h1')?.textContent===${JSON.stringify(title)} && ${badge}?.textContent==='4'`); const before=localReads.length; @@ -104,5 +104,9 @@ test('Messages nav count polls on Tasks and Board and clears on a Board refusal; messagesFailure=null; await wait(`document.querySelector('#bus-view h1')?.textContent===${JSON.stringify(title)} && ${badge}?.textContent==='4'`); } + messagesFailure='human-required'; + await b.evaluate('location.hash="#/settings/appearance",true'); + await wait('document.querySelector("#settings-page-title")?.textContent==="Appearance"'); + assert.equal(await b.evaluate('!!document.querySelector("#bus-view .banner.ref")'),false); }finally{await b.close();await close(web)} }); diff --git a/packages/webui/tests/proxy-browser.test.mjs b/packages/webui/tests/proxy-browser.test.mjs index 5fa670fd6..637c5d7be 100644 --- a/packages/webui/tests/proxy-browser.test.mjs +++ b/packages/webui/tests/proxy-browser.test.mjs @@ -3,7 +3,8 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import http from 'node:http'; -import { readFileSync } from 'node:fs'; +import { readFileSync, existsSync } from 'node:fs'; +import { resolve, extname } from 'node:path'; import { browser } from './browser.mjs'; async function setup(t, readonly = false, refusal = null) { const state = { routes: [], loginStatus: 'wait', receivedKey: false, release: null, priority: 0 }; @@ -28,7 +29,9 @@ async function setup(t, readonly = false, refusal = null) { if (req.url.endsWith('/priority/set')) { state.priority = args.priority; return send({ priority: args.priority }); } } if (req.url === '/settings/model-proxy') { res.setHeader('content-type', 'text/html'); return res.end(readFileSync(new URL('../src/public/proxy.html', import.meta.url))); } - if (req.url === '/proxy.js') { res.setHeader('content-type', 'text/javascript'); return res.end(readFileSync(new URL('../src/public/proxy.js', import.meta.url))); } + if (req.url.startsWith('/api/')) return send({rows:[],unread:0,sessions:[]}); + const root=resolve(import.meta.dirname,'../src/public'), file=resolve(root,'.'+req.url.split('?')[0]); + if(file.startsWith(root+'/') && existsSync(file)) { const type={'.js':'text/javascript','.css':'text/css','.svg':'image/svg+xml','.woff2':'font/woff2'}[extname(file)] || 'application/octet-stream';res.setHeader('content-type',type);return res.end(readFileSync(file)); } res.statusCode = 404; res.end(); }); await new Promise(r => server.listen(0, '127.0.0.1', r)); @@ -53,7 +56,7 @@ test('proxy browser clears write-only key immediately, sends once and renders da assert.equal(state.receivedKey, true); state.release(); await wait('document.querySelector("#proxy-message").textContent.includes("added")'); assert.equal(state.routes.filter(r => r.endsWith('/apikey/add')).length, 1); - assert.equal(await b.evaluate('localStorage.length+sessionStorage.length'), 0); + assert.equal(await b.evaluate('JSON.stringify(localStorage).includes("p4-browser-key") || JSON.stringify(sessionStorage).includes("p4-code")'), false); assert.equal(await b.evaluate('document.body.textContent.includes("p4-browser-key")'), false); }); test('proxy browser OAuth opens safely, callback wait stays pending, status ok completes', { timeout: 60000 }, async t => { @@ -69,7 +72,7 @@ test('proxy browser OAuth opens safely, callback wait stays pending, status ok c state.loginStatus = 'ok'; await wait('document.querySelector("#proxy-login-message").textContent==="Account signed in."'); assert.equal(await b.evaluate('document.querySelector("#proxy-authorize").hasAttribute("href")'), false); - assert.equal(await b.evaluate('localStorage.length+sessionStorage.length'), 0); + assert.equal(await b.evaluate('JSON.stringify(localStorage).includes("p4-browser-key") || JSON.stringify(sessionStorage).includes("p4-code")'), false); }); test('proxy browser read-only disables account changes', { timeout: 60000 }, async t => { const { b, state } = await setup(t, true); diff --git a/packages/webui/tests/proxy-page.test.mjs b/packages/webui/tests/proxy-page.test.mjs index cd514bd9e..c2aaedb73 100644 --- a/packages/webui/tests/proxy-page.test.mjs +++ b/packages/webui/tests/proxy-page.test.mjs @@ -82,8 +82,10 @@ test('native page offers write-only key input and no panel script', async t => { assert.equal(old.headers.location, '/settings/model-proxy'); const r = await call(s, old.headers.location); assert.equal(r.status, 200); - assert.match(r.text, /type="password"/); - assert.match(r.text, /autocomplete="off"/); + const script = await call(s, '/display.js'); + assert.equal(script.status, 200); + assert.match(script.text, /type="password"/); + assert.match(script.text, /autocomplete="off"/); assert.doesNotMatch(r.text, /management\.html|iframe/); }); test('Console caller rejects every non-proxy verb', async () => { diff --git a/packages/webui/tests/routes-browser.test.mjs b/packages/webui/tests/routes-browser.test.mjs index a8cd225fe..daa9a4ed1 100644 --- a/packages/webui/tests/routes-browser.test.mjs +++ b/packages/webui/tests/routes-browser.test.mjs @@ -75,7 +75,7 @@ test('row 65 Settings: the routing table lists every instance, saves a harness, const vars=()=>JSON.parse(readFileSync(file,'utf8')).roles; // Read-only: one row per instance in the file, each with its six values, every select disabled. - await b.navigate(`http://127.0.0.1:${port}/#/settings`); + await b.navigate(`http://127.0.0.1:${port}/#/settings/routing`); await wait('!!document.querySelector("#routes-table")'); const rows=await b.evaluate("[...document.querySelectorAll('#routes-table tbody tr')].map(r=>[r.querySelector('th').textContent,...[...r.querySelectorAll('select')].map(s=>s.value)])"); assert.deepEqual(rows,Object.entries(vars()).map(([name,{vars:v}])=>[name,...KEYS.map(k=>v[k]??'')])); @@ -86,7 +86,7 @@ test('row 65 Settings: the routing table lists every instance, saves a harness, // Send mode: a harness, a model, a thinking level and a whole fallback on the coder, saved and // read back from the file. - await b.navigate(`http://127.0.0.1:${port}/?send=1#/settings`); + await b.navigate(`http://127.0.0.1:${port}/?send=1#/settings/routing`); await wait('document.querySelector("#routes-form button[type=submit]")?.disabled===false'); const before=vars().coder.vars; await set('coder','harness','claude-code'); diff --git a/packages/webui/tests/settings-form.test.mjs b/packages/webui/tests/settings-form.test.mjs index f8c4d2935..618057abe 100644 --- a/packages/webui/tests/settings-form.test.mjs +++ b/packages/webui/tests/settings-form.test.mjs @@ -9,12 +9,12 @@ test('Settings form shows every scope and held role; gated save, exact payload, const bus={inbox:async()=>[],tasks:async()=>[],agents:async()=>[],messages:async()=>({messages:[],unread:0})};const web=await startServer({port:0,board:'http://127.0.0.1:9',bus,reads:{settings:()=>({business:'acme',release:'fixture',notifier:{binding:'fixture'},launch})}}),b=await browser(); try{ await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`window.posts=[];window.enabled=new URL(location.href).searchParams.has('send');window.mode='success';window.fixture=${JSON.stringify(launch)};const original=window.fetch;window.fetch=async(url,options={})=>{if(url==='/api/config')return new Response(JSON.stringify({send:window.enabled}));if(url==='/api/settings'&&options.method==='POST'){posts.push(JSON.parse(options.body));if(mode==='unknown')throw Error('fixture lost answer');if(mode==='refused')return new Response(JSON.stringify({message:'fixture conflict',sent:false}),{status:409});return new Response(JSON.stringify({...fixture,...posts.at(-1),revision:'b'.repeat(64)}));}return original(url,options);};`}); - await b.navigate(`http://127.0.0.1:${web.address().port}/#/settings`); + await b.navigate(`http://127.0.0.1:${web.address().port}/#/settings/limits`); const wait=expr=>b.evaluate(`(async()=>{for(let n=0;n<200;n++){if(${expr})return true;await new Promise(r=>setTimeout(r,30));}throw Error('wait failed: '+${JSON.stringify(expr)});})()`); await wait('!!document.querySelector("#launch-settings-form")');assert.equal(await b.evaluate('document.querySelector("#launch-settings-form button[type=submit]").disabled'),true); // Row 65 (mos-0840): the Role models selects moved to the routing table, so this form has none. assert.equal(await b.evaluate('document.querySelectorAll("#launch-settings-form select").length'),0);assert.equal(await b.evaluate('document.querySelectorAll("#launch-settings-form input[type=number]").length'),4); - await b.navigate(`http://127.0.0.1:${web.address().port}/?send=1#/settings`);await wait('document.querySelector("#launch-settings-form button[type=submit]")?.disabled===false'); + await b.navigate(`http://127.0.0.1:${web.address().port}/?send=1#/settings/limits`);await wait('document.querySelector("#launch-settings-form button[type=submit]")?.disabled===false'); const change=async(parts,value)=>b.evaluate(`(()=>{const e=[...document.querySelectorAll('[data-setting]')].find(e=>e.dataset.setting===${JSON.stringify(JSON.stringify(parts))});e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('input',{bubbles:true}));return true;})()`); const submit=()=>b.evaluate('document.querySelector("#launch-settings-form").requestSubmit();true'); await change(['total'],'0');await change(['providers','anthropic'],'12');await submit();await wait('document.querySelector("#launch-settings-receipt")?.textContent.includes("saved")');const [payload]=await b.evaluate('posts');assert.equal(payload.limits.total,0);assert.equal(payload.limits.providers.anthropic,12);assert.equal('instances' in payload,false);assert.equal(payload.revision,launch.revision);assert.deepEqual(payload.models,launch.models); @@ -33,9 +33,9 @@ test('Q169 Assistant section: gated, changed fields only, name and stop posts, r await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`window.posts=[];window.enabled=new URL(location.href).searchParams.has('send');window.mode='success';window.fixture=${JSON.stringify(withAssistant)};const original=window.fetch;window.fetch=async(url,options={})=>{if(url==='/api/config')return new Response(JSON.stringify({send:window.enabled}));if(options.method==='POST'){const body=JSON.parse(options.body);posts.push([url,body]);if(mode==='refused')return new Response(JSON.stringify({message:'fixture conflict',sent:false}),{status:409});if(url==='/api/name')return new Response(JSON.stringify({...body,at:'2026-10-18T01:00:00.000Z'}));if(url==='/api/assistant-stop')return new Response(JSON.stringify({stopped:[{thread:'t-1',run:'a-run'},{thread:'t-2',run:'b-run'}]}));const a=body.assistants.assistant;window.saved={...fixture,revision:'b'.repeat(64),assistants:{assistant:{...fixture.assistants.assistant,...a}}};return new Response(JSON.stringify(window.saved));}if(url==='/api/settings'&&window.saved){const read=await (await original(url,options)).json();return new Response(JSON.stringify({...read,launch:window.saved}));}return original(url,options);};`}); const port=web.address().port, q=sel=>`document.querySelector(${JSON.stringify(sel)})`; const wait=expr=>b.evaluate(`(async()=>{for(let n=0;n<200;n++){if(${expr})return true;await new Promise(r=>setTimeout(r,30));}throw Error('wait failed: '+${JSON.stringify(expr)});})()`); - await b.navigate(`http://127.0.0.1:${port}/#/settings`);await wait(`!!${q('.assistant-form')}`); + await b.navigate(`http://127.0.0.1:${port}/#/settings/assistant`);await wait(`!!${q('.assistant-form')}`); assert.equal(await b.evaluate(`${q('.assistant-form button[type=submit]')}.disabled&&${q('[data-assistant-stop]')}.disabled&&${q('[data-assistant-name]')}.disabled`),true); - await b.navigate(`http://127.0.0.1:${port}/?send=1#/settings`);await wait(`${q('.assistant-form button[type=submit]')}?.disabled===false`); + await b.navigate(`http://127.0.0.1:${port}/?send=1#/settings/assistant`);await wait(`${q('.assistant-form button[type=submit]')}?.disabled===false`); assert.equal(await b.evaluate(`${q('[data-assistant-field=name]')}.value`),'piper');assert.equal(await b.evaluate(`${q('[data-assistant-field=definition]')}.value`),'assistant'); const change=async(field,value)=>b.evaluate(`(()=>{const e=${q('.assistant-form')}.querySelector('[data-assistant-field="${field}"]');e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('input',{bubbles:true}));return true;})()`); const receipt=text=>wait(`${q('[data-assistant-receipt]')}?.textContent.includes(${JSON.stringify(text)})`); @@ -61,15 +61,15 @@ test('Row 167 a refused names read gives the refused usage page; another names f await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`const query=new URL(location.href).searchParams,refuse=query.get('refuse'),fail=query.get('fail'),original=window.fetch;window.fetch=async(url,options={})=>{if(refuse&&url.startsWith('/api/bus/'+refuse))return new Response(JSON.stringify({error:'human-required',message:'fixture refusal'}),{status:403});if(fail&&url.startsWith('/api/bus/'+fail))return new Response(JSON.stringify({error:'bus-unreachable',message:'fixture failure'}),{status:503});return original(url,options);};`}); const port=web.address().port; const wait=expr=>b.evaluate(`(async()=>{for(let n=0;n<200;n++){if(${expr})return true;await new Promise(r=>setTimeout(r,30));}throw Error('wait failed: '+${JSON.stringify(expr)});})()`); - const refused=async read=>{await b.navigate(`http://127.0.0.1:${port}/?refuse=${read}#/settings`);await wait('document.querySelector("#bus-view")?.textContent.includes("Bus refused the read")');return b.evaluate('document.querySelector("#bus-view").innerHTML');}; + const refused=async read=>{await b.navigate(`http://127.0.0.1:${port}/?refuse=${read}#/settings/${read==='usage'?'tokens':'assistant'}`);await wait('document.querySelector("#bus-view")?.textContent.includes("Bus refused the read")');return b.evaluate('document.querySelector("#bus-view").innerHTML');}; const usage=await refused('usage'), names=await refused('names'); assert.match(usage,/refused: human-required<\/code>/); assert.equal(names,usage); assert.equal(names.includes('assistant-form')||names.includes('launch-settings-form'),false); - await b.navigate(`http://127.0.0.1:${port}/?fail=names#/settings`);await wait('!!document.querySelector(".assistant-form")'); + await b.navigate(`http://127.0.0.1:${port}/?fail=names#/settings/assistant`);await wait('!!document.querySelector(".assistant-form")'); assert.equal(await b.evaluate('document.querySelector(".assistant-form").textContent.includes("The current name could not be read.")'),true); assert.equal(await b.evaluate('document.querySelector("[data-assistant-field=name]").value'),''); - assert.equal(await b.evaluate('!!document.querySelector("#launch-settings-form")'),true); + assert.equal(await b.evaluate('!!document.querySelector("#launch-settings-form")'),false); }finally{await b.close();await close(web);} }); // Row 167 (#1664): one settings snapshot. Each POST answers the fixture with the next revision @@ -83,15 +83,16 @@ async function snapshotPage(){ await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`window.fixture=${JSON.stringify(withAssistant)};${oneSnapshot}`}); const q=sel=>`document.querySelector(${JSON.stringify(sel)})`; const wait=expr=>b.evaluate(`(async()=>{for(let n=0;n<200;n++){if(${expr})return true;await new Promise(r=>setTimeout(r,30));}throw Error('wait failed: '+${JSON.stringify(expr)});})()`); - await b.navigate(`http://127.0.0.1:${web.address().port}/#/settings`); - await wait(`${q('#launch-settings-form button[type=submit]')}?.disabled===false&&${q('.assistant-form button[type=submit]')}?.disabled===false`); - const total=()=>b.evaluate(`[...document.querySelectorAll('[data-setting]')].find(e=>e.dataset.setting===${JSON.stringify(JSON.stringify(['total']))}).value`); - return {web,b,q,wait,total, - setTotal:value=>b.evaluate(`(()=>{const e=[...document.querySelectorAll('[data-setting]')].find(e=>e.dataset.setting===${JSON.stringify(JSON.stringify(['total']))});e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('input',{bubbles:true}));return true;})()`), - setTracker:value=>b.evaluate(`(()=>{const e=${q('.assistant-form [data-assistant-field="tracker"]')};e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('input',{bubbles:true}));return true;})()`), - tracker:()=>b.evaluate(`${q('.assistant-form [data-assistant-field="tracker"]')}.value`), - submitLaunch:()=>b.evaluate(`${q('#launch-settings-form')}.requestSubmit();true`), - submitAssistant:()=>b.evaluate(`${q('.assistant-form')}.requestSubmit();true`), + await b.navigate(`http://127.0.0.1:${web.address().port}/#/settings/limits`); + await wait(`${q('#launch-settings-form button[type=submit]')}?.disabled===false`); + const go=async page=>{await b.evaluate(`location.hash="#/settings/${page}"`);await wait(`document.querySelector("#settings-page-title")?.textContent===${JSON.stringify(page==='limits'?'Launch limits':'Assistant')}`);}; + const total=async()=>{await go('limits');return b.evaluate(`[...document.querySelectorAll('[data-setting]')].find(e=>e.dataset.setting===${JSON.stringify(JSON.stringify(['total']))}).value`);}; + return {web,b,q,wait,total,go, + setTotal:async value=>{await go('limits');return b.evaluate(`(()=>{const e=[...document.querySelectorAll('[data-setting]')].find(e=>e.dataset.setting===${JSON.stringify(JSON.stringify(['total']))});e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('input',{bubbles:true}));return true;})()`);}, + setTracker:async value=>{await go('assistant');return b.evaluate(`(()=>{const e=${q('.assistant-form [data-assistant-field="tracker"]')};e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('input',{bubbles:true}));return true;})()`);}, + tracker:async()=>{await go('assistant');return b.evaluate(`${q('.assistant-form [data-assistant-field="tracker"]')}.value`);}, + submitLaunch:async()=>{await go('limits');return b.evaluate(`${q('#launch-settings-form')}.requestSubmit();true`);}, + submitAssistant:async()=>{await go('assistant');return b.evaluate(`${q('.assistant-form')}.requestSubmit();true`);}, }; } test('Row 167 with a limits draft open, an assistant save gives the limits submit its revision and the typed limit stays',{timeout:90000},async()=>{ @@ -118,10 +119,31 @@ test('Row 167 with an assistant draft open, a launch save gives the assistant su assert.deepEqual(await p.b.evaluate('posts[1]'),{revision:'b'.repeat(64),assistants:{assistant:{tracker:{project:'P19'}}}}); // Someone else writes, so the file is at d. The reload button clears the snapshot even with an // assistant draft open, and the draft's submit then carries d. - await p.setTracker('{"project":"P20"}');await p.b.evaluate(`window.saved={...window.saved,revision:'d'.repeat(64)};${p.q('#launch-settings-reload')}.click();true`); + await p.setTracker('{"project":"P20"}');await p.go('limits');await p.b.evaluate(`window.saved={...window.saved,revision:'d'.repeat(64)};${p.q('#launch-settings-reload')}.click();true`); await p.wait(`${p.q('#launch-settings-receipt')}?.textContent===''`); assert.equal(await p.tracker(),'{"project":"P20"}'); await p.submitAssistant();await p.wait('posts.length===3'); assert.deepEqual(await p.b.evaluate('posts[2]'),{revision:'d'.repeat(64),assistants:{assistant:{tracker:{project:'P20'}}}}); }finally{await p.b.close();await close(p.web);} }); + +test('launch settings mark invalid fields and show saving, saved and refused states', {timeout:90000}, async()=>{ + const bus={messages:async()=>({messages:[],unread:0})}; + const web=await startServer({port:0,board:'http://127.0.0.1:9',bus,reads:{settings:()=>({business:'acme',launch,notifier:{}})}}),b=await browser(); + try { + await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`window.posts=[];const original=fetch;window.fetch=async(url,options={})=>{if(url==='/api/config')return new Response(JSON.stringify({send:true}));if(url==='/api/settings'&&options.method==='POST'){posts.push(JSON.parse(options.body));return new Promise(resolve=>window.answer=(status,body)=>resolve(new Response(JSON.stringify(body),{status})));}return original(url,options);};`}); + const wait=expr=>b.evaluate(`(async()=>{for(let n=0;n<200;n++){if(${expr})return true;await new Promise(r=>setTimeout(r,30));}throw Error('wait failed: '+${JSON.stringify(expr)});})()`); + await b.navigate(`http://127.0.0.1:${web.address().port}/#/settings/limits`);await wait('!!document.querySelector("#launch-settings-form")'); + const set=value=>b.evaluate(`(()=>{const e=document.querySelector('#launch-settings-form input[type=number]');e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('input',{bubbles:true}));document.querySelector('#launch-settings-form').requestSubmit()})()`); + await set('-1');await wait('document.querySelector("[aria-invalid=true]")'); + assert.equal(await b.evaluate('posts.length'),0); + assert.match(await b.evaluate('document.querySelector("#launch-settings-receipt").textContent'),/whole numbers/); + await set('2');await wait('document.querySelector("#launch-settings-form button[type=submit]")?.textContent.includes("Saving")'); + assert.equal(await b.evaluate('[...document.querySelectorAll("#launch-settings-form input")].every(e=>e.disabled)'),true); + await b.evaluate(`answer(200,${JSON.stringify({...launch,revision:'b'.repeat(64)})})`);await wait('document.querySelector("#launch-settings-receipt")?.textContent.includes("saved")'); + assert.equal(await b.evaluate('document.querySelector("#launch-settings-receipt").classList.contains("settings-success")'),true); + await set('3');await wait('posts.length===2');await b.evaluate(`answer(409,{message:'fixture conflict',sent:false})`);await wait('document.querySelector("#launch-settings-receipt")?.textContent.includes("Draft kept")'); + assert.equal(await b.evaluate('document.querySelector("#launch-settings-receipt").classList.contains("err")'),true); + assert.equal(await b.evaluate('document.querySelector("#launch-settings-form input[type=number]").value'),'3'); + } finally {await b.close();await close(web);} +}); diff --git a/packages/webui/tests/settings-redesign-browser.test.mjs b/packages/webui/tests/settings-redesign-browser.test.mjs new file mode 100644 index 000000000..6d14d5c02 --- /dev/null +++ b/packages/webui/tests/settings-redesign-browser.test.mjs @@ -0,0 +1,106 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { w15Fixture } from './w15-fixture.mjs'; + +test('Settings opens browser appearance and its section menu', {timeout:90000}, async t => { + const {f,b,wait}=await w15Fixture(t); + await b.navigate(f.base+'/#/settings'); + await wait('!!document.querySelector("#settings-nav")'); + assert.equal(await b.evaluate('document.querySelector("#settings-page-title").textContent'), 'Appearance'); + assert.equal(await b.evaluate('document.querySelectorAll("input[name=palette]").length'), 10); + assert.equal(await b.evaluate('document.querySelector("#avatar-menu a").textContent'), 'Settings'); +}); + +test('browser choices persist, disclosure works, and controls fit at phone width', {timeout:90000}, async t => { + const {f,b,wait}=await w15Fixture(t); + await b.viewport(390,900); await b.navigate(f.base+'/#/settings'); + await wait('!!document.querySelector(".palette-tile")'); + assert.equal(await b.evaluate('document.querySelector("#settings-disclosure").getAttribute("aria-expanded")'), 'false'); + await b.evaluate('document.querySelector("#settings-disclosure").click()'); + assert.equal(await b.evaluate('document.querySelector("#settings-disclosure").getAttribute("aria-expanded")'), 'true'); + await b.key('Escape'); + assert.equal(await b.evaluate('document.activeElement.id'), 'settings-disclosure'); + await b.evaluate('document.querySelector("[name=palette][value=grove]").click();document.querySelector("[name=density][value=compact]").click()'); + assert.equal(await b.evaluate('document.documentElement.dataset.palette'), 'grove'); + assert.equal(await b.evaluate('document.documentElement.dataset.sidebarDensity'), 'compact'); + assert.equal(await b.evaluate('document.documentElement.scrollWidth<=innerWidth'), true); + assert.equal(await b.evaluate('[...document.querySelectorAll(".palette-content,.settings-segments span,#settings-disclosure")].every(e=>e.getBoundingClientRect().height>=44&&e.getBoundingClientRect().width>=44)'),true); + await b.call('Page.reload'); await wait('document.querySelector("[name=palette][value=grove]")?.checked'); + assert.equal(await b.evaluate('document.querySelector("[name=density][value=compact]").checked'),true); + await b.evaluate('location.hash="#/tasks"'); await wait('location.hash==="#/tasks"'); + assert.equal(await b.evaluate('!!document.querySelector("dialog[open]")'),false); +}); + +test('server sections render and a routing draft can be discarded at phone width', {timeout:90000}, async t => { + const revision='a'.repeat(64); + const routes={revision,harnesses:['claude-code'],models:['opus'],levels:{'claude-code':['high','xhigh']},instances:{chief:{harness:'claude-code',model:'opus',thinking:'high'}}}; + const launch={revision,models:{opus:{provider:'p',model:'m'}},limits:{},usage:{},assistants:{}}; + const instances={revision,launch:true,instances:{chief:{definition:'chief',launcher:true,launched:false,kept:false,running:[]}},definitions:{chief:{accepted:true,services:[]}},noHire:[],retired:[]}; + const {f,b,wait}=await w15Fixture(t,{scenario:{'/api/settings':{launch,notifier:{binding:null}},'/api/bus/routes':{rows:[routes]},'/api/bus/instances':{rows:[instances]},'/api/bus/names':{rows:[]},'/api/bus/limits':{rows:[]},'/api/bus/usage':{rows:[]}}}); + await b.viewport(390,900); + for(const [path,title] of [['limits','Launch limits'],['routing','Routing'],['agents','Agents'],['assistant','Assistant'],['tokens','Token use'],['model-proxy','Model proxy'],['about','About']]) { + await b.navigate(f.base+'/#/settings/'+path); await wait(`document.querySelector('#settings-page-title')?.textContent===${JSON.stringify(title)}`); + assert.equal(await b.evaluate('document.documentElement.scrollWidth<=innerWidth'),true,path); + const undersized=await b.evaluate(`[...document.querySelectorAll('.settings-content button,.settings-content select,.settings-content input:not([type=checkbox]):not([type=radio]):not([type=hidden]),.settings-content summary')].filter(e=>e.getClientRects().length).filter(e=>{const r=e.getBoundingClientRect();return r.width<44||r.height<44}).map(e=>e.outerHTML.slice(0,150))`); + assert.deepEqual(undersized,[],path+' control targets'); + } + await b.navigate(f.base+'/#/settings/routing'); await wait('!!document.querySelector("#routes-table select")'); + await b.evaluate(`(()=>{const e=[...document.querySelectorAll('[data-route]')].find(e=>JSON.parse(e.dataset.route)[1]==='thinking');e.value='xhigh';e.dispatchEvent(new Event('change',{bubbles:true}));})()`); + assert.equal(await b.evaluate('!!document.querySelector("#settings-nav .settings-dot")'),true); + assert.equal(await b.evaluate('getComputedStyle(document.querySelector(".settings-actions")).position'),'fixed'); + await b.evaluate('document.querySelector("#routes-reload").click()'); + await wait('!!document.querySelector("#routes-table select") && !document.querySelector("#settings-nav .settings-dot")'); + assert.equal(await b.evaluate(`[...document.querySelectorAll('[data-route]')].find(e=>JSON.parse(e.dataset.route)[1]==='thinking').value`),'high'); + assert.deepEqual(await b.evaluate('window.__writes'),[]); +}); + +test('agent More menu and confirmation dialogs support keyboard and pointer without posting on cancel', {timeout:90000}, async t => { + const revision='a'.repeat(64), instances={revision,launch:true,instances:{pm:{definition:'coder',launched:true,kept:false,running:[],protected:false,endProtected:false}},definitions:{coder:{accepted:true,services:[]}},noHire:[],retired:[]}; + const {f,b,wait}=await w15Fixture(t,{scenario:{'/api/settings':{notifier:{}},'/api/bus/instances':{rows:[instances]}}}); + await b.viewport(1440,1000); await b.navigate(f.base+'/#/settings/agents'); await wait('!!document.querySelector(".agent-more")'); + await b.evaluate('document.querySelector(".agent-more").focus()'); await b.key('ArrowDown'); + assert.equal(await b.evaluate('document.querySelector(".agent-more").getAttribute("aria-expanded")'),'true'); + assert.equal(await b.evaluate('document.activeElement.textContent'),'Edit'); + assert.equal(await b.evaluate(`(()=>{const m=document.querySelector('.agent-menu'), last=m.querySelector('[data-agent-dialog=delete]'), r=last.getBoundingClientRect();return document.elementFromPoint(r.left+r.width/2,r.top+r.height/2)===last})()`),true,'the full menu is visible and clickable outside the table'); + await b.key('ArrowDown'); assert.equal(await b.evaluate('document.activeElement.textContent'),'Terminate…'); + await b.key('Enter'); assert.equal(await b.evaluate('document.querySelector("#agent-dialog").open'),true); + assert.equal(await b.evaluate('document.activeElement.id'),'agent-dialog-reason'); + await b.key('Escape'); assert.equal(await b.evaluate('document.activeElement.className'),'agent-more'); + await b.evaluate('document.querySelector(".agent-more").click();document.querySelector("[data-agent-dialog=delete]").click()'); + assert.equal(await b.evaluate('document.activeElement.id'),'agent-dialog-cancel'); + assert.match(await b.evaluate('document.querySelector("#agent-dialog-copy").textContent'),/evidence.*workspace/); + await b.evaluate('document.querySelector("#agent-dialog-cancel").click()'); + assert.deepEqual(await b.evaluate('window.__writes'),[]); +}); + +test('dev-owner send enables proxy controls after a delayed config read', {timeout:90000}, async t => { + const {f,b,wait}=await w15Fixture(t,{scenario:{'/api/proxy/accounts':{accounts:[]},'/api/proxy/keys':{keys:[]}}}); + await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`(()=>{const original=fetch;window.fetch=async(u,o)=>{if(u==='/api/config'){await new Promise(r=>setTimeout(r,300));return new Response(JSON.stringify({devOwner:true,send:true,decide:true,edit:true,sso:true}));}return original(u,o)}})()`}); + await b.navigate(f.base+'/#/settings/model-proxy'); + await wait('document.querySelector("#proxy-login-start [data-write]")?.disabled===false'); + assert.equal(await b.evaluate('!!document.querySelector(".settings-readonly")'),false); + assert.equal(await b.evaluate('document.querySelector("#proxy-apikey [data-write]").disabled'),false); +}); + +test('hiring switches lead names and launch settings inputs align in columns', {timeout:90000}, async t => { + const revision='a'.repeat(64), instances={revision,launch:true,instances:{coder:{definition:'coder',launched:true}},definitions:{coder:{accepted:true,services:[]},reviewer:{accepted:true,services:[]}},noHire:[],retired:[]}; + const launch={revision,models:{opus:{provider:'anthropic',model:'opus'},sonnet:{provider:'anthropic',model:'sonnet'},haiku:{provider:'anthropic',model:'haiku'}},limits:{providers:{anthropic:4},models:{anthropic:{opus:4,sonnet:4,haiku:20}}},usage:{}}; + const {f,b,wait}=await w15Fixture(t,{scenario:{'/api/settings':{launch,notifier:{}},'/api/bus/instances':{rows:[instances]}}}); + await b.viewport(1440,1000);await b.navigate(f.base+'/#/settings/agents');await wait('document.querySelectorAll(".hiring-grid [role=switch]").length===2'); + const switchesLead=await b.evaluate('[...document.querySelectorAll(".hiring-grid > div")].every(row=>row.querySelector("[role=switch]").getBoundingClientRect().right<=row.querySelector(":scope > span").getBoundingClientRect().left)'); + const formLayout=await b.evaluate(`(()=>{const f=document.querySelector('#instance-add-form'),labels=[...f.querySelectorAll('.filters>label')],boxes=labels.map(e=>e.getBoundingClientRect()),details=f.querySelector('details').getBoundingClientRect(),button=f.querySelector('button[type=submit]').getBoundingClientRect();return {separate:boxes.every((r,i)=>!i||r.left>=boxes[i-1].right),gap:button.top-details.bottom,headingOutline:getComputedStyle(document.querySelector('#settings-page-title')).outlineStyle}})()`); + assert.equal(formLayout.separate,true,JSON.stringify(formLayout));assert.ok(formLayout.gap>=12,JSON.stringify(formLayout));assert.equal(formLayout.headingOutline,'none'); + await b.evaluate('location.hash="#/settings/limits"');await wait('document.querySelectorAll("#launch-settings-form input[type=number]").length>=5'); + const positions=await b.evaluate(`(()=>{const f=document.querySelector('#launch-settings-form'), numbers=[...f.querySelectorAll('input[type=number]')], table=[...f.querySelectorAll('[data-setting]')].filter(e=>JSON.parse(e.dataset.setting)[0]==='table');const x=e=>Math.round(e.getBoundingClientRect().left);return {limits:numbers.map(x),providers:table.filter(e=>JSON.parse(e.dataset.setting)[2]==='provider').map(x),models:table.filter(e=>JSON.parse(e.dataset.setting)[2]==='model').map(x)};})()`); + for(const column of Object.values(positions)) assert.equal(new Set(column).size,1,JSON.stringify(positions)); + assert.equal(switchesLead,true); +}); + + +test('an unconfigured proxy is one empty state without forms or a false read-only note', {timeout:90000}, async t => { + const {f,b,wait}=await w15Fixture(t,{scenario:{'/api/config':{send:true,devOwner:true},'GET /api/proxy/accounts':{status:503,body:{error:'not-configured'}},'GET /api/proxy/keys':{status:503,body:{error:'not-configured'}}}}); + await b.navigate(f.base+'/#/settings/model-proxy');await wait('document.querySelector("#proxy-message")?.textContent.includes("not configured")'); + assert.equal(await b.evaluate('document.querySelector("#proxy-message").classList.contains("empty")'),true); + assert.equal(await b.evaluate('!!document.querySelector(".settings-readonly")'),false); + assert.equal(await b.evaluate('[...document.querySelectorAll(".settings-model-proxy .panel")].every(e=>e.hidden)'),true); +}); diff --git a/packages/webui/tests/tester-browser.test.mjs b/packages/webui/tests/tester-browser.test.mjs index ad13865bd..42fe13bf9 100644 --- a/packages/webui/tests/tester-browser.test.mjs +++ b/packages/webui/tests/tester-browser.test.mjs @@ -8,12 +8,12 @@ test('tester Console banner exposes only instance route and name editors and sav const s = await testerFixture(t), b = await testerBrowser(s.web); try { const wait = expr => b.evaluate(`(async()=>{for(let n=0;n<150;n++){if(${expr})return true;await new Promise(r=>setTimeout(r,30));}throw Error('wait failed: '+${JSON.stringify(expr)});})()`); - await b.navigate(`http://mosaic-tester.invalid/#/settings`); + await b.navigate(`http://mosaic-tester.invalid/#/settings/routing`); await wait('!!document.querySelector("#tester-banner") && document.querySelector("#routes-form button[type=submit]")?.disabled === false'); assert.match(await b.evaluate('document.querySelector("#tester-banner")?.textContent ?? ""'), /tester/i); assert.equal(await b.evaluate('document.querySelector("#routes-form button[type=submit]").disabled'), false); - assert.ok(await b.evaluate('!!document.querySelector("#instances-table")')); - assert.ok(await b.evaluate('!!document.querySelector(".tester-name-form")')); + assert.ok(await b.evaluate('[...document.querySelectorAll("#settings-nav a")].some(a=>a.getAttribute("href")==="#/settings/agents")')); + assert.ok(await b.evaluate('[...document.querySelectorAll("#settings-nav a")].some(a=>a.getAttribute("href")==="#/settings/names")')); assert.equal(await b.evaluate('!!document.querySelector("#launch-settings-form, .assistant-form, #token-limits-table [data-limit-reset], #send-section")'), false); const selector = JSON.stringify('[data-route=\'["coder","thinking"]\']'); await b.evaluate(`(()=>{const e=document.querySelector(${selector});e.value='low';e.dispatchEvent(new Event('change',{bubbles:true}));document.querySelector('#routes-form').requestSubmit();return true;})()`); diff --git a/packages/webui/tests/usage-browser.test.mjs b/packages/webui/tests/usage-browser.test.mjs index fac72a6f3..e40647751 100644 --- a/packages/webui/tests/usage-browser.test.mjs +++ b/packages/webui/tests/usage-browser.test.mjs @@ -14,7 +14,7 @@ test('REQ-LIMIT-4 Settings shows all token kinds and unknown turns beside every }); const b = await browser(); try { - await b.navigate(`http://127.0.0.1:${server.address().port}/#/settings`); + await b.navigate(`http://127.0.0.1:${server.address().port}/#/settings/tokens`); await b.evaluate(`(async()=>{for(let n=0;n<200;n++){if(document.querySelector('#token-usage-table'))return;await new Promise(r=>setTimeout(r,30));}throw Error('usage table missing');})()`); const rows = await b.evaluate("[...document.querySelectorAll('#token-usage-table tbody tr')].map(row=>[...row.querySelectorAll('td')].map(c=>c.textContent))"); assert.equal(rows.length, 6); diff --git a/packages/webui/tests/views.test.mjs b/packages/webui/tests/views.test.mjs index 69c35eddb..3419c7499 100644 --- a/packages/webui/tests/views.test.mjs +++ b/packages/webui/tests/views.test.mjs @@ -79,7 +79,7 @@ test('Queue, Business and Settings in their five states, with no move button', { ['#/queue', 'Queue', 'Queue', '#bus-view table.s1-queue tbody tr', ['queue-refused', 'not-configured'], () => { s.docs.queue.rows = []; }, 'The queue has no rows.'], ['#/queue/6', 'Row 6', 'Queue', '#bus-view [aria-labelledby=q-row] dl', ['queue-refused'], null, null], ['#/business', 'Business acme', 'Business', '#bus-view table.s1-roles tbody tr', ['not-configured', 'no-bus-host'], () => { s.docs.business = { ...s.docs.business, instances: [], credentials: [] }; }, 'This business has no role instances.'], - ['#/settings', 'Settings', 'Settings', '#bus-view [aria-labelledby=st-notify] dl', ['not-configured'], () => { s.docs.settings = { ...s.docs.settings, notifier: { refused: 'not-configured', message: 'no notifier config at /notify/acme/notify.json' } }; }, 'No notifier binding to show.'], + ['#/settings/about', 'Settings', 'Settings', '#bus-view .settings-about dl', ['not-configured'], () => { s.docs.settings = { ...s.docs.settings, notifier: { refused: 'not-configured', message: 'no notifier config at /notify/acme/notify.json' } }; }, 'Could not be read:'], ]) { const keep = structuredClone(s.docs); // Loading: the read is held; the skeleton names the source. @@ -119,7 +119,7 @@ test('Queue, Business and Settings in their five states, with no move button', { assert.match(await text('#bus-view .empty'), /Nothing to show\./, hash); assert.equal(await text('#fresh-bus'), `${source} not read: refused`, hash); // Settings keeps its appearance control through a refusal; it is this browser's own. - assert.equal(await count('#bus-view select[data-mirror]'), hash === '#/settings' ? 2 : 0, hash); + assert.equal(await count('#bus-view select[data-mirror]'), 0, hash); await b.key('k', 'KeyK', 2); await wait('document.querySelector("#cmdk-dialog").open'); assert.equal(await b.evaluate(`${palette}.filter(h=>h.startsWith("#/queue/")).length`), 0, `${hash}: no kept queue row in the palette after ${code}`); await closePalette(); @@ -130,7 +130,7 @@ test('Queue, Business and Settings in their five states, with no move button', { // Empty. if (emptied) { emptied(); await refresh(); - await wait(`document.querySelector("#bus-view .empty b")?.textContent===${JSON.stringify(emptyText)}`); + if(hash==='#/settings/about') await wait(`document.querySelector("#bus-view .settings-about")?.textContent.includes(${JSON.stringify(emptyText)})`); else await wait(`document.querySelector("#bus-view .empty b")?.textContent===${JSON.stringify(emptyText)}`); await flat(`${hash} empty`); Object.assign(s.docs, keep); await refresh(); await wait(`document.querySelectorAll(${JSON.stringify(rows)}).length===${n}`); @@ -167,9 +167,9 @@ test('Queue, Business and Settings in their five states, with no move button', { assert.equal(await text('#bus-view .s1-cmd code'), 'scripts/mosaic queue move 6 --op --by '); await go('#/business', 'Business acme'); assert.equal(await b.evaluate('[...document.querySelectorAll("#bus-view [aria-labelledby=bz-about] dt")].find(e=>e.textContent==="Arbiters").nextElementSibling.textContent'), 'pm (delivery)'); - for (const hash of ['#/queue', '#/queue/6', '#/business', '#/settings']) { - await go(hash, { '#/queue': 'Queue', '#/queue/6': 'Row 6', '#/business': 'Business', '#/settings': 'Settings' }[hash]); - assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#bus-view button, #bus-view form, #bus-view input")].filter(e=>!e.matches("button[data-copy], button[data-retry]")).length'), 0, `${hash}: no control but Copy and Read again`); + for (const hash of ['#/queue', '#/queue/6', '#/business', '#/settings/about']) { + await go(hash, { '#/queue': 'Queue', '#/queue/6': 'Row 6', '#/business': 'Business', '#/settings/about': 'Settings' }[hash]); + assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#bus-view button, #bus-view form, #bus-view input")].filter(e=>!e.matches("button[data-copy], button[data-retry], #settings-disclosure")).length'), 0, `${hash}: no control but Copy and Read again`); assert.equal(await b.evaluate('[...document.querySelectorAll("#bus-view button")].some(e=>/move|resolve|approve|save|edit/i.test(e.textContent))'), false, hash); } @@ -186,21 +186,21 @@ test('Queue, Business and Settings in their five states, with no move button', { // The owner's model proxy is reached from Settings, never from the Console tree. await go('#/settings', 'Settings'); assert.equal(await count('nav.tree a[href="/proxy"]'), 0); - assert.equal(await count('#bus-view section a[href="/settings/model-proxy"]'), 1); + assert.equal(await count('#settings-nav a[href="/settings/model-proxy"]'), 1); - // Settings: appearance is the one control, mirrored with the command bar and kept in this browser. - await go('#/settings', 'Settings'); - assert.equal(await text('#bus-view [aria-labelledby=st-notify] dd code'), 'jason-dm'); - assert.match(await text('#bus-view [aria-labelledby=st-about]'), /Release0\.0\.99/); - assert.match(await text('#bus-view [aria-labelledby=st-about]'), new RegExp(`Addresshttp://127\\.0\\.0\\.1:${web.address().port}/`)); - await b.evaluate('{const m=document.querySelector("#bus-view select[data-mirror=mode]");m.value="dark";m.dispatchEvent(new Event("change",{bubbles:true}))}'); + // About holds the notifier and instance facts; browser appearance saves immediately. + await go('#/settings/about', 'Settings'); + assert.equal(await text('#bus-view .settings-about dd:last-child code'), 'jason-dm'); + assert.match(await text('#bus-view .settings-about'), /Release0\.0\.99/); + assert.match(await text('#bus-view .settings-about'), new RegExp(`Addresshttp://127\\.0\\.0\\.1:${web.address().port}/`)); + await go('#/settings/appearance', 'Settings'); + await b.evaluate('document.querySelector("[name=theme][value=dark]").click()'); await wait('document.querySelector("#mode").value==="dark"'); assert.equal(await b.evaluate('JSON.parse(localStorage.getItem("mosaic-console-appearance")).mode'), 'dark'); - // The 10 s refresh redraws Settings and keeps focus on the mirror select (Darkwing D29). - await b.evaluate('document.querySelector("#bus-view select[data-mirror=mode]").focus(); document.querySelector("#bus-view h1").dataset.old = "1"'); - assert.equal(await b.evaluate('fireRefresh()'), 1, 'a refresh is due on #/settings'); + await b.evaluate('document.querySelector("[name=theme][value=dark]").focus(); document.querySelector("#bus-view h1").dataset.old = "1"'); + assert.equal(await b.evaluate('fireRefresh()'), 1, 'a refresh is due on Settings'); await wait('!document.querySelector("#bus-view h1").dataset.old && !document.querySelector("#bus-view [aria-busy]")'); - assert.equal(await b.evaluate('document.activeElement?.matches("#bus-view select[data-mirror=mode]") ?? false'), true, 'the refresh keeps focus on the mirror select'); + assert.equal(await b.evaluate('document.activeElement?.matches("[name=theme][value=dark]") ?? false'), true); assert.deepEqual(await b.evaluate('window.errors'), []); assert.deepEqual(await b.evaluate('window.requests.filter(([m])=>m!=="GET")'), []); @@ -232,8 +232,8 @@ test('seeded secrets, Discord ids and paths reach no response and no page; busin // The business file's arbiters object, as loadBusiness gives it (Darkwing 27186). assert.equal(await b.evaluate('[...document.querySelectorAll("#bus-view [aria-labelledby=bz-about] dt")].find(e=>e.textContent==="Arbiters").nextElementSibling.textContent'), 'pm (delivery), cto (technical)'); await seen(); - await go('#/settings', 'Settings'); - assert.equal(await text('#bus-view [aria-labelledby=st-notify] dd code'), 'jason-dm'); + await go('#/settings/about', 'Settings'); + assert.equal(await text('#bus-view .settings-about dd:last-child code'), 'jason-dm'); await seen(); assert.equal(await b.evaluate('document.body.innerText.includes("jason-dm.json")'), false); diff --git a/packages/webui/tests/w15-r1-regression-browser.test.mjs b/packages/webui/tests/w15-r1-regression-browser.test.mjs index af4f4bd7c..4016b2d9f 100644 --- a/packages/webui/tests/w15-r1-regression-browser.test.mjs +++ b/packages/webui/tests/w15-r1-regression-browser.test.mjs @@ -71,13 +71,10 @@ test('drawer destination retains focus and traps Tab across a real poll', { time await b.key('Tab'); assert.equal(await b.evaluate(`document.activeElement.id`), 'nav-close'); }); -test('unsupported sidebar order is disabled while density remains saveable', { timeout: 30000 }, async t => { - const { f, b, wait } = await w15Fixture(t); await b.navigate(f.base + '/#/settings/display'); await wait('!!document.querySelector("#display-form")'); - assert.equal(await b.evaluate(`document.querySelector('[name=order][value=contact-first]').matches(':disabled')`), true); - assert.match(await b.evaluate(`document.querySelector('.display-settings').textContent`), /ordering.*not available/i); - await b.evaluate(`document.querySelector('[name=order][value=contact-first]').click();document.querySelector('#display-form').requestSubmit()`); - assert.doesNotMatch(await b.evaluate(`document.querySelector('#display-status').textContent`), /saved/i); - await b.evaluate(`document.querySelector('[name=density][value=compact]').click();document.querySelector('#display-form').requestSubmit()`); - assert.match(await b.evaluate(`document.querySelector('#display-status').textContent`), /saved/i); +test('unsupported sidebar order is hidden while density saves on change', { timeout: 30000 }, async t => { + const { f, b, wait } = await w15Fixture(t); await b.navigate(f.base + '/#/settings/display'); await wait('!!document.querySelector("[name=density]")'); + assert.equal(await b.evaluate(`document.querySelectorAll('[name=order]').length`), 0); + await b.evaluate(`document.querySelector('[name=density][value=compact]').click()`); + assert.match(await b.evaluate(`document.querySelector('[data-status=density]').textContent`), /saved/i); assert.equal(await b.evaluate(`document.documentElement.dataset.sidebarDensity`), 'compact'); }); diff --git a/packages/webui/tests/w15-shell-browser.test.mjs b/packages/webui/tests/w15-shell-browser.test.mjs index 43da52726..42cad8c00 100644 --- a/packages/webui/tests/w15-shell-browser.test.mjs +++ b/packages/webui/tests/w15-shell-browser.test.mjs @@ -50,26 +50,15 @@ test('shell fixture: project navigation and narrow drawer', { timeout: 90000 }, test('display module on the real fixture server: save, failure and destination', {timeout:90000}, async t => { const { f,b,wait } = await w15Fixture(t); - await b.viewport(390,1000); await b.navigate(f.base+'/#/settings/display'); - await wait('!!document.querySelector("#display-form")'); - await b.evaluate('document.querySelector("[name=density][value=compact]").click()'); - await b.evaluate('location.hash="#/tasks"'); - await wait('document.querySelector(".display-dialog").open'); - await b.evaluate('document.querySelector("[data-choice=save]").click()'); - await wait('location.hash==="#/tasks"'); - assert.match(await b.evaluate('document.querySelector("#display-announcement").textContent'), /Sidebar display saved/); - assert.equal(await b.evaluate('JSON.parse(localStorage.getItem("mosaic-sidebar-display-v1")).density'), 'compact'); - await b.navigate(f.base+'/#/settings/display'); - await wait('!!document.querySelector("#display-form")'); - assert.equal(await b.evaluate('document.querySelector("[name=density]:checked").value'), 'compact'); - await b.evaluate('document.querySelector("[name=density][value=comfortable]").click();Storage.prototype.setItem=function(){throw new Error("blocked")};location.hash="#/inbox"'); - await wait('document.querySelector(".display-dialog").open'); - await b.evaluate('document.querySelector("[data-choice=save]").click()'); - assert.match(await b.evaluate('document.querySelector("#display-leave-status").textContent'), /local browser storage/); - assert.equal(await b.evaluate('location.hash'), '#/settings/display'); - await b.evaluate('document.querySelector("[data-choice=discard]").click()'); - await wait('location.hash==="#/inbox"'); - assert.deepEqual(await b.evaluate('window.__writes'), []); + await b.viewport(390,1000); await b.navigate(f.base+'/#/settings/display'); await wait('!!document.querySelector("[name=density]")'); + await b.evaluate('document.querySelector("[name=density][value=compact]").click(); location.hash="#/tasks"'); await wait('location.hash==="#/tasks"'); + assert.equal(await b.evaluate('JSON.parse(localStorage.getItem("mosaic-sidebar-display-v1")).density'),'compact'); + await b.navigate(f.base+'/#/settings/display'); await wait('!!document.querySelector("[name=density]")'); + assert.equal(await b.evaluate('document.querySelector("[name=density]:checked").value'),'compact'); + await b.evaluate('Storage.prototype.setItem=function(){throw new Error("blocked")};document.querySelector("[name=density][value=comfortable]").click()'); + assert.match(await b.evaluate('document.querySelector("[data-status=density]").textContent'),/Could not save/); + await b.evaluate('location.hash="#/inbox"'); await wait('location.hash==="#/inbox"'); + assert.equal(await b.evaluate('!!document.querySelector("dialog[open]")'),false); assert.deepEqual(await b.evaluate('window.__writes'), []); }); test('canonical routes survive reload and history without writes', { timeout: 90000 }, async t => { @@ -131,39 +120,28 @@ test('display screenshots and zoom, dark mode, hostile labels', { timeout: 90000 const hostile = ' ' + 'Long project '.repeat(35) + '\u202eevil'; const { f,b,wait,capture } = await w15Fixture(t, {scenario:{'/api/chat/projects':{rows:[{id:ids.project,name:hostile,repo:ids.repository}]}}}); for (const width of [1440,390]) { - await b.viewport(width,1000); await b.navigate(f.base+'/#/settings/display'); - await wait('!!document.querySelector("#display-form")'); - assert.ok(await b.evaluate('document.querySelector("#display-form button[type=submit]").getBoundingClientRect().height >= 44')); - await b.evaluate('document.documentElement.style.zoom="";document.documentElement.removeAttribute("data-mode")'); - await b.evaluate('document.querySelector(`[name=density][value=${document.querySelector("[name=density]:checked").value === "compact" ? "comfortable" : "compact"}]`).click();document.querySelector("#display-form").requestSubmit()'); - await wait('document.querySelector("#display-status").textContent.includes("saved")'); - captures.push(await capture('display-saved',width,'#/settings/display')); - await b.evaluate('document.querySelector(`[name=density][value=${document.querySelector("[name=density]:checked").value === "compact" ? "comfortable" : "compact"}]`).click();location.hash="#/projects"'); - await wait('document.querySelector(".display-dialog").open'); - assert.equal(await b.evaluate('document.querySelector("#display-leave-status").textContent'), ''); - captures.push(await capture('display-unsaved',width,'#/settings/display')); - await b.evaluate('window.__setItem=Storage.prototype.setItem;Storage.prototype.setItem=function(){throw new Error("blocked")};document.querySelector("[data-choice=save]").click()'); - await wait('document.querySelector("#display-leave-status").textContent.includes("local browser storage")'); - captures.push(await capture('display-save-failed',width,'#/settings/display')); - await b.evaluate('Storage.prototype.setItem=window.__setItem;document.querySelector("[data-choice=discard]").click()'); - await wait('location.hash==="#/projects" && !!document.querySelector(".chat-projects")'); + await b.viewport(width,1000); await b.navigate(f.base+'/#/settings/appearance'); await wait('!!document.querySelector("[name=density]")'); + assert.ok(await b.evaluate('document.querySelector(".settings-segments span").getBoundingClientRect().height >= 44')); + await b.evaluate('document.querySelector(`[name=density][value=${document.querySelector("[name=density]:checked").value === "compact" ? "comfortable" : "compact"}]`).click()'); + await wait('document.querySelector("[data-status=density]").textContent.includes("Saved")'); captures.push(await capture('display-saved',width,'#/settings/appearance')); + await b.evaluate('window.__setItem=Storage.prototype.setItem;Storage.prototype.setItem=function(){throw new Error("blocked")};document.querySelector(`[name=density][value=${document.querySelector("[name=density]:checked").value === "compact" ? "comfortable" : "compact"}]`).click()'); + assert.match(await b.evaluate('document.querySelector("[data-status=density]").textContent'),/Could not save/); captures.push(await capture('display-save-failed',width,'#/settings/appearance')); + await b.evaluate('Storage.prototype.setItem=window.__setItem;location.hash="#/projects"'); await wait('!!document.querySelector(".chat-projects")'); assert.equal(await b.evaluate('!!document.querySelector(".chat-projects img")'),false); await b.evaluate('document.documentElement.dataset.mode="dark"; document.documentElement.style.zoom="2"'); assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'),true); - assert.equal(await b.evaluate('getComputedStyle(document.documentElement).colorScheme'), 'dark'); + assert.equal(await b.evaluate('getComputedStyle(document.documentElement).colorScheme'),'dark'); } }); test('optional project tree mount, storage refusal and sign-out clear transient choices', {timeout:90000}, async t => { const { f,b,wait } = await w15Fixture(t); await b.call('Page.addScriptToEvaluateOnNewDocument', {source:`window.MosaicProjectTree={mount({container,path}){container.textContent='Stub tree: '+path}};`}); - await b.navigate(f.base+'/#/settings/display'); - await wait('!!document.querySelector("#display-form")'); - assert.match(await b.evaluate('document.querySelector("#project-tree").textContent'), /Stub tree: \/settings\/display/); + await b.navigate(f.base+'/#/settings/appearance'); await wait('!!document.querySelector("[name=density]")'); + assert.match(await b.evaluate('document.querySelector("#project-tree").textContent'), /Stub tree: \/settings\/appearance/); await b.evaluate('document.querySelector("[name=density][value=compact]").click(); document.dispatchEvent(new Event("mosaic-signed-out")); location.hash="#/projects"'); - await wait('location.hash==="#/projects"'); - assert.equal(await b.evaluate('document.querySelector(".display-dialog").open'), false); - assert.equal(await b.evaluate('localStorage.getItem("mosaic-sidebar-display-v1")'), null); + await wait('location.hash==="#/projects"'); assert.equal(await b.evaluate('!!document.querySelector("dialog[open]")'), false); + assert.equal(await b.evaluate('JSON.parse(localStorage.getItem("mosaic-sidebar-display-v1")).density'), 'compact'); assert.deepEqual(await b.evaluate('window.__writes'), []); }); -- 2.54.0 From 65df511f3822ed5672151e5a49738ce040dfee25 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Fri, 6 Nov 2026 15:25:14 -0600 Subject: [PATCH 009/116] fix(webui): settings review fixes (ui slice 2) --- packages/webui/src/public/agents.js | 17 +++-- packages/webui/src/public/bus.js | 76 +++++++++++-------- packages/webui/src/public/display.js | 57 +++++++------- packages/webui/src/public/proxy.html | 2 +- packages/webui/src/public/shell.css | 21 +++++ packages/webui/tests/agents-browser.test.mjs | 4 +- .../webui/tests/instances-browser.test.mjs | 2 +- .../tests/settings-redesign-browser.test.mjs | 2 +- .../tests/settings-review-browser.test.mjs | 44 +++++++++++ 9 files changed, 152 insertions(+), 73 deletions(-) create mode 100644 packages/webui/tests/settings-review-browser.test.mjs diff --git a/packages/webui/src/public/agents.js b/packages/webui/src/public/agents.js index d3108c2fb..3e919298f 100644 --- a/packages/webui/src/public/agents.js +++ b/packages/webui/src/public/agents.js @@ -19,7 +19,7 @@ const reasons = {}; const usable = () => !!ctx && (ctx.canSend || ctx.isTester) && !ctx.out(); const human = () => !!ctx && ctx.canSend && !ctx.isTester; - const redraw = () => { if (ctx && !ctx.out()) ctx.render(); }; + const redraw = () => { if (ctx && !ctx.out()) return ctx.render(); }; const reread = () => { if (ctx && !ctx.out()) ctx.refresh(); }; let editing = null; @@ -27,22 +27,23 @@ ctx = c; view = v; const { txt, esc } = c, title = '

      Agents

      '; if (!v) return `
      ${title}

      The agents could not be read, so there is nothing to act on. Read again to retry.

      `; - const open=usable(), off=!open||busy||pending||c.instanceBusy?' disabled':'', defs=Object.keys(v.definitions||{}), accepted=defs.filter(d=>v.definitions[d]?.accepted); + const open=usable(), off=!open||busy||pending?' disabled':'', addOff=!open||busy||pending||c.instanceBusyOps.includes('add')?' disabled':'', changeOff=!open||busy||pending||c.instanceBusyOps.includes('change')?' disabled':'', defs=Object.keys(v.definitions||{}), accepted=defs.filter(d=>v.definitions[d]?.accepted); + const instanceStatus=op=>{const text=c.instanceReceipts[op]||'', current=c.instanceReceiptOp===op||(!c.instanceReceiptOp&&op==='add');return `

      ${txt(text)}

      `;}; const option=(name,selected,first)=>`${accepted.map(d=>``).join('')}`; const button=(action,name,label)=>``; const rows=Object.entries(v.instances).map(([name,e])=>{ const running=Array.isArray(e.running)?e.running:[], alive=Array.isArray(e.alive)?e.alive:[]; const menu=open?``:''; const d=c.instanceDrafts.change?.instance===name?c.instanceDrafts.change:{}; - const editor=editing===name?`
      ${v.launch?``:''}
      Vars as JSON

      Harness, model and thinking are set in Routing.

      `:''; - return `${txt(name)}${txt(e.definition)}${e.launcher?'Launcher':e.launched?'Yes':'No'}${e.kept?'Yes':'No'}${running.length?running.map(r=>`${txt(r)}`).join(' '):'None'}${alive.map(r=>` still running after fire: ${txt(r)}`).join('')}${open?button('launch',name,'Launch'):''}${menu}${editor}`; + const editor=editing===name?`
      ${v.launch?``:''}
      Vars as JSON

      Harness, model and thinking are set in Routing.

      ${instanceStatus('change')}
      `:''; + return `${txt(name)}${txt(e.definition)}${e.launcher?'Launcher':e.launched?'Yes':'No'}${e.kept?'Yes':'No'}${running.length?running.map(r=>`${txt(r)}`).join(' '):'None'}${alive.map(r=>` still running after fire: ${txt(r)}`).join('')}${open?button('launch',name,'Launch'):''}${menu}${editor}`; }).join(''); const d=c.instanceDrafts.add||{}, bound=defs.filter(n=>Array.isArray(v.definitions[n].services)&&v.definitions[n].services.length).map(n=>`${txt(n)} (${v.definitions[n].services.map(txt).join(', ')})`); - const add=!c.isTester&&open?`

      Add an agent

      ${v.launch?``:''}
      Vars as JSON

      Harness, model and thinking are set in Routing.

      ${bound.length?`

      Definitions that declare credentials are a hand edit: ${bound.join(', ')}.

      `:''}
      `:''; + const add=!c.isTester&&open?`

      Add an agent

      ${v.launch?``:''}
      Vars as JSON

      Harness, model and thinking are set in Routing.

      ${instanceStatus('add')}
      ${bound.length?`

      Definitions that declare credentials are a hand edit: ${bound.join(', ')}.

      `:''}
      `:''; const noHire=Array.isArray(v.noHire)?v.noHire:[], retired=Array.isArray(v.retired)?v.retired:[]; const hiring=!c.isTester?`

      Hiring

      Turn hiring off to stop new agents of a definition.

      ${defs.map(n=>`
      ${open?``:`${noHire.includes(n)?'Off':'On'}`}${txt(n)}
      `).join('')}
      ${retired.length?`

      Retired names, never reused: ${retired.map(txt).join(', ')}.

      `:''}
      `:''; const state=pending?`

      Request ${txt(pending.request)} to ${txt(pending.action)} ${txt(pending.instance)}: ${txt(pending.state)}.

      `:''; - return `
      ${title}${state}
      ${rows}
      AgentDefinitionLaunchKeptRunningActions

      ${txt(receipt)}

      ${txt(c.instanceReceipt)}

      ${add}${hiring}

      `; + return `
      ${title}${state}
      ${rows}
      AgentDefinitionLaunchKeptRunningActions

      ${txt(receipt)}

      ${!open||c.isTester?instanceStatus('add'):''}
      ${add}${hiring}

      `; } // One POST. `null` means the page signed out; otherwise the status and the parsed answer. @@ -132,9 +133,9 @@ if(t.id==='agent-dialog-cancel'){document.querySelector('#agent-dialog').close();dialogReturn?.focus();return;} if(t.id==='agent-dialog-confirm'){const dialog=document.querySelector('#agent-dialog');if(dialogAction==='end')reasons[dialogName]=document.querySelector('#agent-dialog-reason').value;dialog.close();act(dialogAction,dialogName);return;} if(!t.closest?.('#agents-section'))return; - if(t.dataset.agentEdit!==undefined){editing=t.dataset.agentEdit;redraw();return;} + if(t.dataset.agentEdit!==undefined){editing=t.dataset.agentEdit;closeMenu(t.closest('.agent-menu')?.previousElementSibling);redraw()?.then(()=>document.querySelector('#instance-change-form select')?.focus());return;} if(t.dataset.agentDialog){dialogAction=t.dataset.agentDialog;dialogName=t.dataset.agentName;dialogReturn=t.closest('.agent-menu').previousElementSibling;closeMenu(dialogReturn);const dialog=document.querySelector('#agent-dialog'),label={end:'Terminate',regenerate:'Regenerate',delete:'Delete'}[dialogAction];document.querySelector('#agent-dialog-title').textContent=`${label} ${dialogName}?`;document.querySelector('#agent-dialog-copy').textContent=dialogAction==='regenerate'?`Its workspace is renamed under .retired and it starts fresh.`:dialogAction==='delete'?`Its evidence and its workspace under .retired stay.`:'';document.querySelector('#agent-reason-label').hidden=dialogAction!=='end';document.querySelector('#agent-dialog-reason').value='';document.querySelector('#agent-dialog-confirm').textContent=label;dialog.showModal();(dialogAction==='end'?document.querySelector('#agent-dialog-reason'):document.querySelector('#agent-dialog-cancel')).focus();return;} - const action=t.dataset.agentAction,name=t.dataset.agentName;if(action&&name!==undefined){const menu=t.closest('.agent-menu');if(menu)closeMenu(menu.previousElementSibling);act(action,name);} + const actionButton=t.closest?.('[data-agent-action]');if(actionButton?.disabled)return;const action=actionButton?.dataset.agentAction,name=actionButton?.dataset.agentName;if(action&&name!==undefined){const menu=t.closest('.agent-menu');if(menu)closeMenu(menu.previousElementSibling);act(action,name);} }); document.addEventListener('keydown',e=>{const menu=e.target.closest?.('.agent-menu'),more=e.target.closest?.('.agent-more');if(more && ['ArrowDown','Enter',' '].includes(e.key)){e.preventDefault();openMenu(more);return;}if(menu){const trigger=menu.previousElementSibling,items=[...menu.querySelectorAll('button')];if(e.key==='Escape'){e.preventDefault();closeMenu(trigger,true);}else if(e.key==='Tab')closeMenu(trigger);else if(e.key==='ArrowDown'||e.key==='ArrowUp'){e.preventDefault();items[(items.indexOf(e.target)+(e.key==='ArrowDown'?1:-1)+items.length)%items.length]?.focus();}}}); document.addEventListener('cancel',e=>{if(e.target.id==='agent-dialog'){e.preventDefault();e.target.close();dialogReturn?.focus();}},true); diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index ff821c66f..61e27fc72 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -704,12 +704,12 @@

      Palette

      Colors for every page. Harbor is the default.

      ${Brand.palettes.map(p=>``).join('')}

      Sidebar density

      How much space each sidebar row takes.

      ${segment('Density',[['comfortable','Comfortable'],['compact','Compact']],window.MosaicDisplay.get().density)}

      `; } - let browserStatusTimer; + const browserStatusTimers = Object.create(null); function browserStatus(name, ok) { const el = document.querySelector(`[data-status="${name}"]`); if (!el) return; el.textContent = ok ? '✓ Saved in this browser.' : 'Could not save in this browser. The choice applies until you reload.'; - el.classList.toggle('warning', !ok); clearTimeout(browserStatusTimer); - if (ok) browserStatusTimer = setTimeout(()=>{if(el.isConnected)el.textContent='';},4000); + el.classList.toggle('warning', !ok); clearTimeout(browserStatusTimers[name]); + if (ok) browserStatusTimers[name] = setTimeout(()=>{if(el.isConnected)el.textContent='';},4000); } document.addEventListener('change', e => { if (!e.target.closest?.('.settings-appearance')) return; @@ -803,17 +803,19 @@ // Row 155 (#1649, Q169): each assistant instance's settings, its seat name and a stop. A save // sends only the fields that changed, with the read's revision. Drafts survive polling and // refusals as in the limits form, and nothing retries. - let assistantDrafts=Object.create(null), nameDrafts=Object.create(null), assistantBusy=false, assistantReceipts=Object.create(null); + let assistantDrafts=Object.create(null), nameDrafts=Object.create(null), assistantBusy=false, assistantReceipts=Object.create(null), assistantReceiptKinds=Object.create(null), assistantCardReceipts=Object.create(null); + const assistantFormsBusy=new Set(), assistantKey=(instance,kind)=>`${instance}:${kind}`; const asShown=(entry,field)=>field==='definition'?entry.definition??'':entry[field]==null?'':JSON.stringify(entry[field],null,2); function assistantSection(value,names){ if(!value||value.refused)return ''; const v=takeSnapshot(value);if(!v.assistants||!Object.keys(v.assistants).length)return '

      This business has no assistant instance.

      '; - const disabled=!canSend||out()||assistantBusy?' disabled':''; const named=names?Object.fromEntries(names.map(r=>[r.instance,r.name])):null; const forms=Object.entries(v.assistants).map(([instance,entry])=>{ const d=assistantDrafts[instance]||{}, val=f=>Object.hasOwn(d,f)?d[f]:asShown(entry,f), k=esc(instance); const name=Object.hasOwn(nameDrafts,instance)?nameDrafts[instance]:named?.[instance]??''; - return `

      Seat name

      The name people see for this seat.

      ${named?'':' The current name could not be read.'}

      Settings

      Harness, model and thinking are set in Routing.

      Leave empty to remove the tracker.

      ${txt(assistantReceipts[instance]||'')}

      Runs

      Stop ends the runs of your threads. The assistant starts again when you next write to it.

      `; + const busy=kind=>assistantFormsBusy.has(assistantKey(instance,kind)), disabledFor=kind=>!canSend||out()||busy(kind)?' disabled':'', disabled=disabledFor('settings'), nameDisabled=disabledFor('name'), stopDisabled=disabledFor('stop'); + const status=kind=>{const text=assistantCardReceipts[assistantKey(instance,kind)]||'', current=(assistantReceiptKinds[instance]||'settings')===kind;return `

      ${txt(text)}

      `;}; + return `

      Seat name

      The name people see for this seat.

      ${named?'':' The current name could not be read.'}
      ${status('name')}

      Settings

      Harness, model and thinking are set in Routing.

      Leave empty to remove the tracker.

      ${status('settings')}

      Runs

      Stop ends the runs of your threads. The assistant starts again when you next write to it.

      ${status('stop')}
      `; }).join(''); return `
      ${forms}
      `; } @@ -832,37 +834,38 @@ return {revision:settingsSnapshot.revision,assistants:{[instance]:patch}}; } const unknownAssistant='Outcome unknown. Read current settings before trying again. Draft kept.'; - async function assistantPost(url,payload,instance,ok){ - assistantBusy=true;assistantReceipts[instance]='';render(false); - try{const response=await fetch(url,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(response.type==='opaqueredirect'){assistantReceipts[instance]='Sign in again. Draft kept.';signOut();}else{const result=await response.json();assistantReceipts[instance]=response.ok?ok(result):result?.sent==='unknown'?unknownAssistant:`${result?.message||'Refused.'} Draft kept.`;}} - catch{assistantReceipts[instance]=unknownAssistant;}finally{assistantBusy=false;if(!out())render(false);} + async function assistantPost(url,payload,instance,ok,kind='tester'){ + if(kind==='tester')assistantBusy=true;else assistantFormsBusy.add(assistantKey(instance,kind));assistantReceiptKinds[instance]=kind;assistantReceipts[instance]='';if(kind!=='tester')assistantCardReceipts[assistantKey(instance,kind)]='';render(false); + try{const response=await fetch(url,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(response.type==='opaqueredirect'){assistantReceipts[instance]='Sign in again. Draft kept.';signOut();}else{const result=await response.json();assistantReceiptKinds[instance]=kind;assistantReceipts[instance]=response.ok?ok(result):result?.sent==='unknown'?unknownAssistant:`${result?.message||'Refused.'} Draft kept.`;}} + catch{assistantReceiptKinds[instance]=kind;assistantReceipts[instance]=unknownAssistant;}finally{if(kind==='tester')assistantBusy=false;else{assistantCardReceipts[assistantKey(instance,kind)]=assistantReceipts[instance];assistantFormsBusy.delete(assistantKey(instance,kind));}if(!out())render(false);} } const assistantForm=el=>el?.closest?.('.assistant-form'); for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=assistantForm(e.target);if(!form)return;const instance=form.dataset.instance,field=e.target.dataset.assistantField;if(field==='name')nameDrafts[instance]=e.target.value;else if(field)assistantDrafts[instance]={...Object.fromEntries(['definition','vars','tracker'].map(f=>[f,form.querySelector(`[data-assistant-field="${f}"]`).value]))};if(field){markSettingsDraft('assistant',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=form.querySelector('[data-assistant-discard]');if(discard)discard.hidden=false;}}); + document.addEventListener('keydown',e=>{if(e.key==='Enter' && e.target.matches?.('[data-assistant-field=name]')){e.preventDefault();e.target.closest('.assistant-form')?.querySelector('[data-assistant-name]')?.click();}}); document.addEventListener('submit',async e=>{ - const form=assistantForm(e.target);if(!form||e.target!==form)return;e.preventDefault();if(!canSend||out()||assistantBusy)return;const instance=form.dataset.instance;let payload; - try{payload=assistantPayload(instance,form);}catch(err){assistantReceipts[instance]=err.message;render(false);return;} - await assistantPost('/api/settings',payload,instance,result=>{if(!/^[a-f0-9]{64}$/.test(result?.revision??''))return unknownAssistant;delete assistantDrafts[instance];settingsSnapshot=result;const prior=last.get('api:settings');if(prior)last.set('api:settings',{...prior,launch:result});return 'Assistant settings saved.';}); + const form=assistantForm(e.target);if(!form||e.target!==form)return;e.preventDefault();if(!canSend||out())return;const instance=form.dataset.instance;if(assistantFormsBusy.has(assistantKey(instance,'settings')))return;let payload; + try{payload=assistantPayload(instance,form);}catch(err){assistantReceiptKinds[instance]='settings';assistantReceipts[instance]=err.message;assistantCardReceipts[assistantKey(instance,'settings')]=err.message;render(false);return;} + await assistantPost('/api/settings',payload,instance,result=>{if(!/^[a-f0-9]{64}$/.test(result?.revision??''))return unknownAssistant;delete assistantDrafts[instance];settingsSnapshot=result;const prior=last.get('api:settings');if(prior)last.set('api:settings',{...prior,launch:result});return 'Assistant settings saved.';},'settings'); }); document.addEventListener('click',async e=>{ - const form=assistantForm(e.target);if(!form||!canSend||out()||assistantBusy)return;const instance=form.dataset.instance; - if(e.target.dataset.assistantDiscard!==undefined){delete assistantDrafts[instance];delete nameDrafts[instance];delete assistantReceipts[instance];settingsSnapshot=null;last.delete('api:settings');render(true);return;} - if(e.target.dataset.assistantName!==undefined){const name=form.querySelector('[data-assistant-field="name"]').value.trim(); - await assistantPost('/api/name',{instance,name},instance,result=>{if(typeof result?.name!=='string')return unknownAssistant;delete nameDrafts[instance];const prior=last.get('names');if(prior)last.set('names',{...prior,rows:[...prior.rows.filter(r=>r.instance!==result.instance),{instance:result.instance,name:result.name,at:result.at}]});return `Seat name set to ${result.name}.`;});} - else if(e.target.dataset.assistantStop!==undefined)await assistantPost('/api/assistant-stop',{instance},instance,result=>Array.isArray(result?.stopped)?`Stopped ${plural(result.stopped.length,'run')}.`:unknownAssistant); + const form=assistantForm(e.target);if(!form||!canSend||out())return;const instance=form.dataset.instance; + if(e.target.dataset.assistantDiscard!==undefined){delete assistantDrafts[instance];delete nameDrafts[instance];delete assistantReceipts[instance];delete assistantCardReceipts[assistantKey(instance,'name')];delete assistantCardReceipts[assistantKey(instance,'settings')];settingsSnapshot=null;last.delete('api:settings');render(true);return;} + if(e.target.dataset.assistantName!==undefined){if(assistantFormsBusy.has(assistantKey(instance,'name')))return;const name=form.querySelector('[data-assistant-field="name"]').value.trim(); + await assistantPost('/api/name',{instance,name},instance,result=>{if(typeof result?.name!=='string')return unknownAssistant;delete nameDrafts[instance];const prior=last.get('names');if(prior)last.set('names',{...prior,rows:[...prior.rows.filter(r=>r.instance!==result.instance),{instance:result.instance,name:result.name,at:result.at}]});return `Seat name set to ${result.name}.`;},'name');} + else if(e.target.dataset.assistantStop!==undefined&&!assistantFormsBusy.has(assistantKey(instance,'stop')))await assistantPost('/api/assistant-stop',{instance},instance,result=>Array.isArray(result?.stopped)?`Stopped ${plural(result.stopped.length,'run')}.`:unknownAssistant,'stop'); }); // Row 165 (#1662, Q171): role instances. Add one, or change one's definition, vars and launch // membership, with the read's revision. A definition that declares credentials is named but not // offered: binding credentials stays a hand edit. When a change needs a bus restart the receipt // says so; the Console never restarts the bus. Drafts survive polling and refusals; nothing retries. - let instanceView=null, instanceDrafts={add:null,change:null}, instanceBusy=false, instanceReceipt=''; + let instanceView=null, instanceDrafts={add:null,change:null}, instanceBusyOps=new Set(), instanceReceipt='', instanceReceiptOp=null, instanceReceipts=Object.create(null); const RESTART_TEXT='Restart needed: the running bus keeps the roles it loaded at start. The Console does not restart it.'; const NO_RESTART_TEXT='No restart: the launcher reads the change at its next launch check.'; function instancesSection(view){ const title='

      Role instances

      '; if(!view)return `
      ${title}

      The role instances could not be read, so there is nothing to add or change. Read again to retry; they come from the bus host with your identity.

      `; if(!instanceDrafts.add&&!instanceDrafts.change)instanceView=view; - const v=instanceView, disabled=!(canSend || isTester)||out()||instanceBusy?' disabled':''; + const v=instanceView, disabled=!(canSend || isTester)||out()||instanceBusyOps.size?' disabled':''; const defs=Object.entries(v.definitions), accepted=defs.filter(([,d])=>d.accepted).map(([n])=>n); const bound=defs.filter(([,d])=>Array.isArray(d.services)&&d.services.length).map(([n,d])=>`${txt(n)} (${d.services.map(txt).join(', ')})`); const changeable=Object.entries(v.instances).filter(([,e])=>!e.protected).map(([n])=>n); @@ -891,16 +894,16 @@ // The answer replaces the view the next render draws, so it must have the read's whole shape. const instanceAnswer=r=>/^[a-f0-9]{64}$/.test(r?.revision??'')&&typeof r.restart==='boolean'&&[r.instances,r.definitions].every(o=>o&&typeof o==='object'&&!Array.isArray(o)); for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=e.target?.closest?.('.instance-form');if(form){instanceDrafts[form.dataset.op]=instanceFields(form);markSettingsDraft('agents',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=form.querySelector('[data-instance-discard]');if(discard)discard.hidden=false;}}); - document.addEventListener('click',e=>{if(e.target.id!=='instances-reload' && e.target.dataset?.instanceDiscard===undefined)return;instanceDrafts={add:null,change:null};instanceView=null;instanceReceipt='';last.delete('instances');render(true);}); + document.addEventListener('click',e=>{if(e.target.id!=='instances-reload' && e.target.dataset?.instanceDiscard===undefined)return;instanceDrafts={add:null,change:null};instanceView=null;instanceReceipt='';instanceReceipts=Object.create(null);instanceReceiptOp=null;last.delete('instances');render(true);}); document.addEventListener('submit',async e=>{ - const form=e.target?.closest?.('.instance-form');if(!form||e.target!==form)return;e.preventDefault();if(!(canSend || isTester)||out()||instanceBusy||!instanceView)return; - const op=form.dataset.op;instanceDrafts[op]=instanceFields(form);let payload; - try{payload=instancePayload(op,instanceDrafts[op]);}catch(err){instanceReceipt=err.message;render(false);return;} - instanceBusy=true;instanceReceipt='';render(false); + const form=e.target?.closest?.('.instance-form');if(!form||e.target!==form)return;e.preventDefault();if(!(canSend || isTester)||out()||!instanceView)return; + const op=form.dataset.op;if(instanceBusyOps.has(op))return;instanceReceiptOp=op;instanceDrafts[op]=instanceFields(form);let payload; + try{payload=instancePayload(op,instanceDrafts[op]);}catch(err){instanceReceipt=err.message;instanceReceipts[op]=instanceReceipt;render(false);return;} + instanceBusyOps.add(op);instanceReceipt='';instanceReceipts[op]='';render(false); try{const response=await fetch('/api/instances',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(response.type==='opaqueredirect'){instanceReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json(); if(response.ok&&instanceAnswer(result)){instanceDrafts[op]=null;instanceView=result;const prior=last.get('instances');if(prior)last.set('instances',{...prior,rows:[result]});instanceReceipt=`${op==='add'?'Added':'Changed'} ${payload.instance}. ${result.restart?RESTART_TEXT:NO_RESTART_TEXT}`;} else instanceReceipt=response.ok||result?.sent==='unknown'?unknownInstance:`${result?.message||'Refused.'} Draft kept.`;}} - catch{instanceReceipt=unknownInstance;}finally{instanceBusy=false;if(!out())render(false);} + catch{instanceReceipt=unknownInstance;}finally{instanceBusyOps.delete(op);instanceReceiptOp=op;instanceReceipts[op]=instanceReceipt;if(!out())render(false);} }); // Row 65 (mos-0840): the routing table. One row per instance: harness, model and thinking, and // the fallback's three. Each cell offers the switched-on harnesses, the model table's keys and the @@ -919,7 +922,7 @@ const v=routesView, disabled=!(canSend || isTester)||out()||routesBusy?' disabled':''; const cells=name=>routesDraft?.[name]??routeCells(v.instances[name]); const select=(name,key,list,current,why)=>{const offered=current===''||list.includes(current)?list:[...list,current]; - return ``;}; + return ``;}; const levelsOf=h=>Array.isArray(v.levels[h])?v.levels[h]:[]; const rows=Object.keys(v.instances).map(name=>{const c=cells(name); const harness=(key)=>select(name,key,v.harnesses,c[key],'not switched on'); @@ -958,7 +961,7 @@ }); // Row 194 (#1692, D7): the Agents section lives in agents.js (window.MosaicAgents) and draws from // the same instances read. A refresh drops that read so the next render asks the bus again. - const agentsSection=view=>{ if(view&&!instanceDrafts.add&&!instanceDrafts.change)instanceView=view; return window.MosaicAgents?window.MosaicAgents.section(view,{txt,esc,canSend,isTester,out,signOut,instanceDrafts,instanceReceipt,instanceBusy,render:()=>render(false),refresh:()=>{last.delete('instances');render(false);}}):''; }; + const agentsSection=view=>{ if(view&&!instanceDrafts.add&&!instanceDrafts.change)instanceView=view; return window.MosaicAgents?window.MosaicAgents.section(view,{txt,esc,canSend,isTester,out,signOut,instanceDrafts,instanceReceipt,instanceReceiptOp,instanceReceipts,instanceBusyOps:[...instanceBusyOps],render:()=>render(false),refresh:()=>{last.delete('instances');render(false);}}):''; }; // Tester management is deliberately separate from the human's assistant/settings forms. function testerNames(names, instances) { if (!instances || !names) return ''; @@ -982,12 +985,14 @@ }); }); const settingsPages = [['appearance','Appearance'],['limits','Launch limits'],['routing','Routing'],['agents','Agents'],['assistant','Assistant'],['tokens','Token use'],['model-proxy','Model proxy'],['about','About']]; - function markSettingsDraft(page,dirty){const link=document.querySelector(`#settings-nav a[href="#/settings/${page}"]`);if(link && dirty && !link.querySelector('.settings-dot'))link.insertAdjacentHTML('beforeend','unsaved changes');} + function markSettingsDraft(page,dirty){const link=document.querySelector(`#settings-nav a[href="#/settings/${page}"]`), dot='unsaved changes';if(link && dirty && !link.querySelector('.settings-dot'))link.insertAdjacentHTML('beforeend',dot);const button=$('settings-disclosure');if(dirty && link?.getAttribute('aria-current')==='page' && button && !button.querySelector('.settings-dot'))button.querySelector('strong').insertAdjacentHTML('beforeend',dot);} function settingsShell(page, body, helper='') { const pages=isTester ? [['appearance','Appearance'],['routing','Routing'],['agents','Agents'],['names','Seat names']] : settingsPages; const label=pages.find(([id])=>id===page)?.[1] || 'Appearance'; - const links=pages.map(([id,name],i)=>`${i===0?'
      Your browser
      ':i===1?'
      This instance
      ':''}${name}${(id==='routing'&&routesDraft)||(id==='limits'&&settingsInputs)||(id==='assistant'&&(Object.keys(assistantDrafts).length||Object.keys(nameDrafts).length))||(id==='agents'&&(instanceDrafts.add||instanceDrafts.change))?'unsaved changes':''}`).join(''); - return `${head('Settings','Your browser and this instance.')}

      ${label}

      ${helper}

      ${page!=='appearance'&&!canSend&&!isTester?'

      Read only. Saving requires signed-in send mode.

      ':''}${body}
      `; + 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(''); + return `${head('Settings','Your browser and this instance.')}

      ${label}

      ${helper}

      ${page!=='appearance'&&!canSend&&!isTester?'

      Read only. Saving requires signed-in send mode.

      ':''}${body}
      `; } async function settingsView(get, page='appearance') { if (page==='appearance') return settingsShell(page,appearance(),'These choices apply in this browser only.'); @@ -1253,19 +1258,24 @@ return { 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, - field: view.contains(a) ? a.dataset?.field : null, caret: view.contains(a) && a.tagName === 'TEXTAREA' ? [a.selectionStart, a.selectionEnd, a.scrollTop] : null, send: view.contains(a) && a.hasAttribute?.('data-send'), + 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, + fallbacks:[...view.querySelectorAll('.route-row.fallback-open [data-route]')].map(e=>e.dataset.route), + field: view.contains(a) ? a.dataset?.field : null, caret: view.contains(a) && typeof a.selectionStart === 'number' ? [a.selectionStart, a.selectionEnd, a.scrollTop] : null, send: view.contains(a) && a.hasAttribute?.('data-send'), decide: view.contains(a) ? a.dataset?.decide ?? (a.id === 'decide-status' ? 'status' : null) : null, open: [...view.querySelectorAll('details[id]')].filter(d => d.open).map(d => d.id), status: $('copy-status')?.textContent || '', }; } function restore(k) { for (const id of k.open) { const d = $(id); if (d) d.open = true; } + for (const e of $('bus-view').querySelectorAll('.route-row [data-route]')) if(k.fallbacks?.includes(e.dataset.route)) e.closest('.route-row').classList.add('fallback-open'); if ($('copy-status')) $('copy-status').textContent = k.status; const el = [...$('bus-view').querySelectorAll('a[href],[data-copy],[data-retry],[data-mirror],[data-field],[data-send]')].find(e => k.href ? e.getAttribute('href') === k.href : k.copy ? e.dataset.copy === k.copy : k.mirror ? e.dataset.mirror === k.mirror : k.field ? e.dataset.field === k.field : k.send ? e.hasAttribute('data-send') : k.retry && e.hasAttribute('data-retry')); // Row 252: the answer panel's buttons and its status line. 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]); - if (choice) choice.focus({preventScroll:true}); + 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];} } + 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)) { el.focus({ preventScroll: true }); diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index 859f2ed7b..687ab9583 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -1,4 +1,4 @@ -if (location.pathname === '/settings/model-proxy' && !location.hash) location.hash = '#/settings/model-proxy'; +if (document.documentElement.hasAttribute('data-settings-proxy-document') && !location.hash) location.hash = '#/settings/model-proxy'; /* Browser-local sidebar density. No authority or project data is stored here. */ (() => { const key='mosaic-sidebar-display-v1'; @@ -15,11 +15,14 @@ if (location.pathname === '/settings/model-proxy' && !location.hash) location.ha // No browser storage, request/body logging, key reveal, or automatic write retry. (() => { 'use strict'; - const markup = '

      Reading accounts…

      \n\n

      Accounts

      \n

      Higher priority is used first. Account names are stable identifiers; credential values are never displayed.

      \n
      AccountProviderStatusPriority
      \n

      Sign in to an account

      \n
      Subscription account
      \n

      \n

      \n
      Finish sign-in

      If the sign-in tab does not return, copy its full address and paste it here.

      \n

      Add an API key

      \n
      z.ai

      The key is sent once and cleared from this field. It will never be shown again.

      \n

      Client keys

      Only key IDs are shown. Hire and fire manage agent keys.

      \n
      Key IDManaged byAgentIssuedState
      \n'; + const markup = '

      Reading accounts…

      \n\n

      Accounts

      \n

      Higher priority is used first. Account names are stable identifiers; credential values are never displayed.

      \n
      AccountProviderStatusPriority
      \n

      Sign in to an account

      \n
      Subscription account
      \n

      \n

      \n
      Finish sign-in

      If the sign-in tab does not return, copy its full address and paste it here.

      \n

      Add an API key

      \n
      z.ai

      The key is sent once and cleared from this field. It will never be shown again.

      \n

      Client keys

      Only key IDs are shown. Hire and fire manage agent keys.

      \n
      Key IDManaged byAgentIssuedState
      \n'; function mount() { const $ = id => document.getElementById(id); - let canWrite = false, login = null, poll = null, busy = false; + let canWrite = false, login = null, poll = null; + const busy = new Set(), priorityReceipts = new Map(); const message = (text, loginOnly = false) => { $(loginOnly ? 'proxy-login-message' : 'proxy-message').textContent = text; }; + const formBusy=(form,on)=>{for(const control of form.querySelectorAll('fieldset,input,select,button')){if(on){control.dataset.wasDisabled=String(control.disabled);control.disabled=true;}else if(control.dataset.wasDisabled!==undefined){control.disabled=control.dataset.wasDisabled==='true';delete control.dataset.wasDisabled;}}const button=form.querySelector('button[type=submit]');if(button){if(on){button.dataset.label=button.textContent;button.innerHTML=' Saving…';}else if(button.dataset.label){button.textContent=button.dataset.label;delete button.dataset.label;}}}; + const receipt=(id,text,kind)=>{const el=$(id);el.textContent=text;el.className=kind==='error'?'banner err':kind==='success'?'settings-success':'';}; const cell = value => { const td = document.createElement('td'); td.textContent = value ?? '—'; return td; }; async function call(path, args) { const response = await fetch('/api/proxy/' + path, { cache: 'no-store', credentials: 'same-origin', @@ -61,13 +64,13 @@ if (location.pathname === '/settings/model-proxy' && !location.hash) location.ha const td = document.createElement('td'), form = document.createElement('form'); const input = document.createElement('input'); input.type = 'number'; input.min = '-1000'; input.max = '1000'; input.step = '1'; input.value = account.priority; input.setAttribute('aria-label', `Priority for ${account.displayName}`); input.disabled = !canWrite; - const save = document.createElement('button'); save.type = 'submit'; save.textContent = 'Set priority'; save.disabled = !canWrite; save.hidden = !canWrite; - form.append(input, save); form.addEventListener('submit', async event => { - event.preventDefault(); if (!canWrite || busy || !input.checkValidity()) return; - busy = true; save.disabled = true; - try { await call('priority/set', { accountId: account.accountId, priority: Number(input.value) }); message('Priority saved.'); await refresh(); } - catch (error) { message(error.message); } - finally { busy = false; save.disabled = !canWrite; } + const save = document.createElement('button'); save.type = 'submit'; save.className='proxy-priority-save'; save.textContent = 'Set priority'; save.disabled = !canWrite; save.hidden = !canWrite; + const receipt=document.createElement('p');receipt.setAttribute('role','status');if(priorityReceipts.has(account.accountId)){receipt.className='settings-success';receipt.textContent=priorityReceipts.get(account.accountId);}form.append(input, save, receipt); form.addEventListener('submit', async event => { + event.preventDefault(); const busyKey='priority:'+account.accountId;if (!canWrite || busy.has(busyKey) || !input.checkValidity()) return; + busy.add(busyKey);priorityReceipts.delete(account.accountId); receipt.textContent='';receipt.className='';input.disabled = true; save.disabled = true; save.innerHTML = ' Saving…'; + try { await call('priority/set', { accountId: account.accountId, priority: Number(input.value) }); message('Priority saved.');priorityReceipts.set(account.accountId,'Priority saved.');receipt.className='settings-success';receipt.textContent='Priority saved.';await refresh(); } + catch (error) { message(error.message);receipt.className='banner err';receipt.textContent=error.message; } + finally { busy.delete(busyKey); input.disabled = !canWrite; save.disabled = !canWrite; save.textContent='Set priority'; } }); td.append(form); row.append(td); return row; }); @@ -79,39 +82,39 @@ if (location.pathname === '/settings/model-proxy' && !location.hash) location.ha } $('proxy-refresh').addEventListener('click', () => refresh().then(() => message('Accounts and client keys refreshed.')).catch(e => message(e.message))); $('proxy-login-start').addEventListener('submit', async event => { - event.preventDefault(); if (!canWrite || busy || login) return; - busy = true; + event.preventDefault(); const form=event.currentTarget;if (!canWrite || busy.has('login-start') || login) return; + busy.add('login-start');formBusy(form,true); try { login = await call('login/start', { provider: event.currentTarget.elements.provider.value }); $('proxy-authorize').href = login.url; $('proxy-authorize').hidden = false; window.open(login.url, '_blank', 'noopener,noreferrer'); message('Complete account sign-in in the new tab, or use the sign-in link.', true); poll = setTimeout(status, 2000); - } catch (error) { message(error.message, true); } - finally { busy = false; } + } catch (error) { message(error.message, true);$('proxy-login-message').className='banner err'; } + finally { busy.delete('login-start');formBusy(form,false); } }); $('proxy-login-submit').addEventListener('submit', async event => { - event.preventDefault(); if (!canWrite || busy || !login) return; + event.preventDefault(); const form=event.currentTarget;if (!canWrite || busy.has('login-submit') || !login) return; const input = event.currentTarget.elements.redirect_url, redirect_url = input.value; input.value = ''; - busy = true; + busy.add('login-submit');formBusy(form,true); try { await call('login/submit', { redirect_url }); message('Address submitted. Waiting for sign-in confirmation…', true); } - catch (error) { message(error.message, true); } - finally { busy = false; } + catch (error) { message(error.message, true);$('proxy-login-message').className='banner err'; } + finally { busy.delete('login-submit');formBusy(form,false); } }); - $('proxy-login-cancel').addEventListener('click', async () => { - if (!canWrite || busy || !login) return; - busy = true; clearTimeout(poll); + $('proxy-login-cancel').addEventListener('click', async event => { + const form=event.currentTarget.form;if (!canWrite || busy.has('login-cancel') || !login) return; + busy.add('login-cancel');formBusy(form,true); clearTimeout(poll); try { await call('login/cancel', { state: login.state }); endLogin(); message('Sign-in cancelled.', true); } catch (error) { endLogin(); message(error.message, true); } - finally { busy = false; } + finally { busy.delete('login-cancel');formBusy(form,false); } }); $('proxy-apikey').addEventListener('submit', async event => { - event.preventDefault(); if (!canWrite || busy) return; + event.preventDefault(); const form=event.currentTarget;if (!canWrite || busy.has('apikey')) return; const input = event.currentTarget.elements.key, key = input.value; input.value = ''; - busy = true; - try { await call('apikey/add', { provider: 'z.ai', key }); message('API key added.'); await refresh(); } - catch (error) { message(error.message); } - finally { busy = false; } + busy.add('apikey');receipt('proxy-apikey-message','','');formBusy(form,true); + try { await call('apikey/add', { provider: 'z.ai', key }); message('API key added.');receipt('proxy-apikey-message','API key added.','success');await refresh(); } + catch (error) { message(error.message);receipt('proxy-apikey-message',error.message,'error'); } + finally { busy.delete('apikey');formBusy(form,false); } }); const cleanup = () => { clearTimeout(poll); login = null; const redirect=$('proxy-login-submit')?.elements.redirect_url, key=$('proxy-apikey')?.elements.key; if(redirect)redirect.value='';if(key)key.value=''; }; window.addEventListener('pagehide', cleanup, {once:true}); diff --git a/packages/webui/src/public/proxy.html b/packages/webui/src/public/proxy.html index 7836d65c7..fe4bd02a1 100644 --- a/packages/webui/src/public/proxy.html +++ b/packages/webui/src/public/proxy.html @@ -1,5 +1,5 @@ - + Dashboard · Mosaic Console diff --git a/packages/webui/src/public/shell.css b/packages/webui/src/public/shell.css index bd145e3c6..f47220c35 100644 --- a/packages/webui/src/public/shell.css +++ b/packages/webui/src/public/shell.css @@ -293,3 +293,24 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed} /* Agent menus must extend beyond the table without being clipped by its scroll region. */ .settings-agents .table-wrap{overflow:visible} + +/* Review fixes: preserve readable actions, labels and targets at every width. */ +.settings-content .instance-form .filters>label:not(:has(input[type=checkbox])){align-items:flex-start} +.settings-content .instance-form .filters>label:has(input[type=checkbox]){grid-column:1/-1;justify-self:start} +.settings-content .settings-actions .banner:not(:empty){order:-1;flex:1 0 100%;margin:0} +.agent-mobile-label{display:none} +#bus-view .page-head:has(+ .settings-layout) p{font-size:16px} +.settings-segments:has(input:focus-visible){outline:2px solid var(--focus);outline-offset:2px} +.settings-segments input:focus-visible+span{outline:none} +#proxy-authorize:not([hidden]){display:inline-flex;align-items:center;min-height:44px} +.settings-content #proxy-accounts .proxy-priority-save{background:var(--surface);color:var(--text);border-color:var(--border)} +@media(min-width:760px){#routes-table select{min-width:132px}} +@media(max-width:759px){ + #agents-table :is(th,td,code){min-width:0;max-width:100%;white-space:normal;overflow-wrap:anywhere;word-break:break-word} + .agent-mobile-label{display:inline;color:var(--muted)} + .settings-content .settings-actions.has-draft{max-height:45vh;overflow-y:auto;align-items:center} + .settings-content .settings-actions.has-draft p:not(:empty){display:block;order:-1;flex:1 0 100%;margin:0} + .settings-content:has(.settings-actions.has-draft){padding-bottom:50vh} +} + +.settings-success:not(:empty)::before{content:"✓ ";} diff --git a/packages/webui/tests/agents-browser.test.mjs b/packages/webui/tests/agents-browser.test.mjs index 183e1b7e6..d40c26afa 100644 --- a/packages/webui/tests/agents-browser.test.mjs +++ b/packages/webui/tests/agents-browser.test.mjs @@ -29,12 +29,12 @@ test('row 194 T16 Settings Agents: unavailable read-only, launch follows its req // Read-only: the table, the unavailable line, every action disabled, nothing injected. await b.navigate(`http://127.0.0.1:${port}/#/settings/agents`); await wait('!!document.querySelector("#agents-table")'); - assert.deepEqual(await b.evaluate("[...document.querySelectorAll('#agents-table tbody tr')].map(r=>[...r.querySelectorAll('th,td')].slice(0,5).map(c=>c.textContent))"),[ + assert.deepEqual(await b.evaluate("[...document.querySelectorAll('#agents-table tbody tr')].map(r=>[...r.querySelectorAll('th,td')].slice(0,5).map(c=>{const copy=c.cloneNode(true);copy.querySelector('.agent-mobile-label')?.remove();return copy.textContent}))"),[ ['coder','coder','Yes','No','run-1 still running after fire: run-0'],[hostile,'coder','No','Yes',`None still running after fire: ${hostile}`],['assistant','assistant','No','No','None'],['bean','companion','No','No','None'], ]); assert.equal(await b.evaluate('window.injected===true'),false); // D7 (S6): a run a fire's stop left alive is flagged beside the running runs, as text. - assert.deepEqual(await b.evaluate("[...document.querySelectorAll('#agents-table .agent-alive code')].map(c=>c.textContent)"),['run-0',hostile]); + assert.deepEqual(await b.evaluate("[...document.querySelectorAll('#agents-table .agent-alive code')].map(c=>{const copy=c.cloneNode(true);copy.querySelector('.agent-mobile-label')?.remove();return copy.textContent})"),['run-0',hostile]); assert.match(await b.evaluate('document.querySelector(".settings-readonly").textContent'),/Read only/); assert.equal(await b.evaluate('document.querySelectorAll("#agents-section [data-agent-action],#agents-section .agent-more").length'),0); assert.match(await b.evaluate('document.querySelector("#agents-section").textContent'),/Retired names, never reused: old-coder\./); diff --git a/packages/webui/tests/instances-browser.test.mjs b/packages/webui/tests/instances-browser.test.mjs index 7b6f31fd3..f786d3fbd 100644 --- a/packages/webui/tests/instances-browser.test.mjs +++ b/packages/webui/tests/instances-browser.test.mjs @@ -29,7 +29,7 @@ test('row 165 Settings: role instances read, add with a restart named, change wi // Read-only: the table, the accepted definitions only, the hand-edit line, every control disabled. await b.navigate(`http://127.0.0.1:${port}/#/settings/agents`); await wait('!!document.querySelector("#agents-table")'); - assert.deepEqual(await b.evaluate("[...document.querySelectorAll('#agents-table tbody tr')].map(r=>[...r.querySelectorAll('th,td')].slice(0,3).map(c=>c.textContent))"),[ + assert.deepEqual(await b.evaluate("[...document.querySelectorAll('#agents-table tbody tr')].map(r=>[...r.querySelectorAll('th,td')].slice(0,3).map(c=>{const copy=c.cloneNode(true);copy.querySelector('.agent-mobile-label')?.remove();return copy.textContent}))"),[ ['chief','chief-of-staff','Launcher'],['coder','coder','Yes'],['assistant','assistant','No'], ]); assert.equal(await b.evaluate('window.injected===true'),false); diff --git a/packages/webui/tests/settings-redesign-browser.test.mjs b/packages/webui/tests/settings-redesign-browser.test.mjs index 6d14d5c02..9691cd80d 100644 --- a/packages/webui/tests/settings-redesign-browser.test.mjs +++ b/packages/webui/tests/settings-redesign-browser.test.mjs @@ -88,7 +88,7 @@ test('hiring switches lead names and launch settings inputs align in columns', { const {f,b,wait}=await w15Fixture(t,{scenario:{'/api/settings':{launch,notifier:{}},'/api/bus/instances':{rows:[instances]}}}); await b.viewport(1440,1000);await b.navigate(f.base+'/#/settings/agents');await wait('document.querySelectorAll(".hiring-grid [role=switch]").length===2'); const switchesLead=await b.evaluate('[...document.querySelectorAll(".hiring-grid > div")].every(row=>row.querySelector("[role=switch]").getBoundingClientRect().right<=row.querySelector(":scope > span").getBoundingClientRect().left)'); - const formLayout=await b.evaluate(`(()=>{const f=document.querySelector('#instance-add-form'),labels=[...f.querySelectorAll('.filters>label')],boxes=labels.map(e=>e.getBoundingClientRect()),details=f.querySelector('details').getBoundingClientRect(),button=f.querySelector('button[type=submit]').getBoundingClientRect();return {separate:boxes.every((r,i)=>!i||r.left>=boxes[i-1].right),gap:button.top-details.bottom,headingOutline:getComputedStyle(document.querySelector('#settings-page-title')).outlineStyle}})()`); + const formLayout=await b.evaluate(`(()=>{const f=document.querySelector('#instance-add-form'),labels=[...f.querySelectorAll('.filters>label')],boxes=labels.map(e=>e.getBoundingClientRect()),details=f.querySelector('details').getBoundingClientRect(),button=f.querySelector('button[type=submit]').getBoundingClientRect();return {separate:boxes[1].left>=boxes[0].right&&boxes[2].top>=boxes[0].bottom,gap:button.top-details.bottom,headingOutline:getComputedStyle(document.querySelector('#settings-page-title')).outlineStyle}})()`); assert.equal(formLayout.separate,true,JSON.stringify(formLayout));assert.ok(formLayout.gap>=12,JSON.stringify(formLayout));assert.equal(formLayout.headingOutline,'none'); await b.evaluate('location.hash="#/settings/limits"');await wait('document.querySelectorAll("#launch-settings-form input[type=number]").length>=5'); const positions=await b.evaluate(`(()=>{const f=document.querySelector('#launch-settings-form'), numbers=[...f.querySelectorAll('input[type=number]')], table=[...f.querySelectorAll('[data-setting]')].filter(e=>JSON.parse(e.dataset.setting)[0]==='table');const x=e=>Math.round(e.getBoundingClientRect().left);return {limits:numbers.map(x),providers:table.filter(e=>JSON.parse(e.dataset.setting)[2]==='provider').map(x),models:table.filter(e=>JSON.parse(e.dataset.setting)[2]==='model').map(x)};})()`); diff --git a/packages/webui/tests/settings-review-browser.test.mjs b/packages/webui/tests/settings-review-browser.test.mjs new file mode 100644 index 000000000..9ecc2f11b --- /dev/null +++ b/packages/webui/tests/settings-review-browser.test.mjs @@ -0,0 +1,44 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import {readFile} from 'node:fs/promises'; +import {resolve,extname} from 'node:path'; +import {browser} from './browser.mjs'; +import {w15Fixture} from './w15-fixture.mjs'; + +const rev='a'.repeat(64), long='a'.repeat(64); +const instances={revision:rev,launch:true,instances:{pm:{definition:'coder',launched:true,kept:false,running:['run-1'],protected:false,endProtected:false},[long]:{definition:'coder',launched:true,kept:false,running:[long],protected:false,endProtected:false}},definitions:{coder:{accepted:true,services:[]}},noHire:[],retired:[]}; +const launch={revision:rev,models:{opus:{provider:'anthropic',model:'opus'}},limits:{},usage:{},assistants:{assistant:{definition:'assistant',vars:{},tracker:null}}}; +const routes={revision:rev,harnesses:['claude-code','codex'],models:['opus'],levels:{'claude-code':['high','xhigh'],codex:['high','xhigh']},instances:{pm:{harness:'claude-code',model:'opus',thinking:'high'}}}; +const scenario={'/api/config':{devOwner:true,send:true,decide:true,edit:true},'/api/settings':{launch,notifier:{binding:null}},'/api/bus/instances':{rows:[instances]},'/api/bus/routes':{rows:[routes]},'/api/bus/names':{rows:[{instance:'assistant',name:'Piper'}]},'/api/bus/limits':{rows:[]},'/api/bus/usage':{rows:[]},'/api/proxy/accounts':{accounts:[{accountId:'fixture',displayName:'Fixture',provider:'claude',status:'ready',priority:100}]},'/api/proxy/keys':{keys:[]}}; +async function page(t,section,width=1440,options={}) { + const x=await w15Fixture(t,{scenario}); const {b,f,wait}=x; + if(options.poll)await b.call('Page.addScriptToEvaluateOnNewDocument',{source:`(()=>{const original=setTimeout;window.setTimeout=(fn,ms,...args)=>{if(ms===10000)window.__pollRefresh=fn;return original(fn,ms,...args)}})()`}); + await b.viewport(width,width===390?900:1000);await b.navigate(f.base+'/#/settings/'+section); + await wait(`document.querySelector('#settings-page-title')?.textContent===${JSON.stringify(({agents:'Agents',routing:'Routing',limits:'Launch limits',assistant:'Assistant',appearance:'Appearance','model-proxy':'Model proxy'})[section])}`); + if(section==='agents')await wait('!!document.querySelector(".agent-more")'); + if(section==='routing')await wait('!!document.querySelector("[data-route]")'); + if(section==='model-proxy')await wait('!!document.querySelector("#proxy-accounts form")'); + return x; +} +async function pointer(b,sel,xpart=.5){const pt=await b.evaluate(`(()=>{let e=document.querySelector(${JSON.stringify(sel)});e.scrollIntoView({block:'center'});let r=e.getBoundingClientRect();return {x:r.left+r.width*${xpart},y:r.top+r.height/2}})()`);for(const type of ['mousePressed','mouseReleased'])await b.call('Input.dispatchMouseEvent',{type,...pt,button:'left',clickCount:1});} +async function input(b,sel,value){await b.evaluate(`(()=>{let e=document.querySelector(${JSON.stringify(sel)});e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('input',{bubbles:true}));e.focus()})()`);} +const opts={timeout:90000}; +test('F1 More Edit opens and focuses editor through keyboard and pointer',opts,async t=>{const {b,wait}=await page(t,'agents');await b.evaluate('document.querySelector(".agent-more").focus()');await b.key('ArrowDown');await b.key('Enter');await wait('!!document.querySelector("#instance-change-form")');assert.equal(await b.evaluate('document.activeElement.closest("#instance-change-form")!==null'),true);await b.evaluate('location.hash="#/settings/appearance"');await wait('!!document.querySelector(".settings-appearance")');await b.evaluate('location.hash="#/settings/agents"');await wait('!!document.querySelector(".agent-more")');await pointer(b,'.agent-more');await pointer(b,'[data-agent-edit]');await wait('!!document.querySelector("#instance-change-form")');}); +test('F2 pointer on hiring track and thumb and keyboard all send',opts,async t=>{const {b,wait}=await page(t,'agents');await pointer(b,'.switch-track',.5);await wait('__writes.length===1');await wait('document.querySelector("#agents-receipt")?.textContent.length>0');assert.equal(await b.evaluate('__writes[0].path'),'/api/veto');await b.evaluate('window.__previousSwitch=document.querySelector(".hiring-grid [role=switch]")');await pointer(b,'.switch-track',.15);await wait('__writes.length===2');await wait('document.querySelector(".hiring-grid [role=switch]")!==window.__previousSwitch && document.querySelector("#agents-receipt")?.textContent.length>0');await b.evaluate('document.querySelector(".hiring-grid [role=switch]").focus()');await b.key(' ');await wait('__writes.length===3');}); +test('F3 phone shows invalid, refusal and unknown receipts while draft remains',opts,async t=>{const {b,wait}=await page(t,'limits',390);await input(b,'#launch-settings-form input[type=number]','-1');await b.key('Enter');await wait('!!document.querySelector("[aria-invalid]")');assert.equal(await b.evaluate('document.querySelector("#launch-settings-receipt").getBoundingClientRect().height>0'),true);await input(b,'#launch-settings-form input[type=number]','2');await b.evaluate(`__scenario['POST /api/settings']={status:409,body:{message:'Fixture conflict',sent:false}}`);await b.key('Enter');await wait('document.querySelector("#launch-settings-receipt")?.textContent.includes("Fixture conflict")');assert.equal(await b.evaluate('document.querySelector("#launch-settings-receipt").getBoundingClientRect().height>0'),true);await b.evaluate(`__scenario['POST /api/settings']={status:500,body:{sent:'unknown'}}`);await wait('document.querySelector("#launch-settings-form button[type=submit]")?.disabled===false');await b.evaluate("document.querySelector('#launch-settings-form').requestSubmit()");await wait('document.querySelector("#launch-settings-receipt")?.textContent.includes("Outcome unknown")');assert.equal(await b.evaluate('document.querySelector("#launch-settings-receipt").getBoundingClientRect().height>0'),true);}); +test('F4 polling preserves Vars and fallback expansion, focus and caret',opts,async t=>{const {b,wait}=await page(t,'agents',1440,{poll:true});await b.evaluate('document.querySelector("#instance-add-form summary").click()');await input(b,'#instance-add-form textarea','{"note":"draft"}');await b.evaluate('document.activeElement.setSelectionRange(4,4);window.__old=document.activeElement;window.__pollRefresh()');await wait('document.querySelector("#instance-add-form textarea")!==window.__old');assert.deepEqual(await b.evaluate('({open:document.querySelector("#instance-add-form details").open,focus:document.activeElement===document.querySelector("#instance-add-form textarea"),caret:document.activeElement.selectionStart})'),{open:true,focus:true,caret:4});await b.evaluate('location.hash="#/settings/routing"');await wait('!!document.querySelector(".fallback-toggle")');await b.viewport(390,900);await pointer(b,'.fallback-toggle');await b.evaluate('document.querySelector(".fallback-cell select").focus();window.__old=document.activeElement;window.__pollRefresh()');await wait('document.querySelector(".fallback-cell select")!==window.__old');assert.equal(await b.evaluate('document.querySelector(".route-row").classList.contains("fallback-open")&&document.activeElement===document.querySelector(".fallback-cell select")'),true);}); +test('F5 Enter in seat name saves only name despite settings draft',opts,async t=>{const {b,wait}=await page(t,'assistant',390);await input(b,'[data-assistant-field=definition]','changed');await input(b,'[data-assistant-field=name]','Wren');await b.key('Enter');await wait('__writes.length>0');assert.equal(await b.evaluate('__writes[0].path'),'/api/name');assert.deepEqual(await b.evaluate('JSON.parse(__writes[0].body)'),{instance:'assistant',name:'Wren'});}); +test('F6 add agent labels left aligned with launch on own row',opts,async t=>{const {b}=await page(t,'agents');const geometry=await b.evaluate(`(()=>{let f=document.querySelector('#instance-add-form'),l=[...f.querySelectorAll('.filters>label')],c=l.map(e=>e.querySelector('input,select').getBoundingClientRect()),r=l.map(e=>e.getBoundingClientRect());return {left:l.slice(0,2).every(e=>getComputedStyle(e).alignItems==='flex-start'),separate:r[2].top>=Math.max(c[0].bottom,c[1].bottom),gap:f.querySelector('button[type=submit]').getBoundingClientRect().top-f.querySelector('details').getBoundingClientRect().bottom}})()`);assert.equal(geometry.left,true);assert.equal(geometry.separate,true);assert.ok(geometry.gap>=12);}); +test('F7 maximum length agent values wrap at 390',opts,async t=>{const {b}=await page(t,'agents',390);assert.equal(await b.evaluate('document.documentElement.scrollWidth<=innerWidth'),true);}); +test('F8 standalone proxy document mounts its settings section',opts,async t=>{const root=resolve('packages/webui/src/public'),server=http.createServer(async(req,res)=>{if(req.method!=='GET'){res.writeHead(403);return res.end();}const path=new URL(req.url,'http://fixture').pathname;if(path.startsWith('/api/')){res.setHeader('content-type','application/json');return res.end(JSON.stringify(path==='/api/config'?{send:true,devOwner:true}:path==='/api/proxy/accounts'?{accounts:[]}:path==='/api/proxy/keys'?{keys:[]}:{rows:[],sessions:[],projects:[],unread:0}));}const file=resolve(root,'.'+(path==='/'?'/index.html':path));if(!file.startsWith(root+'/')){res.writeHead(403);return res.end();}try{res.setHeader('content-type',({'.html':'text/html','.js':'text/javascript','.css':'text/css','.svg':'image/svg+xml'})[extname(file)]||'application/octet-stream');res.end(await readFile(file));}catch{res.writeHead(404);res.end();}});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));const b=await browser({machine:false});t.after(()=>b.close());await b.navigate(`http://127.0.0.1:${server.address().port}/proxy.html`);await b.evaluate('new Promise(r=>setTimeout(r,500))');assert.equal(await b.evaluate('!!document.querySelector("#proxy-accounts")'),true);}); +test('F9 add agent saving and refusal remain local and visible',opts,async t=>{const {b,wait}=await page(t,'agents');await pointer(b,'.agent-more');await pointer(b,'[data-agent-edit]');await wait('!!document.querySelector("#instance-change-form")');await input(b,'#instance-add-form [data-instance-field=instance]','new-coder');await b.evaluate(`document.querySelector('#instance-add-form select').value='coder';window.__baseFetch=fetch;window.fetch=(u,o)=>o?.method==='POST'?new Promise(resolve=>window.__answer=(status,body)=>resolve(new Response(JSON.stringify(body),{status}))):window.__baseFetch(u,o);document.querySelector('#instance-add-form').requestSubmit()`);await wait('!!window.__answer && !!document.querySelector("#instance-add-form .settings-spinner")');assert.equal(await b.evaluate('!!document.querySelector("#instance-add-form .settings-spinner")'),true);assert.equal(await b.evaluate('document.querySelector("#instance-change-form select").disabled'),false);await b.evaluate('__answer(409,{message:"Fixture conflict",sent:false})');await wait('document.querySelector("#instances-receipt")?.textContent.includes("Fixture conflict")');assert.equal(await b.evaluate('!!document.querySelector("#instance-add-form .banner.err")'),true);assert.equal(await b.evaluate('document.querySelector("#instance-add-form .banner.err").getBoundingClientRect().bottom<=document.querySelector("#instance-add-form button[type=submit]").getBoundingClientRect().top'),true);}); +test('F10 routing widths, segmented focus, conditional proxy link and priority style',opts,async t=>{const {b,wait}=await page(t,'routing');assert.equal(await b.evaluate('[...document.querySelectorAll("#routes-table select")].every(e=>e.getBoundingClientRect().width>=132)'),true);await b.evaluate('location.hash="#/settings/appearance"');await wait('!!document.querySelector(".settings-segments")');await b.evaluate('document.querySelector("[name=theme]:checked").focus()');await b.key('ArrowLeft');assert.equal(await b.evaluate('getComputedStyle(document.querySelector(".settings-segments")).outlineStyle!=="none"'),true);await b.evaluate('location.hash="#/settings/model-proxy"');await wait('!!document.querySelector("#proxy-accounts form")');await b.evaluate(`window.open=()=>null;__scenario['POST /api/proxy/login/start']={status:200,body:{url:'https://fixture.invalid/authorize',state:'fixture-state'}}`);await pointer(b,'#proxy-login-start button[type=submit]');await wait('document.querySelector("#proxy-authorize")?.hidden===false');assert.equal(await b.evaluate(`document.querySelector('#proxy-authorize').getBoundingClientRect().height>=44`),true);assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#proxy-accounts button")).backgroundColor===getComputedStyle(document.querySelector("#proxy-refresh")).backgroundColor'),true);}); +test('F11 Vars fields have labels and mobile agent values identify columns',opts,async t=>{const {b,wait}=await page(t,'agents',390);assert.equal(await b.evaluate('document.querySelector("#instance-add-form textarea").labels.length>0'),true);assert.match(await b.evaluate('document.querySelector("#agents-table tbody tr").innerText'),/Definition/);assert.equal(await b.evaluate('document.querySelector("#agents-table tbody td").getAttribute("headers")'), 'agent-col-definition');await b.viewport(1440,1000);await pointer(b,'.agent-more');await pointer(b,'[data-agent-edit]');await wait('!!document.querySelector("#instance-change-form")');assert.equal(await b.evaluate('document.querySelector("#instance-change-form textarea").labels.length>0'),true);}); +test('F12 collapsed section announces current draft and clears after discard',opts,async t=>{const {b,wait}=await page(t,'routing',390);await b.evaluate(`(()=>{let e=[...document.querySelectorAll('[data-route]')].find(e=>JSON.parse(e.dataset.route)[1]==='thinking');e.value='xhigh';e.dispatchEvent(new Event('change',{bubbles:true}))})()`);assert.equal(await b.evaluate('!!document.querySelector("#settings-disclosure .settings-dot")'),true);assert.match(await b.evaluate('document.querySelector("#settings-disclosure").textContent'),/unsaved changes/);await pointer(b,'#routes-reload');await wait('!document.querySelector("#settings-nav .settings-dot")');assert.equal(await b.evaluate('!!document.querySelector("#settings-disclosure .settings-dot")'),false);}); +test('F13 each browser save receipt expires independently',opts,async t=>{const {b}=await page(t,'appearance');await b.evaluate('document.querySelector("[name=theme][value=dim]").focus();document.querySelector("[name=theme][value=dim]").click();document.querySelector("[name=palette][value=grove]").focus();document.querySelector("[name=palette][value=grove]").click();document.querySelector("[name=density][value=compact]").focus();document.querySelector("[name=density][value=compact]").click()');await b.evaluate('new Promise(r=>setTimeout(r,4200))');assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".settings-browser-status")].map(e=>e.textContent)'),['','','']);}); +test('F14 settings subtitle is 16px and fallback option is None',opts,async t=>{const {b,wait}=await page(t,'appearance');assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#bus-view .page-head p")).fontSize'),'16px');await b.evaluate('location.hash="#/settings/routing"');await wait('!!document.querySelector(".fallback-cell select")');assert.equal(await b.evaluate('document.querySelector(".fallback-cell select option").textContent'),'None');}); +test('F9 assistant saving shows spinner and local refusal',opts,async t=>{const {b,wait}=await page(t,'assistant');await input(b,'[data-assistant-field=definition]','changed');await b.evaluate(`window.__baseFetch=fetch;window.fetch=(u,o)=>o?.method==='POST'?new Promise(resolve=>window.__answer=(status,body)=>resolve(new Response(JSON.stringify(body),{status}))):window.__baseFetch(u,o);document.querySelector('.assistant-form').requestSubmit()`);await wait('!!window.__answer');assert.equal(await b.evaluate('!!document.querySelector(".assistant-form .settings-spinner")'),true);assert.equal(await b.evaluate('document.querySelector("[data-assistant-field=name]").disabled'),false);await b.evaluate('__answer(409,{message:"Fixture conflict",sent:false})');await wait('document.querySelector("[data-assistant-receipt]")?.textContent.includes("Fixture conflict")');assert.equal(await b.evaluate('document.querySelector("[data-assistant-receipt]").classList.contains("err")'),true);}); +test('F9 proxy priority disables input and shows saving',opts,async t=>{const {b,wait}=await page(t,'model-proxy');await b.evaluate(`window.__baseFetch=fetch;window.fetch=(u,o)=>o?.method==='POST'?new Promise(resolve=>window.__answer=(status,body)=>resolve(new Response(JSON.stringify(body),{status}))):window.__baseFetch(u,o);document.querySelector('#proxy-accounts form').requestSubmit()`);await wait('!!window.__answer');assert.equal(await b.evaluate('document.querySelector("#proxy-accounts input").disabled'),true);assert.equal(await b.evaluate('!!document.querySelector("#proxy-accounts .settings-spinner")'),true);assert.equal(await b.evaluate('document.querySelector("#proxy-apikey [name=key]").matches(":disabled")'),false);await b.evaluate('__answer(409,{error:"fixture"})');await wait('!!document.querySelector("#proxy-accounts form .banner.err")');await b.evaluate(`window.__answer=null;let f=document.querySelector('#proxy-apikey');f.elements.key.value='fixture-key';f.requestSubmit()`);await wait('!!window.__answer');assert.equal(await b.evaluate('document.querySelector("#proxy-apikey input").disabled'),true);assert.equal(await b.evaluate('!!document.querySelector("#proxy-apikey .settings-spinner")'),true);await b.evaluate('__answer(409,{error:"fixture"})');await wait('!!document.querySelector("#proxy-apikey-message.banner.err")');assert.equal(await b.evaluate('document.querySelector("#proxy-apikey input").value'), '');}); +test('F3 routing refusal remains visible and announced in the phone draft bar',opts,async t=>{const {b,wait}=await page(t,'routing',390);await b.evaluate(`__scenario['POST /api/routes']={status:409,body:{message:'Fixture conflict',sent:false}};[...document.querySelectorAll('[data-route]')].find(e=>JSON.parse(e.dataset.route)[1]==='thinking').focus()`);await b.key('ArrowDown');await wait('!!document.querySelector("#settings-disclosure .settings-dot")');await pointer(b,'#routes-form button[type=submit]');await wait('document.querySelector("#routes-receipt")?.textContent.includes("Fixture conflict")');assert.deepEqual(await b.evaluate(`(()=>{const e=document.querySelector('#routes-receipt'),r=e.getBoundingClientRect();return {visible:r.width>0&&r.height>0,role:e.getAttribute('role'),banner:e.classList.contains('err')}})()`),{visible:true,role:'status',banner:true});}); +test('F9 simultaneous assistant card refusals stay with their own drafts',opts,async t=>{const {b,wait}=await page(t,'assistant');await b.evaluate(`window.__answers={};window.__baseFetch=fetch;window.fetch=(u,o)=>o?.method==='POST'?new Promise(resolve=>window.__answers[u]=(status,body)=>resolve(new Response(JSON.stringify(body),{status}))):window.__baseFetch(u,o)`);await input(b,'[data-assistant-field=definition]','changed');await b.evaluate('document.querySelector(".assistant-form").requestSubmit()');await wait('!!window.__answers["/api/settings"] && !!document.querySelector(".assistant-form .settings-spinner")');await input(b,'[data-assistant-field=name]','Wren');await b.key('Enter');await wait('!!window.__answers["/api/name"]');await b.evaluate(`__answers['/api/name'](409,{message:'Name refused',sent:false})`);await wait('document.querySelector("[data-assistant-kind=name]")?.textContent.includes("Name refused")');await b.evaluate(`__answers['/api/settings'](409,{message:'Settings refused',sent:false})`);await wait('document.querySelector("[data-assistant-kind=settings]")?.textContent.includes("Settings refused")');assert.match(await b.evaluate('document.querySelector("[data-assistant-kind=name]").textContent'),/Name refused/);assert.equal(await b.evaluate('document.querySelector("[data-assistant-field=name]").value'),'Wren');assert.equal(await b.evaluate('document.querySelector("[data-assistant-field=definition]").value'),'changed');}); -- 2.54.0 From c907e4d0d088d676bffd5f3577c471c0e6e950b2 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Fri, 6 Nov 2026 15:29:46 -0600 Subject: [PATCH 010/116] feat(webui): project pages redesign (ui slice 3) --- packages/webui/src/public/brand.js | 1 + packages/webui/src/public/bus.js | 10 +- packages/webui/src/public/chat.js | 58 +++-- packages/webui/src/public/index.html | 6 +- packages/webui/src/public/project-archive.js | 10 +- packages/webui/src/public/projects.css | 92 ++++++++ packages/webui/src/public/projects.js | 213 ++++++++++++++++++ packages/webui/src/public/requests.js | 6 +- packages/webui/src/public/tokens.css | 3 + packages/webui/src/serve.mjs | 2 + packages/webui/tests/browser.test.mjs | 2 +- packages/webui/tests/chat-browser.test.mjs | 12 +- packages/webui/tests/granted-user.test.mjs | 12 + packages/webui/tests/helpers/w15-inbox.mjs | 1 + .../project-archive-style-browser.test.mjs | 1 + .../tests/projects-slice3-browser.test.mjs | 113 ++++++++++ packages/webui/tests/serve.test.mjs | 2 +- .../tests/w15-conversations-browser.test.mjs | 19 +- .../webui/tests/w15-shell-browser.test.mjs | 2 +- 19 files changed, 520 insertions(+), 45 deletions(-) create mode 100644 packages/webui/src/public/projects.css create mode 100644 packages/webui/src/public/projects.js create mode 100644 packages/webui/tests/projects-slice3-browser.test.mjs diff --git a/packages/webui/src/public/brand.js b/packages/webui/src/public/brand.js index 80540567c..3d469e1bf 100644 --- a/packages/webui/src/public/brand.js +++ b/packages/webui/src/public/brand.js @@ -117,6 +117,7 @@ function breadcrumbs() { const path = location.hash.slice(2).split('?')[0], parts = path.split('/').filter(Boolean), box = $('breadcrumbs'); if (!box || !$('bus-view')) return; + if (window.MosaicProjects?.breadcrumb?.(box, $('bus-view'))) return; if (!parts.length || parts[0] === 'board') { box.innerHTML = 'Dashboard'; return; } const names = {projects:'Projects',chat:'Projects',inbox:'Inbox',messages:'Messages',tasks:'Tasks',agents:'Agents',queue:'Queue',business:'Business',docs:'Docs',settings:'Settings'}; const name = names[parts[0]] || 'Dashboard', heading = $('bus-view').querySelector('h1')?.textContent?.trim(); diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index 836d369d1..cb8318a90 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -251,8 +251,9 @@ 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'], ['/business', 'Business', '', 'business'], ['/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}` : ''}
    • `; + return `
    • ${l}${extra ? ` ${extra}` : ''}${h === '/projects' ? '
      ' : ''}
    • `; }).join(''); + window.MosaicProjectTree?.mount?.({ container: $('project-tree'), path: route }); if (focused) [...$('sections').querySelectorAll('a[href]')].find(a => a.getAttribute('href') === focused)?.focus({ preventScroll: true }); } function countInbox(rows) { inboxCount = { open: rows.length, blocking: rows.filter(d => d.blocking).length }; } @@ -1254,16 +1255,13 @@ document.body.classList.toggle('on-bus', !board); $('bus-view').hidden = board; sections(path); - // Conversations owns the project tree. The optional mount receives only the route, - // and must obtain authorized project data itself. It may be absent during integration. - window.MosaicProjectTree?.mount?.({ container: $('project-tree'), path }); document.querySelectorAll('.rail a').forEach(a => { const target = a.getAttribute('href').slice(1); const active = target === '/projects' ? /^\/(projects|chat)(\/|$)/.test(path) : target === '/' ? path === '/' : path === target; if (active) a.setAttribute('aria-current', 'page'); else a.removeAttribute('aria-current'); }); const chatPath = path === '/projects' ? '/chat' : /^\/projects\/(threads|rooms)\//.test(path) ? '/chat' + path.slice('/projects'.length) : /^\/projects\/[^/]+$/.test(path) ? '/chat/projects/' + path.slice('/projects/'.length) : path; window.MosaicChat?.leave(chatPath); if (path === '/settings/display' && window.MosaicDisplay) { window.MosaicDisplay.render($('bus-view'), navigated); shown = route; return; } - if (chatPath === '/chat' || chatPath.startsWith('/chat/') || /^\/projects\/[0-9a-f-]+\/settings$/i.test(chatPath)) { + if (chatPath === '/chat' || chatPath.startsWith('/chat/') || /^\/projects\/[0-9a-f-]+\/(?:settings|conversations|tasks|requirements|files)$/i.test(chatPath)) { // Row 177 (#1675): the tester Console writes to its own threads. const focusedHeading = document.activeElement === $('bus-view').querySelector('h1'); await window.MosaicChat.render({ path: chatPath, container: $('bus-view'), canSend: canSend || isTester, tester: isTester, navigated }); @@ -1389,7 +1387,7 @@ const decisions = (last.get('inbox')?.rows || []).map(d => ({ href: `#/inbox/${enc(d.id)}`, label: first(d.question), group: `decision ${short(d.id)}` })); const tasks = (last.get('tasks')?.rows || []).filter(r => TASK.test(String(r.task_ref))).map(r => { const t = task(r); return { href: `#/tasks/${enc(t.ref)}`, label: `#${t.id} ${t.title ?? '(no title in the current read)'}`, group: 'task' }; }); const rows = (last.get('api:queue')?.rows || []).filter(r => Number.isInteger(r.id)).map(r => ({ href: `#/queue/${r.id}`, label: `${r.id} ${r.piece ?? ''}`, group: `queue row, ${r.state}` })); - pkAll = [...VIEWS.map(([href, label]) => ({ href, label, group: 'view' })), ...decisions, ...tasks, ...rows]; + pkAll = [...VIEWS.map(([href, label]) => ({ href, label, group: 'view' })), ...(window.MosaicProjects?.palette?.() || []), ...decisions, ...tasks, ...rows]; } function pkFill() { const q = $('cmdk-input').value.trim().toLowerCase(); diff --git a/packages/webui/src/public/chat.js b/packages/webui/src/public/chat.js index 8f8aa16e5..d272b8b62 100644 --- a/packages/webui/src/public/chat.js +++ b/packages/webui/src/public/chat.js @@ -209,9 +209,13 @@ function conversation(t) { const s = state(current.key); const withRequest = requestRows(s.rows); - const messages = s.rows.map(m => `
    • ${txt(m.from_role)} ${stamp(m.at)}
      ${messageBody(m)}${withRequest.has(m.id) ? `
      ` : ''}
    • `).join(''); + const messages = s.rows.map(m => `
    • ${txt(m.from_role)} ${stamp(m.at)}
      ${messageBody(m)}${withRequest.has(m.id) ? `
      ` : ''}
    • `).join(''); const receipt = s.receipt; - return `

      ${link('projects', t.project, current.projects.find(p => p.id === t.project)?.name ?? 'Project')} / ${txt(t.instance)}

      ${heading(t.name)}${libraryLine(libraryOf(current, t))}
      Conversation details${sessionControls(t)}${sharing(t)}

      Reading never wakes the assistant. An accepted message is not an answer.

      ${threadWrites() ? `` : ''}
        ${messages || (current.readFailed ? '
      1. Messages unavailable.
      2. ' : '
      3. No messages yet.
      4. ')}
      ${current.readFailed ? '' : s.more ? '

      Showing earlier history. Read forward to reach the current conversation.

      ' : '

      Caught up to the last read.

      '}
      ${threadWrites() ? `

      To: ${txt(t.instance)} · Private conversation

      ` : ''}

      ${txt(receipt)}

      Files

      Files unavailable.
      `; + const project = current.projects.find(p => p.id === t.project); + const redesigned = project && roomOwner() && window.MosaicProjects && (!legacyRoute() || current.path?.startsWith('/projects')); + const frame = redesigned ? window.MosaicProjects.header(project, 'conversations', current.threads, t.name, true) : heading(t.name); + const details = redesigned ? `

      Conversation details

      ${sessionControls(t)}${sharing(t)}

      Reading never wakes the assistant. An accepted message is not an answer.

      ${threadWrites() ? `` : ''}
      ` : `
      Conversation details${sessionControls(t)}${sharing(t)}

      Reading never wakes the assistant. An accepted message is not an answer.

      ${threadWrites() ? `` : ''}`; + return `

      ${link('projects', t.project, current.projects.find(p => p.id === t.project)?.name ?? 'Project')} / ${txt(t.instance)}

      ${frame}${libraryLine(libraryOf(current, t))}${details}
        ${messages || (current.readFailed ? '
      1. Messages unavailable.
      2. ' : '
      3. No messages yet.
      4. ')}
      ${current.readFailed ? '' : s.more ? '

      Showing earlier history. Read forward to reach the current conversation.

      ' : '

      Caught up to the last read.

      '}
      ${threadWrites() ? `

      To: ${txt(t.instance)} · Private conversation

      ` : ''}

      ${txt(receipt)}

      Files

      Files unavailable.
      `; } // C2-10c: rooms reuse the same state, renderer and generation fences as threads. const ROOM_LINES = Object.freeze({ @@ -246,10 +250,12 @@ const messages = s.rows.map(m => { const speaker = m.from_role === 'human' ? 'Human' : roomName(m.from_role); const recipients = m.from_role === 'human' ? ` → ${(m.to ?? []).map(r => txt(roomName(r))).join(', ')}` : ''; - return `
    • ${txt(speaker)}${recipients} ${stamp(m.at)}
      ${messageBody({ ...m, from_role: m.from_role === 'human' ? m.from_role : speaker })}
    • `; + return `
    • ${txt(speaker)}${recipients} ${stamp(m.at)}
      ${messageBody({ ...m, from_role: m.from_role === 'human' ? m.from_role : speaker })}${m.from_role !== 'human' && c.threads.find(t => t.instance === m.from_role && t.name === t.instance) ? `Open ${txt(speaker)} conversation` : ''}
    • `; }).join(''); const off = !c.roomReady || c.channelDisabled || s.pending || !roomOwner(); - return `

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

      ${heading((p?.name ?? 'Project') + ' room')}${roomOpenControl(c.id)}${libraryLine(libraryOf(c))}

      Messages are copied to selected contacts. Their replies are private.

      Room members: ${(c.members ?? []).map(m => `${txt(m.name)} (@${txt(m.instance)})`).join(', ') || 'unavailable'}

        ${messages || (c.readFailed ? '
      1. Messages unavailable.
      2. ' : '
      3. No messages yet.
      4. ')}
      ${c.readFailed ? '' : s.more ? '' : '

      Caught up to the last read.

      '}
      ${c.projectArchived ? '

      This project is archived; its room history stays readable.

      ' : `
      Choose recipients${(c.members ?? []).map(m => ``).join('')}

      Choose contacts above, or use leading @tags. Without tags, the message goes to all room members. Mentions in the message do not add recipients. The broker checks every address.

      `}

      ${txt(s.receipt)}

      `; + const redesigned = p && window.MosaicProjects && roomOwner() && (!legacyRoute() || current.path?.startsWith('/projects')); + const frame = redesigned ? window.MosaicProjects.header(p, 'room', c.threads) + `

      Project room

      Room details

      ${roomOpenControl(c.id)}

      Room members: ${(c.members ?? []).map(m => `${txt(m.name)} (@${txt(m.instance)})`).join(', ') || 'unavailable'}

      ` : heading((p?.name ?? 'Project') + ' room') + roomOpenControl(c.id); + return `

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

      ${frame}${libraryLine(libraryOf(c))}

      Messages are copied to the members you choose. Each reply stays in that member's conversation.

      Room members: ${(c.members ?? []).map(m => `${txt(m.name)} (@${txt(m.instance)})`).join(', ') || 'unavailable'}

        ${messages || (c.readFailed ? '
      1. Messages unavailable.
      2. ' : '
      3. No messages yet.
      4. ')}
      ${c.readFailed ? '' : s.more ? '' : '

      Caught up to the last read.

      '}
      ${c.projectArchived ? '

      This project is archived; its room history stays readable.

      ' : `
      To: Recipients${(c.members ?? []).map(m => redesigned ? `` : ``).join('')}

      Choose contacts above, or use leading @tags. Without tags, the message goes to all room members. Mentions in the message do not add recipients. The broker checks every address.

      `}

      ${txt(s.receipt)}

      `; } function drawRoomCompletion() { const list = document.getElementById('chat-room-completion'), field = document.getElementById('chat-room-body'); @@ -269,7 +275,7 @@ const mentioned = tags.length ? [...body.matchAll(/@([A-Za-z0-9][A-Za-z0-9_.-]*)/g)].map(m => m[1]).find(name => !tags.includes(name) && current.members.some(m => m.instance === name)) : null; if (offer) offer.innerHTML = mentioned ? `` : ''; preview.innerHTML = tags.length ? 'To: ' + tags.map(tag => `@${txt(tag)}`).join(' ') : 'To: all room members'; - for (const box of document.querySelectorAll('[data-room-member]')) box.checked = tags.length ? tags.includes(box.dataset.roomMember) : true; + for (const box of document.querySelectorAll('[data-room-member]')) { box.checked = tags.length ? tags.includes(box.dataset.roomMember) : true; document.querySelector(`[data-room-chip="${CSS.escape(box.dataset.roomMember)}"]`)?.setAttribute('aria-pressed', String(box.checked)); } const prefix = field.value.slice(0, field.selectionStart), token = /(?:^|\s)@([^\s@]*)$/u.exec(prefix); current.completion = null; if (document.activeElement === field && !field.disabled && token && !roomAddress(prefix.slice(0, token.index)).body.trim()) { @@ -287,13 +293,13 @@ field.value = value; state(current.key).draft = value; field.focus(); field.setSelectionRange(caret, caret); updateRoomCompletion(); } - async function renderRoom({ path, container, canSend, user, tester, navigated, next }) { + async function renderRoom({ path, originalPath = path, container, canSend, user, tester, navigated, next }) { if (out()) return; controller?.abort(); controller = new AbortController(); const signal = controller.signal, g = ++generation; const match = /^\/chat\/rooms\/([0-9a-f-]+)$/i.exec(path), id = match?.[1]; const old = current; - current = { kind: 'room', id, key: 'room:' + id, path, container, canSend, user, tester, + current = { kind: 'room', id, key: 'room:' + id, path: originalPath, container, canSend, user, tester, projects: old?.kind === 'room' && old.id === id ? old.projects : [], threads: [], members: [], roomReady: false, channelDisabled: old?.channelDisabled ?? false, refused: false, error: '' }; current.projectArchived = current.projects.some(p => p.id === id && p.archived); if (!UUID.test(id ?? '') || !roomOwner()) { @@ -400,6 +406,7 @@ function paint(navigated = false) { if (!current || out()) return; const keep = capture(), c = current; + const redesigned = (!legacyRoute() || c.path?.startsWith('/projects')) && !!window.MosaicProjects && !c.user && !c.tester; let html = '

      Projects

      '; if (c.error) html += ``; if (c.archiveUnknown) html += '

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

      '; @@ -413,14 +420,19 @@ else html += heading('Thread unavailable'); } else if (c.kind === 'project') { const p = c.projects.find(p => p.id === c.id); - html += heading(p?.name ?? 'Project unavailable'); + html += p && !c.refused && redesigned ? window.MosaicProjects.header(p, c.section, c.threads) : heading(p?.name ?? 'Project unavailable'); if (p && !c.refused) { + if (p.archived && redesigned && !c.canSend) html += '

      This project is archived. Its saved conversations and records stay readable.

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

      Project overview

      Project information

      Repository: ${txt(p.repo || 'Not linked')}

      Repository setting unavailable.
      `; + else if (c.section === 'conversations') html += '

      Conversations

      ' + threads(c.threads.filter(t => !t.shared)) + (p.archived ? '' : creation('thread', c.id)); + else if (redesigned) html += '
      Reading…
      '; else html += `

      Project information

      ${knownRequests.get(c.id)?.repo === p.repo && knownRequests.get(c.id)?.ids.size ? '

      Request status from conversations opened in this session. Other work may not be shown.

      ' : '

      Request status is not loaded. Open a conversation to see its requests.

      '}

      Conversations

      ` + roomOpenControl(c.id) + threads(c.threads.filter(t => !t.shared)) + '

      Shared with me

      ' + threads(c.threads.filter(t => t.shared)) + (p.archived ? '' : creation('thread', c.id)); } + } else if (redesigned) { + html += '
      ' + heading('Projects') + '

      Projects and their conversations.

      ' + (c.canSend ? '
      New project' + creation('project', 'projects') + '
      ' : '') + '
      ' + + c.projects.filter(p => !p.archived).map(p => `${txt(p.name)}${p.repo ? `Repository: ${txt(p.repo)}` : 'No linked repository'}Reading…`).join('') + (c.projects.length ? '' : c.readFailed ? '

      Projects unavailable.

      ' : '

      No projects yet.

      ') + '

      Shared with me

      ' + (c.threads.some(t => t.shared) ? threads(c.threads.filter(t => t.shared)) : '

      Nothing is shared with you yet.

      '); } else { - html += heading('Projects') + '

      Projects and their conversations.

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

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

      ${p.repo ? `

      Repository: ${txt(p.repo)}

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

      Projects unavailable.

      ' : '

      No projects yet.

      ') + '

      Shared with me

      ' + threads(c.threads.filter(t => t.shared)) + creation('project', 'projects'); + html += heading('Projects') + '

      Projects and their conversations.

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

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

      ${p.repo ? `

      Repository: ${txt(p.repo)}

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

      Projects unavailable.

      ' : '

      No projects yet.

      ') + '

      Shared with me

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

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

      '; c.container.innerHTML = html + '
      '; @@ -441,10 +453,19 @@ const remote = c.container.querySelector('[data-chat-remote]'); const project = c.projects.find(p => p.id === c.id); if (remote && roomOwner() && typeof window.MosaicProjectRemote?.mount === 'function') { remote.replaceChildren(); window.MosaicProjectRemote.mount({ container: remote, projectId: c.id, repositoryKey: project?.repo ?? null, projectArchived: !!c.projectArchived, preserve: true }); } - window.MosaicProjectArchive?.mount(c.container, c); + if (!redesigned || c.kind !== 'project' || c.settings || c.projectArchived) window.MosaicProjectArchive?.mount(c.container, c); + if (redesigned && c.kind === 'project' && c.projectArchived && !c.settings) { + const controls = c.container.querySelector('.project-archive-control'); + if (controls) c.container.querySelector('.project-tabs')?.insertAdjacentElement('afterend', controls); + } + if (!c.user && !c.tester && window.MosaicProjects) { + const projectContent = c.container.querySelector('[data-project-content]'); + if (projectContent && project) void window.MosaicProjects.mountContent({ container: projectContent, project, threads: c.threads, section: c.section, canSend: c.canSend }); + if (c.kind === 'list') window.MosaicProjects.enhanceList(c.container, c.projects, c.threads); + } document.title = `${c.container.querySelector('h1')?.textContent ?? 'Chat'} · Mosaic Console`; const details = c.container.querySelector('.chat-details'); - if (details && keep?.detailsOpen) details.open = true; + if (details && keep?.detailsOpen && details.tagName === 'DETAILS') details.open = true; const log = c.container.querySelector('.chat-log'); if (log) { const s = state(c.key ?? c.id); @@ -460,6 +481,7 @@ } } else if (navigated) c.container.querySelector('h1')?.focus({ preventScroll: true }); updateRoomCompletion(); + if (navigated) c.container.querySelector('.project-tabs [aria-current]')?.scrollIntoView({ block: 'nearest', inline: 'nearest' }); } function readError(err) { return err.code === 'channel-disabled' ? channelMessage : err.code === 'thread-not-owned' ? 'This thread is not available to this user.' : @@ -469,12 +491,14 @@ async function render({ path, container, canSend, user = false, tester = false, navigated = false, next = false }) { if (out()) return; const originalPath = path; - const settings = /^\/projects\/([0-9a-f-]+)\/settings$/i.exec(path); - if (settings) path = '/chat/projects/' + settings[1]; + const sectionRoute = /^\/projects\/([0-9a-f-]+)\/(settings|conversations|tasks|requirements|files)$/i.exec(path); + const settings = sectionRoute?.[2] === 'settings'; + const section = sectionRoute?.[2] ?? 'overview'; + if (sectionRoute) path = '/chat/projects/' + sectionRoute[1]; else if (path === '/projects') path = '/chat'; else if (/^\/projects\/(threads|rooms)\//.test(path)) path = '/chat/' + path.slice('/projects/'.length); else if (/^\/projects\/[0-9a-f-]+$/i.test(path)) path = '/chat/projects/' + path.slice('/projects/'.length); - if (/^\/chat\/rooms(?:\/|$)/.test(path)) return renderRoom({ path, container, canSend, user, tester, navigated, next }); + if (/^\/chat\/rooms(?:\/|$)/.test(path)) return renderRoom({ path, originalPath, container, canSend, user, tester, navigated, next }); const match = /^\/chat(?:\/(projects|threads)\/([0-9a-f-]+)(?:\/sessions\/([0-9a-f-]+))?)?$/.exec(path); controller?.abort(); controller = new AbortController(); const signal = controller.signal, g = ++generation; @@ -485,7 +509,7 @@ paint(); return; } const old = current; - current = { container, kind, id, archiveUnknown: kind === 'thread' && !user && !tester, settings: !!settings, path: originalPath, canSend, user, tester, chatGrants: [], thread: old && old.id === id ? old.thread : null, shared: old && old.id === id ? old.shared : false, projects: old?.projects ?? [], threads: old?.threads ?? [], repos: old?.repos ?? [], instances: old?.instances ?? [], instanceError: kind === 'project' ? 'Reading thread instances…' : '', error: '', readFailed: false, channelDisabled: old?.channelDisabled ?? false, refused: false, legacyDefault: old && old.id === id ? old.legacyDefault : false, sessions: old && old.id === id ? old.sessions ?? [] : [], session: match[3] ?? (old && old.id === id ? old.session : null), key: match[3] ? id + '/' + match[3] : old && old.id === id ? old.key : id }; + current = { container, kind, id, archiveUnknown: kind === 'thread' && !user && !tester, settings: !!settings, section, path: originalPath, canSend, user, tester, chatGrants: [], thread: old && old.id === id ? old.thread : null, shared: old && old.id === id ? old.shared : false, projects: old?.projects ?? [], threads: old?.threads ?? [], repos: old?.repos ?? [], instances: old?.instances ?? [], instanceError: kind === 'project' ? 'Reading thread instances…' : '', error: '', readFailed: false, channelDisabled: old?.channelDisabled ?? false, refused: false, legacyDefault: old && old.id === id ? old.legacyDefault : false, sessions: old && old.id === id ? old.sessions ?? [] : [], session: match[3] ?? (old && old.id === id ? old.session : null), key: match[3] ? id + '/' + match[3] : old && old.id === id ? old.key : id }; current.projectArchived = current.projects.some(p => p.id === (kind === 'project' ? id : current.thread?.project) && p.archived); if (kind === 'thread' && old?.kind === 'thread' && old.id === id && !navigated && old.archiveUnknown === false && old.projects.some(p => p.id === old.thread?.project)) current.archiveUnknown = false; if (current.projectArchived) current.archiveUnknown = false; @@ -773,6 +797,8 @@ document.addEventListener('click', event => { if (!current || out()) return; if (event.target.id === 'chat-room-open') void openRoom(); + const chip = event.target.closest?.('[data-room-chip]'); + if (chip) { const name = chip.dataset.roomChip; document.querySelector(`[data-room-member="${CSS.escape(name)}"]`)?.click(); document.querySelector(`[data-room-chip="${CSS.escape(name)}"]`)?.focus(); } const offer = event.target.closest?.('[data-room-offer]'); if (offer && current.kind === 'room') { const field = document.getElementById('chat-room-body'), parsed = roomAddress(field.value), name = offer.dataset.roomOffer; diff --git a/packages/webui/src/public/index.html b/packages/webui/src/public/index.html index a16a16f95..68625da67 100644 --- a/packages/webui/src/public/index.html +++ b/packages/webui/src/public/index.html @@ -3,9 +3,9 @@ Dashboard · Mosaic Console - + - +
      Mosaic Stack @@ -15,7 +15,7 @@
      -