From a88302d6eb5a4eef25565d5eae273dd5713ef8b0 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Mon, 16 Nov 2026 14:36:07 -0600 Subject: [PATCH 1/3] feat(webui): triage drawer, the instance owner opens Triage from the top bar and reads its state, health and transcript, and sends a message when the route allows it; nobody else gets the entry, the markup or a request (#1873, lane triage-drawer) The drawer reads GET /api/triage only while open. A poll keeps the draft and the reader's scroll place. Every field is set as text. Cards show the command with no Run button, and the dropped count. The send box shows only when config triageSend and the read's send are both true. It names each answer in plain words, never resends, and keeps the draft after a refusal. Workflows: Save with only the state changed in an add form says the step is not added yet and keeps the form. The step picker no longer offers the system-only triage template. --- packages/webui/src/public/display.js | 266 ++++++++++++++ packages/webui/src/public/shell.css | 51 +++ packages/webui/src/public/workflows.js | 13 +- .../tests/triage-drawer-browser.test.mjs | 347 ++++++++++++++++++ .../webui/tests/workflows-browser.test.mjs | 42 ++- 5 files changed, 714 insertions(+), 5 deletions(-) create mode 100644 packages/webui/tests/triage-drawer-browser.test.mjs diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index 0613263b4..be5b7d9cb 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -1,4 +1,270 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date(value).toLocaleString() : 'unknown'; +// #1873 triage-drawer: the instance owner's Triage drawer, one system-level entry in the top bar. +// It reads /api/config and /api/triage through the fetch this file starts with, before the +// organization wrapper below replaces it, so both reads stay unscoped: Triage is in no organization. +// The entry, the drawer and every Triage request exist only when that config says triage: true. +// Every value from the read goes in as text, never as markup. The drawer reads only while open. +(() => { + const systemFetch = window.fetch.bind(window); + const POLL_MS = 4000; + // Control, direction and zero-width characters never reach the page; newline and tab stay. + // eslint-disable-next-line no-control-regex + const HIDDEN = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u180e\u2028\u2029\ufeff\u200b-\u200f\u202a-\u202e\u2066-\u2069]/g; + const clean = (value, max = 8000) => (typeof value === 'string' ? value : value === null || value === undefined ? '' : String(value)).replace(/\r\n?/g, '\n').replace(HIDDEN, '').slice(0, max); + const when = value => window.MosaicLocalTime(clean(value, 64)); + const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = clean(text); return n; }; + const NO_ROUTE = 'No model route is set for Triage, so Triage will not start. The instance owner sets the route first.'; + let config = null, entry = null, drawer = null, parts = null, timer = null, gen = 0, sending = false, lastTranscript = '', lastHealth = ''; + + const read = () => systemFetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => (r.ok ? r.json() : null)).catch(() => null); + read().then(c => { if (c && c.triage === true) { config = c; addEntry(); } }); + + function addEntry() { + const bar = document.querySelector('.cmd-right'); + if (!bar || document.getElementById('triage-open')) return; + entry = el('button', 'header-action'); + entry.id = 'triage-open'; entry.type = 'button'; entry.title = 'Triage'; + entry.setAttribute('aria-label', 'Triage'); entry.setAttribute('aria-expanded', 'false'); entry.setAttribute('aria-controls', 'triage-drawer'); + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + svg.setAttribute('class', 'i'); svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true'); + path.setAttribute('d', 'M3 12h4l3-8 4 16 3-8h4'); + svg.append(path); entry.append(svg, el('span', '', 'Triage')); + entry.addEventListener('click', () => (drawer && !drawer.hidden ? close() : open())); + bar.insertBefore(entry, document.getElementById('refresh') ?? bar.firstChild); + } + + function build() { + drawer = el('aside', 'ws-drawer triage-drawer'); + drawer.id = 'triage-drawer'; + drawer.setAttribute('aria-labelledby', 'triage-title'); + const hd = el('div', 'hd'), title = el('h2', '', 'Triage'), x = el('button', 'x', '×'); + title.id = 'triage-title'; title.tabIndex = -1; + x.type = 'button'; x.setAttribute('aria-label', 'Close Triage'); + x.addEventListener('click', close); + hd.append(title, x); + const state = el('p', 'triage-state'); state.id = 'triage-state'; state.setAttribute('role', 'status'); + const healthSec = el('details', 'triage-health-sec'); healthSec.open = true; + const healthSum = el('summary', '', 'Health'); + const health = el('ul', 'triage-health'); health.id = 'triage-health'; + healthSec.append(healthSum, health); + const convo = el('h3', 'triage-convo-title', 'Conversation'); + const transcript = el('ol', 'triage-transcript'); transcript.id = 'triage-transcript'; transcript.tabIndex = 0; + transcript.setAttribute('aria-label', 'Triage conversation'); + const compose = el('div', 'triage-compose'); + drawer.append(hd, state, healthSec, convo, transcript, compose); + drawer.addEventListener('keydown', e => { if (e.key === 'Escape') { e.preventDefault(); close(); } }); + document.body.append(drawer); + parts = { title, state, health, transcript, compose, box: null, send: null, status: null, off: null }; + } + + // The message box is built once and never rewritten by a read, so a draft survives every poll. + function composer(view) { + const c = parts.compose; + const canSend = config.triageSend === true && view.send === true; + if (!canSend) { + if (parts.box) { c.replaceChildren(); parts.box = parts.send = parts.status = null; } + if (!parts.off || !parts.off.isConnected) { parts.off = el('p', 'note triage-send-off'); parts.off.id = 'triage-send-off'; c.append(parts.off); } + parts.off.textContent = 'This Console is read-only, so messages cannot be sent from here.'; + return; + } + if (!parts.box) { + c.replaceChildren(); + const label = el('label', 'triage-label', 'Message to Triage'); + label.htmlFor = 'triage-text'; + const box = el('textarea', 'triage-text'); box.id = 'triage-text'; box.rows = 3; box.maxLength = 8000; + box.setAttribute('aria-describedby', 'triage-send-off triage-send-status'); + box.addEventListener('keydown', e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); submit(); } }); + const row = el('div', 'triage-send-row'); + const send = el('button', 'ws-btn primary triage-send', 'Send'); send.id = 'triage-send'; send.type = 'button'; + send.addEventListener('click', submit); + const hint = el('span', 'triage-hint', 'Ctrl+Enter sends'); + row.append(send, hint); + const off = el('p', 'note triage-send-off'); off.id = 'triage-send-off'; + const status = el('p', 'triage-send-status'); status.id = 'triage-send-status'; status.setAttribute('role', 'status'); + c.append(label, box, off, row, status); + Object.assign(parts, { box, send, status, off }); + } + // A route that is not set, or a session over its cap, turns the box off and says why. + const until = typeof view.overCapUntil === 'string' && view.overCapUntil ? view.overCapUntil : null; + const reason = view.route !== 'set' ? 'Sending is off: no model route is set for Triage.' + : until ? `Sending is off: Triage is over its daily token cap until ${when(until)}.` : ''; + parts.off.textContent = reason; + parts.box.disabled = !!reason; + parts.send.disabled = !!reason || sending; + } + + const stateLine = view => { + if (view.route !== 'set') return clean(view.routeMessage) || NO_ROUTE; + if (view.overCapUntil) return clean(view.capMessage) ? `${clean(view.capMessage)} Local time: ${when(view.overCapUntil)}.` : `Triage is over its daily token cap. It takes messages again at ${when(view.overCapUntil)}.`; + if (view.running === true) return 'Running.'; + const x = view.lastExit; + if (x && typeof x === 'object') { + const how = [x.code !== null && x.code !== undefined ? `code ${clean(x.code)}` : '', x.signal ? `signal ${clean(x.signal)}` : ''].filter(Boolean).join(', ') || 'no code'; + return `Not running. Last exit: ${how} at ${when(x.at)}.`; + } + return 'Not running. No run has ended yet.'; + }; + + const notRead = v => v === 'not read' || v === null || v === undefined || typeof v !== 'object'; + const configWords = c => (notRead(c) ? 'not read' : c.valid === true ? 'valid' : `not valid${c.code ? ` (${clean(c.code)})` : ''}`); + function healthLines(s) { + if (notRead(s)) return ['Health: not read']; + const lines = []; + lines.push(notRead(s.console) ? 'Console: not read' : `Console: ${clean(s.console.state) || 'not read'}, ${when(s.console.at)}`); + if (notRead(s.proxy)) lines.push('Proxy: not read'); + else { + const p = s.proxy; + const words = [p.healthy === true ? 'healthy' : p.healthy === false ? 'not healthy' : 'health not read']; + if (p.initialized === false) words.push('not set up'); + if (p.installed === false) words.push('not installed'); + if (typeof p.active === 'string' && p.active) words.push(`unit ${clean(p.active)}`); + if (p.fence === true) words.push('fence set'); + lines.push(`Proxy: ${words.join(', ')}`); + } + lines.push(`System config: ${configWords(s.systemConfig)}`); + const orgs = s.organizations; + if (notRead(orgs) || !Array.isArray(orgs.list)) lines.push('Organizations: not read'); + else if (!orgs.list.length) lines.push('Organizations: none'); + else for (const o of orgs.list) { + if (!o || typeof o !== 'object') continue; + const bus = notRead(o.bus) ? 'bus not read' : `bus ${clean(o.bus.state) || 'not read'}${o.bus.lastStart && o.bus.lastStart.ok === false ? `, last start failed ${when(o.bus.lastStart.at)}` : ''}`; + const proc = notRead(o.processing) ? 'processing not read' : o.processing.invalid === true ? 'processing state not valid' : o.processing.halted === true ? 'processing stopped' : 'processing on'; + lines.push(`${clean(o.id) || 'unnamed'}: ${bus}, ${proc}, config ${configWords(o.config)}`); + } + return lines; + } + + const WHO = { owner: 'You', triage: 'Triage', host: 'Console' }; + function entryNode(m, owners) { + const from = Object.hasOwn(WHO, m.from) ? m.from : 'other'; + const li = el('li', `triage-msg from-${from}`); + li.dataset.from = from; + const head = el('div', 'triage-msg-head'); + head.append(el('strong', '', WHO[from] ?? 'Unknown sender'), el('span', 'triage-when', when(m.at))); + li.append(head); + if (m.in_reply_to && (from === 'triage' || from === 'host')) { + const asked = owners.get(m.in_reply_to); + li.append(el('p', 'triage-reply', asked !== undefined ? `Reply to: ${asked.length > 120 ? `${asked.slice(0, 119)}…` : asked}` : 'Reply to an earlier message')); + } + li.append(el('p', 'triage-text-body', m.text)); + if (from === 'triage') { + const cards = Array.isArray(m.cards) ? m.cards.filter(c => c && typeof c === 'object') : []; + if (cards.length) { + const list = el('ul', 'triage-cards'); + list.setAttribute('aria-label', 'Suggested commands'); + for (const c of cards) { + const card = el('li', 'triage-card'); + card.append(el('span', 'triage-card-meta', `Step: ${clean(c.step)} · Organization: ${clean(c.org)}`), el('code', 'triage-card-cmd', c.command)); + list.append(card); + } + li.append(list); + } + const dropped = Number.isSafeInteger(m.dropped) && m.dropped > 0 ? m.dropped : 0; + if (dropped) li.append(el('p', 'triage-dropped', `${dropped} ${dropped === 1 ? 'card' : 'cards'} dropped: not a known step or organization.`)); + } + return li; + } + + function render(view) { + // Where the reader is, measured before anything above the conversation changes its height. + const t = parts.transcript, atBottom = t.scrollHeight - t.scrollTop - t.clientHeight < 24, top = t.scrollTop; + parts.state.textContent = stateLine(view); + parts.state.dataset.kind = view.route !== 'set' ? 'off' : view.overCapUntil ? 'cap' : view.running === true ? 'running' : 'stopped'; + const lines = healthLines(view.snapshot); + const healthKey = JSON.stringify(lines); + if (healthKey !== lastHealth) { lastHealth = healthKey; parts.health.replaceChildren(...lines.map(l => el('li', l.endsWith('not read') ? 'not-read' : '', l))); } + // The box first: it sets the conversation's height, which the scroll position below depends on. + composer(view); + const list = Array.isArray(view.transcript) ? view.transcript.filter(m => m && typeof m === 'object') : []; + const key = JSON.stringify(list); + if (key !== lastTranscript) { + const first = lastTranscript === ''; + lastTranscript = key; + const owners = new Map(list.filter(m => m.from === 'owner' && typeof m.id === 'string').map(m => [m.id, clean(m.text)])); + if (list.length) t.replaceChildren(...list.map(m => entryNode(m, owners))); + else t.replaceChildren(el('li', 'triage-empty', 'No messages yet.')); + t.scrollTop = first || atBottom ? t.scrollHeight : top; + } + } + + // Only the newest read renders and schedules the next one, so a send's read and the timer's never + // run two chains at once, and an answer that lands after close is dropped. + async function poll() { + const mine = ++gen; + clearTimeout(timer); + let view = null, failed = null; + try { + const r = await systemFetch('/api/triage', { cache: 'no-store', redirect: 'manual' }); + if (r.ok) view = await r.json(); else failed = r.status; + } catch { failed = 'no answer'; } + if (mine !== gen || !drawer || drawer.hidden) return; + if (view && typeof view === 'object') render(view); + else { parts.state.textContent = `Triage could not be read (${failed}). The drawer tries again shortly.`; parts.state.dataset.kind = 'error'; } + timer = setTimeout(poll, POLL_MS); + } + + function open() { + if (!drawer) build(); + drawer.hidden = false; + entry.setAttribute('aria-expanded', 'true'); + if (!parts.state.dataset.kind) { parts.state.textContent = 'Reading Triage.'; parts.state.dataset.kind = 'reading'; } + poll().then(() => { if (!drawer.hidden && !drawer.contains(document.activeElement)) (parts.box && !parts.box.disabled ? parts.box : parts.title).focus(); }); + } + + function close() { + if (!drawer || drawer.hidden) return; + gen += 1; + clearTimeout(timer); timer = null; + drawer.hidden = true; + entry.setAttribute('aria-expanded', 'false'); + entry.focus(); + } + + // Plain words for each answer. A refused send keeps the draft; an unknown outcome is never resent. + function answer(status, body) { + const code = body && typeof body.error === 'string' ? body.error : ''; + if (status === 202) return { sent: true, text: 'Sent. Triage answers in the conversation above.' }; + if (status === 409) return { text: code === 'triage-no-route' ? 'Not sent: no model route is set for Triage. The instance owner sets the route first.' : code === 'triage-route-refused' ? 'Not sent: the model route refused to start Triage.' : 'Not sent: the model route\'s answer is not usable.' }; + if (status === 429) { + if (code === 'triage-over-cap') { + const until = typeof body.until === 'string' ? clean(body.until) : ''; + return { text: until ? `Not sent: Triage is over its daily token cap. It takes messages again at ${when(until)} (${until}).` : 'Not sent: Triage is over its daily token cap.' }; + } + return { text: 'Not sent: Triage has too many messages waiting. Try again in a moment.' }; + } + if (status === 400) return { text: code === 'triage-message-empty' ? 'Not sent: the message is empty.' : code === 'triage-message-too-long' ? 'Not sent: the message is too long.' : 'Not sent: the Console did not accept this as a Triage message.' }; + if (status === 403) return { text: code === 'read-only' ? 'Not sent: this Console is read-only.' : 'Not sent: the Console refused a request that did not come from this page.' }; + if (status === 503 && code === 'outcome-unknown') return { unknown: true, text: 'Triage did not answer. The message may or may not have arrived. It was not sent again: check the conversation before you send it again.' }; + if (status === 503) return { text: `Not sent: ${clean(body && body.message) || 'Triage could not take the message'}.` }; + if (status === 401 || status === 404) return { text: 'Not sent: this page can no longer reach Triage. Reload the page.' }; + return { text: `Not sent: the Console answered ${status}.` }; + } + + async function submit() { + if (sending || !parts.box || parts.box.disabled) return; + const text = parts.box.value; + if (!text.trim()) { parts.status.textContent = 'Not sent: the message is empty.'; return; } + sending = true; parts.send.disabled = true; parts.status.textContent = 'Sending…'; + let result; + try { + const r = await systemFetch('/api/triage/message', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text }), cache: 'no-store', redirect: 'manual' }); + result = answer(r.status, await r.json().catch(() => null)); + } catch { + result = { unknown: true, text: 'The Console did not answer. The message may or may not have arrived. It was not sent again: check the conversation before you send it again.' }; + } + sending = false; + if (!parts.box) return; + // The status line can grow the composer; a reader at the bottom of the transcript stays there. + const t = parts.transcript, atBottom = t.scrollHeight - t.scrollTop - t.clientHeight < 24; + parts.status.textContent = result.text; + parts.status.dataset.kind = result.sent ? 'ok' : result.unknown ? 'unknown' : 'refused'; + // Only a 202 clears the box, and only when the reader has not typed more since. + if (result.sent && parts.box.value === text) parts.box.value = ''; + parts.send.disabled = parts.box.disabled; + if (atBottom) t.scrollTop = t.scrollHeight; + if (drawer && !drawer.hidden) poll(); + } +})(); // #1873 SP1: one shell for the whole system. `#/dashboard` is the system landing route and // `#/orgs//...` is a route inside the same page, not a mode: opening another organization // changes the scope of later /api reads and fires `mosaic-org-switch`. Nothing reloads. diff --git a/packages/webui/src/public/shell.css b/packages/webui/src/public/shell.css index f3d7bb2df..16262b17a 100644 --- a/packages/webui/src/public/shell.css +++ b/packages/webui/src/public/shell.css @@ -810,3 +810,54 @@ html[data-organizations] .ws-drawer-acts .note{flex-basis:100%} html[data-organizations] .ws-av.mob{display:inline-grid;margin-right:6px;vertical-align:-3px} html[data-organizations] .ws-tbl .t2.mono.hide-m{display:none} } +/* #1873 triage-drawer: the owner's Triage drawer, in the agent drawer family. It sits above an open + agent drawer, keeps its own header and message box in view, and scrolls the conversation alone. */ +#triage-drawer{position:fixed;top:var(--bar-h,52px);right:0;bottom:0;width:min(440px,100vw);z-index:41;display:flex;flex-direction:column;overflow:hidden;background:var(--surface);color:var(--text);border-left:1px solid var(--line);box-shadow:-8px 0 24px color-mix(in srgb,#000 14%,transparent)} +#triage-drawer[hidden]{display:none} +#triage-drawer .hd{display:flex;align-items:center;gap:8px;padding:12px 14px 12px 17px;border-bottom:1px solid var(--line);flex:none;box-shadow:inset 4px 0 0 var(--action)} +#triage-drawer h2{margin:0;font-size:18px;font-weight:800;color:var(--strong)} +#triage-drawer h2:focus{outline:none} +#triage-drawer .x{margin-left:auto;flex:none;width:32px;height:32px;border:1px solid var(--line);border-radius:6px;background:var(--canvas);color:var(--strong);font-size:20px;line-height:1;cursor:pointer} +#triage-drawer .triage-state{margin:0;padding:10px 14px;flex:none;font-size:14px;font-weight:600;color:var(--strong);border-bottom:1px solid var(--line);overflow-wrap:anywhere} +#triage-drawer .triage-state[data-kind=off],#triage-drawer .triage-state[data-kind=cap]{color:var(--warning);background:color-mix(in srgb,var(--warning) 9%,var(--surface))} +#triage-drawer .triage-state[data-kind=running]::before{content:"";display:inline-block;width:8px;height:8px;margin-right:7px;border-radius:50%;background:var(--success);vertical-align:1px} +#triage-drawer .triage-health-sec{flex:none;padding:8px 14px;border-bottom:1px solid var(--line)} +#triage-drawer .triage-health-sec summary{cursor:pointer;font:700 11px/1.6 var(--font);letter-spacing:.06em;text-transform:uppercase;color:var(--muted)} +#triage-drawer .triage-health{list-style:none;margin:6px 0 0;padding:0;display:grid;gap:3px;max-height:24vh;overflow:auto;font-size:12.5px;color:var(--strong)} +#triage-drawer .triage-health li{overflow-wrap:anywhere;padding-left:12px;position:relative} +#triage-drawer .triage-health li::before{content:"";position:absolute;left:0;top:.5em;width:6px;height:6px;border-radius:50%;background:var(--line)} +#triage-drawer .triage-health li.not-read{color:var(--muted)} +#triage-drawer .triage-convo-title{margin:0;padding:10px 14px 4px;flex:none;font:700 11px/1.3 var(--font);letter-spacing:.06em;text-transform:uppercase;color:var(--muted)} +#triage-drawer .triage-transcript{list-style:none;margin:0;padding:4px 14px 12px;flex:1 1 auto;min-height:120px;overflow:auto;overscroll-behavior:contain;display:flex;flex-direction:column;gap:8px} +#triage-drawer .triage-transcript:focus-visible{outline:2px solid var(--action);outline-offset:-2px} +#triage-drawer .triage-msg{border:1px solid var(--line);border-radius:8px;padding:8px 10px;background:var(--canvas);font-size:13.5px;overflow-wrap:anywhere} +#triage-drawer .triage-msg.from-owner{background:color-mix(in srgb,var(--action) 8%,var(--surface));border-color:color-mix(in srgb,var(--action) 30%,var(--line))} +#triage-drawer .triage-msg.from-host,#triage-drawer .triage-msg.from-other{background:transparent;border-style:dashed;color:var(--muted)} +#triage-drawer .triage-msg-head{display:flex;gap:8px;align-items:baseline;margin-bottom:3px} +#triage-drawer .triage-msg-head strong{color:var(--strong);font-size:13px} +#triage-drawer .triage-when{font-size:11.5px;color:var(--muted)} +#triage-drawer .triage-reply{margin:0 0 4px;padding-left:8px;border-left:3px solid var(--line);font-size:12.5px;color:var(--muted)} +#triage-drawer .triage-text-body{margin:0;white-space:pre-wrap;color:var(--strong)} +#triage-drawer .from-host .triage-text-body,#triage-drawer .from-other .triage-text-body{color:inherit} +#triage-drawer .triage-cards{list-style:none;margin:8px 0 0;padding:0;display:grid;gap:6px} +#triage-drawer .triage-card{display:grid;gap:4px;border:1px solid var(--line);border-radius:6px;padding:6px 8px;background:var(--surface)} +#triage-drawer .triage-card-meta{font-size:12px;color:var(--muted)} +#triage-drawer .triage-card-cmd{display:block;font:12px/1.5 var(--mono);color:var(--strong);white-space:pre-wrap;overflow-wrap:anywhere;user-select:all} +#triage-drawer .triage-dropped{margin:6px 0 0;font-size:12px;color:var(--warning)} +#triage-drawer .triage-empty{color:var(--muted);font-size:13px} +#triage-drawer .triage-compose{flex:none;display:grid;gap:6px;padding:10px 14px 14px;border-top:1px solid var(--line);background:var(--surface)} +#triage-drawer .triage-label{font-size:12px;font-weight:700;color:var(--muted)} +#triage-drawer .triage-text{width:100%;box-sizing:border-box;min-height:64px;max-height:30vh;resize:vertical;padding:8px 10px;border:1px solid var(--line);border-radius:6px;background:var(--canvas);color:var(--strong);font:14px/1.45 var(--font)} +#triage-drawer .triage-text:disabled{opacity:.6;cursor:not-allowed} +#triage-drawer .triage-send-row{display:flex;align-items:center;gap:10px} +#triage-drawer .triage-send{display:inline-flex;align-items:center;min-height:36px;padding:4px 16px;border:1px solid var(--action);border-radius:var(--r,6px);background:var(--action);color:var(--canvas);font:700 13px/1.4 var(--font);cursor:pointer} +#triage-drawer .triage-send:disabled{background:var(--raised);border-color:var(--line);color:var(--muted);cursor:not-allowed} +#triage-drawer .triage-hint{font-size:12px;color:var(--muted)} +#triage-drawer .note{margin:0;font-size:12.5px;color:var(--warning)} +#triage-drawer .note:empty,#triage-drawer .triage-send-status:empty{display:none} +#triage-drawer .triage-send-status{margin:0;font-size:13px;color:var(--strong)} +#triage-drawer .triage-send-status[data-kind=refused]{color:var(--danger)} +#triage-drawer .triage-send-status[data-kind=unknown]{color:var(--warning)} +#triage-drawer .triage-send-status[data-kind=ok]{color:var(--success)} +@media (min-width:1200px){body:has(#triage-drawer:not([hidden])) .content{padding-right:calc(440px + 22px)}} +@media (max-width:700px){#triage-drawer{top:0;left:0;width:auto;border-left:0;box-shadow:none;z-index:60}html:has(#triage-drawer:not([hidden])),body:has(#triage-drawer:not([hidden])){overflow:hidden}#triage-drawer .triage-health{max-height:18vh}} diff --git a/packages/webui/src/public/workflows.js b/packages/webui/src/public/workflows.js index 2447e3240..1756b220d 100644 --- a/packages/webui/src/public/workflows.js +++ b/packages/webui/src/public/workflows.js @@ -40,11 +40,15 @@ return value; } const plain = v => v !== null && typeof v === 'object' && !Array.isArray(v); + // #1873: the templates no organization may hold (organization vocabulary SYSTEM_ONLY). The read may still + // list them; a step role never resolves to one and the picker never offers one. + const SYSTEM_ONLY = ['triage']; + const offered = list => (list || []).filter(r => !SYSTEM_ONLY.includes(r)); async function read(org, s) { const value = await call(`${base(org)}/workflows`, 'GET'); if (!plain(value) || !plain(value.workflows) || !plain(value.projects) || !plain(value.roles) || typeof value.revision !== 'string') throw Error('The workflow read returned an unexpected answer.'); s.data = value; - s.known = new Set([...(value.roles.definitions || []), ...(value.roles.templates || []), 'human']); + s.known = new Set([...(value.roles.definitions || []), ...offered(value.roles.templates), 'human']); } // SP17: a write in flight holds the poll. Each organization counts its writes (epoch moves when one starts // and when it ends); a read that began before a write ended, or answers while one is in flight, is dropped @@ -310,7 +314,7 @@ // The role picker: human, the organization's roles, the role templates, and first any role the step names // that resolves to none of those (checked and marked, so leaving it in is a choice the save check names). function rolePick(s, chosen, prefix, off = false) { - const defs = [...(s.data.roles.definitions || [])].sort(), tpl = [...(s.data.roles.templates || [])].filter(r => !defs.includes(r)).sort(); + const defs = [...(s.data.roles.definitions || [])].sort(), tpl = offered(s.data.roles.templates).filter(r => !defs.includes(r)).sort(); const odd = chosen.filter(r => !s.known.has(r)); const box = (r, mark = '') => ``; const group = (title, list, mark) => (list.length ? `

${title}

${list.map(r => box(r, mark)).join('')}` : ''); @@ -620,9 +624,10 @@ const d = drafts.get(key); if (!d || d.busy) return; // SP17 review: a new step typed in the add form is not saved over or dropped: Save says so and keeps the - // form. An add form with nothing typed in it is closed and the rest is saved. + // form. So is one in which only the state was changed. An add form left as it opened is closed and the + // rest is saved. if (d.edit?.mode === 'add') { - if (d.edit.title.trim() || d.edit.roles.length) { + if (d.edit.title.trim() || d.edit.roles.length || editDirty(d.edit)) { d.atBar = false; d.status = `Not saved: new step ${d.edit.i + 1} is not added yet. Press Add step, or Cancel to drop it.`; say(d.status); paint(); return toAddTitle(); } diff --git a/packages/webui/tests/triage-drawer-browser.test.mjs b/packages/webui/tests/triage-drawer-browser.test.mjs new file mode 100644 index 000000000..69e774d53 --- /dev/null +++ b/packages/webui/tests/triage-drawer-browser.test.mjs @@ -0,0 +1,347 @@ +// #1873 triage-drawer: the Console's Triage drawer over GET /api/triage and POST /api/triage/message. +// Only the instance owner sees it: the entry, the drawer and every Triage request exist only when the +// unscoped /api/config says triage: true. The real server serves the routes from a fake Triage host, +// so every answer here crossed the real HTTP boundary. One page stub forces the 403 answer, which the +// browser's own same-origin request cannot produce. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { fileURLToPath } from 'node:url'; +import { startServer } from '../src/serve.mjs'; +import { createDevOwner } from '../src/dev-owner.mjs'; +import { TriageError } from '../src/triage-host.mjs'; +import { capMessage, NO_ROUTE_MESSAGE } from '../src/triage-http.mjs'; +import { browser } from './browser.mjs'; +import { close } from './fixture.mjs'; + +const waitFor = b => (expression, tries = 200) => b.evaluate(`(async()=>{for(let i=0;i<${tries};i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`); +const sleep = ms => new Promise(r => setTimeout(r, ms)); +const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString(); +const POLL_MS = 4000; + +async function orgFixture() { + const { checkRootAgents } = await import('../../organization/src/index.mjs'); + const rolesDir = fileURLToPath(new URL('../../../roles', import.meta.url)); + const root = { state: 'ok', ...checkRootAgents({ agentsVersion: 1, agents: {} }, { rolesDir }) }; + const LIST = [{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true }]; + const empty = (name) => Promise.resolve(['usage', 'limits'].includes(name) ? {} : []); + const opts = () => ({ + bus: { inbox: () => empty('inbox'), agents: () => empty('agents'), 'thread.claims': () => empty('claims'), tasks: () => empty('tasks'), usage: () => empty('usage'), limits: () => empty('limits'), decisions: () => empty('decisions') }, + chat: { threads: () => empty('threads'), projects: () => empty('projects') }, + }); + const member = org => ({ id: org.id, doc: { appearance: { theme: org.theme }, roles: { chief: { definition: 'chief-of-staff' } }, projects: {} }, status: async () => ({ healthy: true, pid: 4242, boot: null }), options: opts }); + const organizations = { + list: async () => LIST, + members: async () => LIST.map(member), + resolve: async id => { + const org = LIST.find(o => o.id === id); if (!org) return null; + return { + busHealthy: true, + reads: { business: async () => ({ business: { id, human: 'jason', projects: [], appearance: { theme: org.theme } } }), settings: async () => ({ business: id, release: 'fixture', notifier: {}, launch: { business: id, revision: 'a'.repeat(64), models: {}, limits: { total: 4 }, instances: {}, usage: { total: 0, providers: {}, models: {} } } }), queue: async () => ({ rows: [] }), busStatus: async () => ({}) }, + bus: { messages: async () => ({ messages: [], unread: 0 }), agents: async () => [], 'thread.claims': async () => [], inbox: async () => [], tasks: async () => [], instances: async () => ({ business: id, revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {}, instances: {} }) }, + chat: { projects: async () => [], threads: async () => [] }, + }; + }, + }; + return { organizations, agentLevels: { loadRoot: () => root, rolesDir, ctx: { configDir: '/cfg', dataRoot: '/data', instance: 'test' } } }; +} + +const SNAPSHOT = () => ({ + snapshotVersion: 1, at: at(1), console: { state: 'answering', at: at(1) }, proxy: 'not read', + systemConfig: { valid: true, exit: 0, code: null }, + organizations: { count: 2, list: [ + { id: 'acme', bus: { state: 'running', lastStart: { ok: true, at: at(60) } }, processing: { halted: false, invalid: false }, config: { valid: true, exit: 0, code: null } }, + { id: 'gamma', bus: 'not read', processing: 'not read', config: { valid: false, exit: 2, code: 'org-config-invalid' } }, + ] }, +}); + +// The fake host. `h` is the state the next read returns; `h.next` is an error the next message throws. +function fakeHost(over = {}) { + const h = { route: 'set', running: false, lastExit: null, overCapUntil: null, snapshot: SNAPSHOT(), transcript: [], reads: 0, sent: [], next: null, ...over }; + let n = 0; + const triage = { + snapshotAt: () => Date.now(), + refresh: async () => null, + state: async () => { h.reads += 1; return { route: h.route, running: h.running, lastExit: h.lastExit, overCapUntil: h.overCapUntil, snapshot: h.snapshot, transcript: h.transcript }; }, + message: async text => { + h.sent.push(text); + const e = h.next; h.next = null; + if (e) throw e; + const m = { id: `owner-${String(++n).padStart(12, '0')}`, at: new Date().toISOString() }; + h.transcript = [...h.transcript, { at: m.at, from: 'owner', id: m.id, text }]; + return m; + }, + }; + return { h, triage }; +} + +async function setup(t, { host = fakeHost(), triage = host.triage, send = true, sso = createDevOwner(), viewport = [1440, 900], path = '/#/dashboard', init = null } = {}) { + const { organizations, agentLevels } = await orgFixture(); + const server = await startServer({ port: 0, sso, organizations, agentLevels, triage, send: send ? async () => ({}) : null, log: () => {} }); + t.after(() => close(server)); + const b = await browser({ machine: false }); t.after(() => b.close()); + await b.viewport(...viewport); + const requests = []; + await b.call('Network.enable'); + b.on('Network.requestWillBeSent', p => { const u = new URL(p.request.url); requests.push(`${p.request.method} ${u.pathname}`); }); + if (init) await b.call('Page.addScriptToEvaluateOnNewDocument', { source: init }); + const base = `http://127.0.0.1:${server.address().port}`; + await b.navigate(`${base}${path}`); + const wait = waitFor(b); + const text = sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.innerText ?? null`); + const click = sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)}).click()`); + const triageReads = () => requests.filter(r => r === 'GET /api/triage').length; + return { b, base, wait, text, click, requests, triageReads, h: host.h }; +} + +const open = async f => { await f.wait('document.querySelector("#triage-open")'); await f.click('#triage-open'); await f.wait('["off", "cap", "running", "stopped"].includes(document.querySelector("#triage-drawer #triage-state")?.dataset.kind)'); }; +const type = async (f, words) => { await f.b.evaluate('document.querySelector("#triage-text").focus()'); await f.b.call('Input.insertText', { text: words }); }; +const sendAndWait = async (f, before) => { await f.click('#triage-send'); await f.wait(`document.querySelector("#triage-send-status").textContent.trim() && document.querySelector("#triage-send-status").textContent !== ${JSON.stringify(before)} && !document.querySelector("#triage-send").disabled`); return f.text('#triage-send-status'); }; + +test('item 1: a session that is not the instance owner gets no entry, no drawer markup and no Triage request', async t => { + // No Triage host wired: the config never says triage. + { + const f = await setup(t, { triage: null }); + await f.wait('document.querySelector("#dashboard-kpis")'); + await sleep(1500); + assert.equal(await f.b.evaluate('document.querySelector("#triage-open, #triage-drawer, [id^=triage]")'), null); + assert.deepEqual(f.requests.filter(r => /triage/i.test(r)), []); + } + // A Triage host, but a signed-in session that is not the root owner. + { + const owner = createDevOwner(), plain = { ...owner.session(), rootOwner: false }; + const f = await setup(t, { sso: { ...owner, session: () => plain } }); + await f.wait('document.querySelector("#dashboard-kpis")'); + await sleep(1500); + assert.equal(await f.b.evaluate('document.querySelector("[id^=triage]")'), null); + assert.equal(await f.b.evaluate('document.body.innerHTML.includes("Triage")'), false, 'no Triage words in the page'); + assert.deepEqual(f.requests.filter(r => /triage/i.test(r)), []); + } +}); + +test('item 1: the owner gets one Triage entry in the top bar on the dashboard and inside an organization; nothing is read until it opens', async t => { + const f = await setup(t, { path: '/#/orgs/acme/organization' }); + await f.wait('document.querySelector(".cmd-right #triage-open")'); + assert.equal(await f.b.evaluate('document.querySelectorAll("#triage-open").length'), 1); + assert.equal(await f.b.evaluate('document.querySelector("#triage-drawer")'), null, 'no drawer markup before it opens'); + await sleep(800); + assert.equal(f.triageReads(), 0, 'no read before it opens'); + assert.equal(await f.b.evaluate('document.querySelector("#triage-open").getAttribute("aria-expanded")'), 'false'); + await open(f); + assert.equal(await f.b.evaluate('document.querySelector("#triage-open").getAttribute("aria-expanded")'), 'true'); + // From inside an organization the read is still the system route, never the organization's. + assert.ok(f.triageReads() >= 1); + assert.deepEqual(f.requests.filter(r => /triage/.test(r) && r !== 'GET /api/triage'), []); + assert.ok(f.requests.includes('GET /api/config'), 'the unscoped config read'); + // The same entry on the system dashboard. + await f.b.evaluate('location.hash = "#/dashboard"'); + await f.wait('location.hash === "#/dashboard" && document.querySelector("#triage-open")'); +}); + +test('item 1: at 390 wide the entry stays visible and one click opens the drawer', async t => { + const f = await setup(t, { viewport: [390, 844] }); + await f.wait('document.querySelector("#triage-open")'); + const box = await f.b.evaluate('(() => { const r = document.querySelector("#triage-open").getBoundingClientRect(); return { w: r.width, h: r.height, right: r.right, top: r.top }; })()'); + assert.ok(box.w > 0 && box.h > 0 && box.right <= 390 && box.top >= 0, JSON.stringify(box)); + await open(f); + const d = await f.b.evaluate('(() => { const r = document.querySelector("#triage-drawer").getBoundingClientRect(); return { l: r.left, w: r.width, page: document.documentElement.clientWidth }; })()'); + assert.ok(d.l <= 1 && d.w >= d.page - 1, `the drawer takes the whole width: ${JSON.stringify(d)}`); + assert.equal(await f.b.evaluate('document.documentElement.scrollWidth <= 390'), true, 'no sideways scroll'); +}); + +test('item 2 and 3: route not set says so, and the message box is off with the reason', async t => { + const f = await setup(t, { host: fakeHost({ route: 'not set' }) }); + await open(f); + assert.match(await f.text('#triage-state'), new RegExp(NO_ROUTE_MESSAGE.slice(0, 40))); + assert.equal(await f.b.evaluate('document.querySelector("#triage-text")?.disabled'), true); + assert.equal(await f.b.evaluate('document.querySelector("#triage-send")?.disabled'), true); + assert.match(await f.text('#triage-send-off'), /no model route is set/i); +}); + +test('item 2: over cap shows the cap message and the time it takes messages again', async t => { + const until = new Date(Date.now() + 3 * 3600000).toISOString(); + const f = await setup(t, { host: fakeHost({ overCapUntil: until }) }); + await open(f); + const state = await f.text('#triage-state'); + assert.ok(state.includes(capMessage(until)), state); + const local = await f.b.evaluate(`window.MosaicLocalTime(${JSON.stringify(until)})`); + assert.ok(state.includes(`Local time: ${local}.`), state); + assert.match(await f.text('#triage-send-off'), /daily token cap/i); +}); + +test('item 2: running, last exit, and the health snapshot with "not read" shown as that', async t => { + const host = fakeHost({ running: true }); + const f = await setup(t, { host }); + await open(f); + assert.match(await f.text('#triage-state'), /^Running/); + const health = await f.text('#triage-health'); + assert.match(health, /Console: answering/); + assert.match(health, /Proxy: not read/); + assert.match(health, /System config: valid/); + assert.match(health, /acme: bus running, processing on, config valid/); + assert.match(health, /gamma: bus not read, processing not read, config not valid \(org-config-invalid\)/); + assert.doesNotMatch(health.split('\n').find(l => l.startsWith('gamma')), /healthy|running/); + // The next poll picks up a stopped session and its last exit, and a snapshot that read nothing. + host.h.running = false; host.h.lastExit = { code: 1, signal: null, at: at(2) }; + host.h.snapshot = { snapshotVersion: 1, at: at(0), console: { state: 'answering', at: at(0) }, proxy: { initialized: true, installed: true, active: 'active', healthy: true, fence: false }, systemConfig: 'not read', organizations: 'not read' }; + await f.wait('/Last exit/.test(document.querySelector("#triage-state").textContent)', 300); + assert.match(await f.text('#triage-state'), /Not running\. Last exit: code 1/); + const after = await f.text('#triage-health'); + assert.match(after, /Proxy: healthy/); + assert.match(after, /System config: not read/); + assert.match(after, /Organizations: not read/); + // No snapshot at all. + host.h.snapshot = null; + await f.wait('/Health: not read/.test(document.querySelector("#triage-health").textContent)', 300); +}); + +test('item 2: the transcript shows owner, Triage and host lines, a reply under its message, and cards as text with no Run button', async t => { + const transcript = [ + { at: at(5), from: 'owner', id: 'owner-000000000001', text: 'Why is gamma down?' }, + { at: at(4), from: 'triage', in_reply_to: 'owner-000000000001', text: 'gamma config is not valid. Restart acme after fixing it.', cards: [{ step: 'org-config-validate', org: 'gamma', command: 'mosaic org config validate gamma' }, { step: 'bus-restart', org: 'acme', command: 'mosaic bus restart acme' }], dropped: 2 }, + { at: at(3), from: 'owner', id: 'owner-000000000002', text: 'And beta?' }, + { at: at(2), from: 'host', in_reply_to: 'owner-000000000002', text: 'Triage stopped before it answered this message. Send it again.' }, + ]; + const f = await setup(t, { host: fakeHost({ running: true, transcript }) }); + await open(f); + const items = await f.b.evaluate('[...document.querySelectorAll("#triage-transcript > li")].map(li => ({ from: li.dataset.from, text: li.innerText }))'); + assert.deepEqual(items.map(i => i.from), ['owner', 'triage', 'owner', 'host']); + assert.match(items[0].text, /You/); assert.match(items[0].text, /Why is gamma down\?/); + assert.match(items[1].text, /Triage/); assert.match(items[1].text, /Reply to: Why is gamma down\?/); + assert.match(items[1].text, /Step: org-config-validate/); assert.match(items[1].text, /Organization: gamma/); + assert.match(items[1].text, /mosaic org config validate gamma/); assert.match(items[1].text, /mosaic bus restart acme/); + assert.match(items[1].text, /2 cards dropped/); + assert.match(items[3].text, /Console/); assert.match(items[3].text, /Reply to: And beta\?/); + assert.equal(await f.b.evaluate('document.querySelectorAll("#triage-transcript button, #triage-transcript a, #triage-transcript input").length'), 0, 'no Run button or link in a card'); + assert.equal(await f.b.evaluate('[...document.querySelectorAll("#triage-drawer button")].some(x => /run/i.test(x.textContent))'), false); +}); + +test('item 3: each send answer has plain words, a refused send keeps the draft, and an unknown outcome is never resent', async t => { + const host = fakeHost({ running: true }); + const until = new Date(Date.now() + 2 * 3600000).toISOString(); + // The browser's own request is same-origin, so the 403 comes from a page stub over the native fetch. + const init = `(() => { const f = window.fetch.bind(window); window.fetch = (input, init) => (window.__force403 && input === '/api/triage/message') ? Promise.resolve(new Response('{"error":"read-only"}', { status: 403, headers: { 'content-type': 'application/json' } })) : f(input, init); })();`; + const f = await setup(t, { host, init }); + await open(f); + assert.equal(await f.b.evaluate('document.activeElement?.id'), 'triage-text', 'the box has focus when the drawer opens'); + let status = ''; + const draft = () => f.b.evaluate('document.querySelector("#triage-text").value'); + const refused = async (setupNext, pattern, label) => { + await setupNext(); + status = await sendAndWait(f, status); + assert.match(status, pattern, label); + assert.equal(await draft(), 'is acme healthy?', `${label}: the draft stays`); + }; + await type(f, 'is acme healthy?'); + await refused(() => { host.h.next = new TriageError('triage-no-route', 'x'); }, /Not sent.*no model route is set/i, '409'); + await refused(() => { const e = new TriageError('triage-over-cap', 'x'); e.until = until; host.h.next = e; }, new RegExp(`Not sent.*daily token cap.*${until.slice(0, 16)}`), '429'); + await refused(() => { host.h.next = new TriageError('triage-message-too-long', 'x'); }, /Not sent.*too long/i, '400'); + await refused(() => f.b.evaluate('window.__force403 = true'), /Not sent.*read-only/i, '403'); + await f.b.evaluate('window.__force403 = false'); + const before = host.h.sent.length; + await refused(() => { host.h.next = new Error('lost'); }, /may or may not have arrived/i, '503'); + assert.equal(host.h.sent.length, before + 1); + await sleep(POLL_MS + 1500); + assert.equal(host.h.sent.length, before + 1, 'an unknown outcome is not sent again'); + status = await sendAndWait(f, status); + assert.match(status, /^Sent/); + assert.equal(await draft(), '', 'a sent message clears the box'); + await f.wait('[...document.querySelectorAll("#triage-transcript > li")].some(li => li.dataset.from === "owner" && li.textContent.includes("is acme healthy?"))'); + // Ctrl+Enter sends too. + await type(f, 'second'); + await f.b.key('Enter', 'Enter', 2); + await f.wait('document.querySelector("#triage-text").value === "" && /^Sent/.test(document.querySelector("#triage-send-status").textContent)'); + assert.equal(host.h.sent.at(-1), 'second'); +}); + +test('item 3: a read-only Console shows no message box and says why', async t => { + const f = await setup(t, { send: false }); + await open(f); + assert.equal(await f.b.evaluate('document.querySelector("#triage-text")'), null); + assert.match(await f.text('#triage-send-off'), /read-only/i); +}); + +test('item 4: polling runs only while the drawer is open and stops on close', async t => { + const f = await setup(t, { host: fakeHost({ running: true }) }); + await f.wait('document.querySelector("#triage-open")'); + await sleep(1000); + assert.equal(f.triageReads(), 0); + await open(f); + await sleep(POLL_MS * 2 + 1000); + const open2 = f.triageReads(); + assert.ok(open2 >= 2, `reads while open: ${open2}`); + await f.click('#triage-drawer .x'); + await f.wait('!document.querySelector("#triage-drawer") || document.querySelector("#triage-drawer").hidden'); + assert.equal(await f.b.evaluate('document.activeElement?.id'), 'triage-open', 'focus goes back to the entry'); + const closed = f.triageReads(); + await sleep(POLL_MS * 2 + 1000); + assert.equal(f.triageReads(), closed, 'no read after close'); + // Escape closes it as well, and reopening reads again. + await open(f); + await f.b.evaluate('document.querySelector("#triage-text").focus()'); + await f.b.key('Escape'); + await f.wait('!document.querySelector("#triage-drawer") || document.querySelector("#triage-drawer").hidden'); +}); + +test('item 4: a poll keeps the draft and the cursor, and keeps the scroll position when the reader has scrolled up', async t => { + const transcript = Array.from({ length: 40 }, (_, i) => ({ at: at(60 - i), from: i % 2 ? 'triage' : 'owner', ...(i % 2 ? { text: `answer ${i}`, cards: [], dropped: 0 } : { id: `owner-${String(i).padStart(12, '0')}`, text: `question ${i}` }) })); + const host = fakeHost({ running: true, transcript }); + const f = await setup(t, { host, viewport: [1440, 700] }); + await open(f); + const scroller = 'document.querySelector("#triage-transcript")'; + // Opening lands on the newest line. + assert.equal(await f.b.evaluate(`(() => { const s = ${scroller}; return s.scrollHeight - s.scrollTop - s.clientHeight < 4; })()`), true); + await type(f, 'half a thought'); + await f.b.evaluate('document.querySelector("#triage-text").setSelectionRange(4, 4)'); + await f.b.evaluate(`${scroller}.scrollTop = 120`); + host.h.transcript = [...transcript, { at: at(0), from: 'host', text: 'a new line', in_reply_to: null }]; + await f.wait('document.querySelector("#triage-transcript").textContent.includes("a new line")', 300); + assert.equal(await f.b.evaluate(`${scroller}.scrollTop`), 120, 'scrolled up: the position stays'); + assert.equal(await f.b.evaluate('document.querySelector("#triage-text").value'), 'half a thought'); + assert.equal(await f.b.evaluate('document.activeElement?.id'), 'triage-text'); + assert.equal(await f.b.evaluate('document.querySelector("#triage-text").selectionStart'), 4); + // At the bottom, a new line scrolls into view. + await f.b.evaluate(`(() => { const s = ${scroller}; s.scrollTop = s.scrollHeight; })()`); + host.h.transcript = [...host.h.transcript, { at: at(0), from: 'host', text: 'one more line' }]; + await f.wait('document.querySelector("#triage-transcript").textContent.includes("one more line")', 300); + assert.equal(await f.b.evaluate(`(() => { const s = ${scroller}; return s.scrollHeight - s.scrollTop - s.clientHeight < 4; })()`), true); +}); + +test('item 5: markup and control characters in every field stay text: no element, no link, no script', async t => { + const BAD = 'linkbold'; + const CTRL = '\u0007\u001b[31m\u202eevil\u200b\u2028\ufeff'; + const v = s => `${BAD}${CTRL}${s}`; + const snapshot = { + snapshotVersion: 1, at: v('at'), console: { state: v('state'), at: v('cat') }, + proxy: { initialized: true, installed: true, active: v('active'), healthy: null, fence: false }, + systemConfig: { valid: false, exit: 2, code: v('code') }, + organizations: { count: 1, list: [{ id: v('org'), bus: { state: v('bus'), lastStart: { ok: false, at: v('ls') } }, processing: { halted: true, invalid: true }, config: { valid: false, exit: 2, code: v('oc') } }] }, + }; + const transcript = [ + { at: v('t1'), from: 'owner', id: v('id'), text: v('owner text') }, + { at: v('t2'), from: 'triage', in_reply_to: v('id'), text: v('triage text'), cards: [{ step: v('step'), org: v('corg'), command: v('cmd') }], dropped: v('dropped') }, + { at: v('t3'), from: 'host', in_reply_to: v('nope'), text: v('host text') }, + { at: v('t4'), from: v('from'), text: v('unknown sender') }, + ]; + const host = fakeHost({ running: true, transcript, snapshot, lastExit: { code: v('code'), signal: v('sig'), at: v('lat') }, overCapUntil: v('until') }); + const f = await setup(t, { host }); + await open(f); + await f.wait('document.querySelector("#triage-transcript > li")'); + const out = await f.b.evaluate(`(() => { + const d = document.querySelector('#triage-drawer'); + return { + pwned: window.__pwned ?? null, + tags: [...d.querySelectorAll('img, a, b, script, iframe, svg image, [onerror], [href]')].map(e => e.outerHTML), + text: d.textContent, + body: document.body.querySelectorAll('img[src="x"], a[href^="https://example.test"]').length, + }; + })()`); + assert.equal(out.pwned, null); + assert.deepEqual(out.tags, []); + assert.equal(out.body, 0); + for (const word of ['owner text', 'triage text', 'host text', 'cmd', 'corg', 'step', 'org', 'oc', 'code', 'active']) assert.ok(out.text.includes(word), `${word} shown as text`); + assert.ok(out.text.includes(' { reads.push(id); if (st.failRead) throw Object.assign(new Error('org-unavailable'), { code: 'org-unavailable' }); - const answer = { revision: st.revs[id], document: structuredClone(st.docs[id] ?? {}), templates: ['writer'] }; + const answer = { revision: st.revs[id], document: structuredClone(st.docs[id] ?? {}), templates: ['writer', 'triage'] }; const h = st.held.read; if (h) { st.held.read = null; await h; } return answer; }; @@ -976,6 +976,46 @@ test('SP17: while a Save is in flight the form takes no typing, and takes it aga assert.equal(await b.evaluate(`document.querySelector('${form} input[name="title"]').value`), 'Ship again'); }); +// #1873 triage-drawer item 6: the Triage template is system-only. The picker never offers it, and a step +// that names it is marked and named by the save check, as any role the organization cannot hold. +test('the step picker does not offer the triage template, and a step naming it is marked and refused before the bus', { timeout: 60000 }, async t => { + const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?step=1' }); + await wait(`!!document.querySelector('${form}')`, 'step 1 form'); + assert.equal(await b.evaluate(`document.querySelector('${form} input[name="role"][value="triage"]')`), null, 'not in the edit form'); + await b.evaluate(press('[data-wfg-add]')); + await wait(`!!document.querySelector('[data-wfg-add-form]')`, 'add form'); + assert.equal(await b.evaluate(`document.querySelector('[data-wfg-add-form] input[name="role"][value="triage"]')`), null, 'not in the add form'); + assert.doesNotMatch(await b.evaluate(text('[data-wfg-add-form] [data-wfg-roles-pick]')), /triage/); + await b.evaluate(press('[data-wfg-add-form] [data-wfg-cancel]')); + st.change('acme', doc => { doc.workflows.sorted = { steps: [{ title: 'Sort', state: 'todo', roles: ['triage'] }] }; }); + await b.evaluate(`location.hash = '#/orgs/acme/workflows/sorted?step=1'`); + await wait(`!!document.querySelector('${form}') && document.querySelectorAll('[data-wfg-graph] [data-wfg-missing]').length === 1`, 'triage marked in the graph'); + assert.match(await b.evaluate(text(`${form} [data-wfg-roles-pick]`)), /triage names no current role/); + await b.evaluate(fill(`${form} input[name="title"]`, 'Sort it')); + await b.evaluate(press('[data-wfg-save]')); + await wait(`/Step 1: triage names no current role/.test(${text('[data-wfg-status]')})`, 'refused on the page'); + assert.equal(st.writes.length, 0, 'nothing sent'); +}); + +// #1873 triage-drawer item 6: an add form in which only the state was changed is not closed without a word. +test('Save with only the state changed in the add form says so and keeps the form', { timeout: 60000 }, async t => { + const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=1' }); + await retitle(b, wait, 1, 'Build it'); + await b.evaluate(press('[data-wfg-add]')); + await wait(`!!document.querySelector('[data-wfg-add-form]')`, 'add form'); + await b.evaluate(`(()=>{const e=document.querySelector('[data-wfg-add-form] select[name="state"]');e.value='in-review';e.dispatchEvent(new Event('input',{bubbles:true}));return true})()`); + await b.evaluate(press('[data-wfg-bar] [data-wfg-save]')); + await wait(`/new step 2 is not added yet/.test(${text('[data-wfg-bar] [data-wfg-status]')})`, 'said in words'); + assert.equal(st.writes.length, 0, 'nothing written'); + assert.equal(await b.evaluate(`document.querySelector('[data-wfg-add-form] select[name="state"]')?.value`), 'in-review', 'the form is kept as set'); + // Cancel drops it; Save then saves the rest. + await b.evaluate(press('[data-wfg-add-form] [data-wfg-cancel]')); + await wait(`!document.querySelector('[data-wfg-add-form]')`, 'add form closed'); + await b.evaluate(press('[data-wfg-save]')); + await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'saved'); + assert.deepEqual(st.writes.at(-1).args.workflow.steps.map(s => s.title), ['Build it', 'Ship']); +}); + // SP17 review 2 P2-1: a new step typed in the add form is not dropped by the bar's Save: Save says it is not // added yet and keeps the form; once added, Save sends it. test('SP17: the bar Save with a new step typed in the add form says so and keeps it, and saves it once added', { timeout: 60000 }, async t => { -- 2.54.0 From fd300b4fe328b9e1380aba8d0308b11009d28c29 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Mon, 16 Nov 2026 14:51:27 -0600 Subject: [PATCH 2/3] fix(webui): triage drawer review, a scrolled-up reader keeps the line in view when the oldest lines drop at the 200-line cap, a failed start says the message is in the conversation and was not delivered, a read that turns sending off hides the box and keeps the draft, and the text cleaner removes every control, format, separator and invisible character (#1873, lane triage-drawer) The test helper opens the drawer after the page's first render has focused its heading, as a person would. A drawer opened before that loses focus to the heading (bus.js); that is left as a follow-up. --- packages/webui/src/public/display.js | 42 ++++++++--- .../tests/triage-drawer-browser.test.mjs | 70 +++++++++++++++++-- 2 files changed, 97 insertions(+), 15 deletions(-) diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index be5b7d9cb..082b759c1 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -7,14 +7,14 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( (() => { const systemFetch = window.fetch.bind(window); const POLL_MS = 4000; - // Control, direction and zero-width characters never reach the page; newline and tab stay. - // eslint-disable-next-line no-control-regex - const HIDDEN = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u180e\u2028\u2029\ufeff\u200b-\u200f\u202a-\u202e\u2066-\u2069]/g; + // Control, format (direction, zero-width, soft hyphen, word joiner, tag), separator and other invisible + // characters (fillers, variation selectors) never reach the page; newline and tab stay. + const HIDDEN = /(?![\n\t])[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\u034f\u115f\u1160\u180b-\u180d\u3164\ufe00-\ufe0f\uffa0\u{e0100}-\u{e01ef}]/gu; const clean = (value, max = 8000) => (typeof value === 'string' ? value : value === null || value === undefined ? '' : String(value)).replace(/\r\n?/g, '\n').replace(HIDDEN, '').slice(0, max); const when = value => window.MosaicLocalTime(clean(value, 64)); const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = clean(text); return n; }; const NO_ROUTE = 'No model route is set for Triage, so Triage will not start. The instance owner sets the route first.'; - let config = null, entry = null, drawer = null, parts = null, timer = null, gen = 0, sending = false, lastTranscript = '', lastHealth = ''; + let config = null, entry = null, drawer = null, parts = null, timer = null, gen = 0, sending = false, lastTranscript = '', lastHealth = '', shown = []; const read = () => systemFetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => (r.ok ? r.json() : null)).catch(() => null); read().then(c => { if (c && c.triage === true) { config = c; addEntry(); } }); @@ -57,14 +57,15 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( parts = { title, state, health, transcript, compose, box: null, send: null, status: null, off: null }; } - // The message box is built once and never rewritten by a read, so a draft survives every poll. + // The message box is built once and never rewritten or removed by a read, so a draft survives every + // poll. A read that turns sending off hides the box; one that turns it on again shows it. function composer(view) { const c = parts.compose; const canSend = config.triageSend === true && view.send === true; - if (!canSend) { - if (parts.box) { c.replaceChildren(); parts.box = parts.send = parts.status = null; } + const READ_ONLY = 'This Console is read-only, so messages cannot be sent from here.'; + if (!canSend && !parts.box) { if (!parts.off || !parts.off.isConnected) { parts.off = el('p', 'note triage-send-off'); parts.off.id = 'triage-send-off'; c.append(parts.off); } - parts.off.textContent = 'This Console is read-only, so messages cannot be sent from here.'; + parts.off.textContent = READ_ONLY; return; } if (!parts.box) { @@ -82,8 +83,10 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( const off = el('p', 'note triage-send-off'); off.id = 'triage-send-off'; const status = el('p', 'triage-send-status'); status.id = 'triage-send-status'; status.setAttribute('role', 'status'); c.append(label, box, off, row, status); - Object.assign(parts, { box, send, status, off }); + Object.assign(parts, { label, box, send, status, off, row }); } + for (const n of [parts.label, parts.box, parts.row]) n.hidden = !canSend; + if (!canSend) { parts.off.textContent = READ_ONLY; parts.box.disabled = parts.send.disabled = true; return; } // A route that is not set, or a session over its cap, turns the box off and says why. const until = typeof view.overCapUntil === 'string' && view.overCapUntil ? view.overCapUntil : null; const reason = view.route !== 'set' ? 'Sending is off: no model route is set for Triage.' @@ -179,11 +182,26 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( const key = JSON.stringify(list); if (key !== lastTranscript) { const first = lastTranscript === ''; + // The host keeps the newest 200 lines, so a new line can drop old ones from the top. A reader who + // has scrolled up keeps the line they are reading at the same place, not the same scroll number. + const edge = () => t.getBoundingClientRect().top; + let anchor = null; + if (!first && !atBottom) { + const i = [...t.children].findIndex(n => n.getBoundingClientRect().bottom > edge() + 1); + if (i >= 0 && shown[i] !== undefined) anchor = { key: shown[i], off: t.children[i].getBoundingClientRect().top - edge() }; + } lastTranscript = key; const owners = new Map(list.filter(m => m.from === 'owner' && typeof m.id === 'string').map(m => [m.id, clean(m.text)])); if (list.length) t.replaceChildren(...list.map(m => entryNode(m, owners))); else t.replaceChildren(el('li', 'triage-empty', 'No messages yet.')); - t.scrollTop = first || atBottom ? t.scrollHeight : top; + shown = list.map(m => JSON.stringify(m)); + if (first || atBottom) t.scrollTop = t.scrollHeight; + else { + t.scrollTop = top; + const j = anchor ? shown.indexOf(anchor.key) : -1; + if (j >= 0) t.scrollTop += t.children[j].getBoundingClientRect().top - edge() - anchor.off; + else if (anchor) t.scrollTop = 0; + } } } @@ -224,6 +242,10 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( function answer(status, body) { const code = body && typeof body.error === 'string' ? body.error : ''; if (status === 202) return { sent: true, text: 'Sent. Triage answers in the conversation above.' }; + // These come after the host wrote the message, with its "did not start" line under it. + if (code === 'triage-route-invalid' || code === 'triage-start-failed') return { text: `Not delivered: ${code === 'triage-start-failed' ? 'the Triage session did not start' : 'Triage did not start because the model route\'s answer is not usable'}. The message is in the conversation with the Console's note; it was not sent again.` }; + // This one can come before or after the message is written. + if (code === 'triage-dir-unsafe') return { text: 'Not delivered: a Triage directory is not safe to use, so Triage did not start. It was not sent again: check the conversation before you send it again.' }; if (status === 409) return { text: code === 'triage-no-route' ? 'Not sent: no model route is set for Triage. The instance owner sets the route first.' : code === 'triage-route-refused' ? 'Not sent: the model route refused to start Triage.' : 'Not sent: the model route\'s answer is not usable.' }; if (status === 429) { if (code === 'triage-over-cap') { diff --git a/packages/webui/tests/triage-drawer-browser.test.mjs b/packages/webui/tests/triage-drawer-browser.test.mjs index 69e774d53..4a1634a92 100644 --- a/packages/webui/tests/triage-drawer-browser.test.mjs +++ b/packages/webui/tests/triage-drawer-browser.test.mjs @@ -8,7 +8,7 @@ import assert from 'node:assert/strict'; import { fileURLToPath } from 'node:url'; import { startServer } from '../src/serve.mjs'; import { createDevOwner } from '../src/dev-owner.mjs'; -import { TriageError } from '../src/triage-host.mjs'; +import { TriageError, NOT_STARTED } from '../src/triage-host.mjs'; import { capMessage, NO_ROUTE_MESSAGE } from '../src/triage-http.mjs'; import { browser } from './browser.mjs'; import { close } from './fixture.mjs'; @@ -55,6 +55,8 @@ const SNAPSHOT = () => ({ }); // The fake host. `h` is the state the next read returns; `h.next` is an error the next message throws. +// An error marked `recorded` throws after the owner line and the host's "did not start" line are written, +// as the real host does when the session fails to start. function fakeHost(over = {}) { const h = { route: 'set', running: false, lastExit: null, overCapUntil: null, snapshot: SNAPSHOT(), transcript: [], reads: 0, sent: [], next: null, ...over }; let n = 0; @@ -65,9 +67,10 @@ function fakeHost(over = {}) { message: async text => { h.sent.push(text); const e = h.next; h.next = null; - if (e) throw e; + if (e && !e.recorded) throw e; const m = { id: `owner-${String(++n).padStart(12, '0')}`, at: new Date().toISOString() }; h.transcript = [...h.transcript, { at: m.at, from: 'owner', id: m.id, text }]; + if (e) { h.transcript = [...h.transcript, { at: new Date().toISOString(), from: 'host', in_reply_to: m.id, text: NOT_STARTED }]; throw e; } return m; }, }; @@ -93,7 +96,9 @@ async function setup(t, { host = fakeHost(), triage = host.triage, send = true, return { b, base, wait, text, click, requests, triageReads, h: host.h }; } -const open = async f => { await f.wait('document.querySelector("#triage-open")'); await f.click('#triage-open'); await f.wait('["off", "cap", "running", "stopped"].includes(document.querySelector("#triage-drawer #triage-state")?.dataset.kind)'); }; +// The page focuses its heading when its first render ends (bus.js). Open after that, as a person would, or +// that late focus can land after the drawer's own. +const open = async f => { await f.wait('document.querySelector("#triage-open")'); await f.wait('document.activeElement?.tagName === "H1"', 100).catch(() => {}); await f.click('#triage-open'); await f.wait('["off", "cap", "running", "stopped"].includes(document.querySelector("#triage-drawer #triage-state")?.dataset.kind)'); }; const type = async (f, words) => { await f.b.evaluate('document.querySelector("#triage-text").focus()'); await f.b.call('Input.insertText', { text: words }); }; const sendAndWait = async (f, before) => { await f.click('#triage-send'); await f.wait(`document.querySelector("#triage-send-status").textContent.trim() && document.querySelector("#triage-send-status").textContent !== ${JSON.stringify(before)} && !document.querySelector("#triage-send").disabled`); return f.text('#triage-send-status'); }; @@ -260,6 +265,45 @@ test('item 3: a read-only Console shows no message box and says why', async t => assert.match(await f.text('#triage-send-off'), /read-only/i); }); +test('item 3: a send that reached the conversation but did not start Triage says so, not "Not sent", and keeps the draft', async t => { + const host = fakeHost(); + const f = await setup(t, { host }); + await open(f); + let status = ''; + for (const [code, words] of [['triage-start-failed', /session did not start/i], ['triage-route-invalid', /route's answer is not usable/i]]) { + await f.b.evaluate('document.querySelector("#triage-text").value = ""'); + await type(f, `try ${code}`); + const e = new TriageError(code, 'x'); e.recorded = true; host.h.next = e; + status = await sendAndWait(f, status); + assert.doesNotMatch(status, /^Not sent/, code); + assert.match(status, /Not delivered/, code); + assert.match(status, words, code); + assert.match(status, /in the conversation/i, code); + assert.equal(await f.b.evaluate('document.querySelector("#triage-text").value'), `try ${code}`, `${code}: the draft stays`); + await f.wait(`document.querySelector("#triage-transcript").textContent.includes(${JSON.stringify(NOT_STARTED)})`, 300); + } + // A directory refusal can come before or after the message is written, so the words cover both. + host.h.next = new TriageError('triage-dir-unsafe', 'x'); + status = await sendAndWait(f, status); + assert.match(status, /Not delivered.*not safe to use.*check the conversation/i); +}); + +test('item 3: a read that turns sending off hides the box and keeps the draft; one that turns it on again shows it', async t => { + const init = `(() => { const f = window.fetch.bind(window); window.fetch = (input, init) => (window.__sendOff && input === '/api/triage') ? f(input, init).then(r => r.json()).then(j => new Response(JSON.stringify({ ...j, send: false }), { status: 200, headers: { 'content-type': 'application/json' } })) : f(input, init); })();`; + const f = await setup(t, { host: fakeHost({ running: true }), init }); + await open(f); + await type(f, 'keep me'); + await f.b.evaluate('window.__sendOff = true'); + await f.wait('/read-only/i.test(document.querySelector("#triage-send-off")?.textContent || "")', 300); + const off = await f.b.evaluate('(() => { const x = document.querySelector("#triage-text"); return x && { value: x.value, hidden: x.hidden, disabled: x.disabled, send: document.querySelector("#triage-send").disabled, shown: x.getClientRects().length > 0 }; })()'); + assert.deepEqual(off, { value: 'keep me', hidden: true, disabled: true, send: true, shown: false }); + await f.b.evaluate('window.__sendOff = false'); + await f.wait('document.querySelector("#triage-text").getClientRects().length > 0', 300); + assert.equal(await f.b.evaluate('document.querySelector("#triage-text").value'), 'keep me'); + assert.equal(await f.b.evaluate('document.querySelector("#triage-text").disabled'), false); + assert.equal(await f.text('#triage-send-off'), ''); +}); + test('item 4: polling runs only while the drawer is open and stops on close', async t => { const f = await setup(t, { host: fakeHost({ running: true }) }); await f.wait('document.querySelector("#triage-open")'); @@ -306,9 +350,25 @@ test('item 4: a poll keeps the draft and the cursor, and keeps the scroll positi assert.equal(await f.b.evaluate(`(() => { const s = ${scroller}; return s.scrollHeight - s.scrollTop - s.clientHeight < 4; })()`), true); }); +test('item 4: at the 200-line cap the oldest lines drop, and a scrolled-up reader keeps the same line in view', async t => { + const line = i => ({ at: new Date(Date.now() - (300 - i) * 60000).toISOString(), from: 'host', text: `line ${i}` }); + const transcript = Array.from({ length: 200 }, (_, i) => line(i)); + const host = fakeHost({ running: true, transcript }); + const f = await setup(t, { host, viewport: [1440, 700] }); + await open(f); + const firstInView = `(() => { const s = document.querySelector("#triage-transcript"), top = s.getBoundingClientRect().top; const li = [...s.children].find(n => n.getBoundingClientRect().bottom > top + 1); return { text: li.textContent, off: Math.round(li.getBoundingClientRect().top - top) }; })()`; + await f.b.evaluate('document.querySelector("#triage-transcript").scrollTop = 600'); + const before = await f.b.evaluate(firstInView); + host.h.transcript = [...transcript.slice(3), line(200), line(201), line(202)]; + await f.wait('document.querySelector("#triage-transcript").textContent.includes("line 202")', 300); + const after = await f.b.evaluate(firstInView); + assert.equal(after.text, before.text, 'the same line is first in view'); + assert.ok(Math.abs(after.off - before.off) <= 1, `at the same place: ${before.off} then ${after.off}`); +}); + test('item 5: markup and control characters in every field stay text: no element, no link, no script', async t => { const BAD = 'linkbold'; - const CTRL = '\u0007\u001b[31m\u202eevil\u200b\u2028\ufeff'; + const CTRL = '\u0007\u001b[31m\u202eevil\u200b\u2028\ufeff\u00ad\u2060\u034f\ufe0f\u{E0041}\u{E0100}'; const v = s => `${BAD}${CTRL}${s}`; const snapshot = { snapshotVersion: 1, at: v('at'), console: { state: v('state'), at: v('cat') }, @@ -341,7 +401,7 @@ test('item 5: markup and control characters in every field stay text: no element for (const word of ['owner text', 'triage text', 'host text', 'cmd', 'corg', 'step', 'org', 'oc', 'code', 'active']) assert.ok(out.text.includes(word), `${word} shown as text`); assert.ok(out.text.includes(' Date: Mon, 16 Nov 2026 15:04:49 -0600 Subject: [PATCH 3/3] fix(webui): triage drawer re-check notes, a scrolled-up reader keeps the right one of two identical lines in view, the unsafe-directory answer no longer says Triage did not start since it can come while a session runs, and the text cleaner removes every default-ignorable character (#1873, lane triage-drawer) --- packages/webui/src/public/display.js | 17 +++++++++++------ .../webui/tests/triage-drawer-browser.test.mjs | 12 ++++++++---- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/packages/webui/src/public/display.js b/packages/webui/src/public/display.js index 082b759c1..c6acace7f 100644 --- a/packages/webui/src/public/display.js +++ b/packages/webui/src/public/display.js @@ -7,9 +7,9 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( (() => { const systemFetch = window.fetch.bind(window); const POLL_MS = 4000; - // Control, format (direction, zero-width, soft hyphen, word joiner, tag), separator and other invisible + // Control, format (direction, zero-width, soft hyphen, word joiner, tag), separator and default-ignorable // characters (fillers, variation selectors) never reach the page; newline and tab stay. - const HIDDEN = /(?![\n\t])[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\u034f\u115f\u1160\u180b-\u180d\u3164\ufe00-\ufe0f\uffa0\u{e0100}-\u{e01ef}]/gu; + const HIDDEN = /(?![\n\t])[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/gu; const clean = (value, max = 8000) => (typeof value === 'string' ? value : value === null || value === undefined ? '' : String(value)).replace(/\r\n?/g, '\n').replace(HIDDEN, '').slice(0, max); const when = value => window.MosaicLocalTime(clean(value, 64)); const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = clean(text); return n; }; @@ -188,17 +188,22 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( let anchor = null; if (!first && !atBottom) { const i = [...t.children].findIndex(n => n.getBoundingClientRect().bottom > edge() + 1); - if (i >= 0 && shown[i] !== undefined) anchor = { key: shown[i], off: t.children[i].getBoundingClientRect().top - edge() }; + if (i >= 0 && shown[i] !== undefined) anchor = { i, key: shown[i], off: t.children[i].getBoundingClientRect().top - edge() }; } lastTranscript = key; const owners = new Map(list.filter(m => m.from === 'owner' && typeof m.id === 'string').map(m => [m.id, clean(m.text)])); if (list.length) t.replaceChildren(...list.map(m => entryNode(m, owners))); else t.replaceChildren(el('li', 'triage-empty', 'No messages yet.')); - shown = list.map(m => JSON.stringify(m)); + const next = list.map(m => JSON.stringify(m)); + // Lines only drop from the top and add at the bottom, so the anchor moves up by the number dropped. + // That finds the right one of two identical lines; anything else falls back to the first match. + const fits = d => shown.length - d <= next.length && shown.slice(d).every((k, n) => next[n] === k); + let j = -1; + if (anchor) { let d = 0; while (d <= anchor.i && !fits(d)) d += 1; j = d <= anchor.i ? anchor.i - d : next.indexOf(anchor.key); } + shown = next; if (first || atBottom) t.scrollTop = t.scrollHeight; else { t.scrollTop = top; - const j = anchor ? shown.indexOf(anchor.key) : -1; if (j >= 0) t.scrollTop += t.children[j].getBoundingClientRect().top - edge() - anchor.off; else if (anchor) t.scrollTop = 0; } @@ -245,7 +250,7 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date( // These come after the host wrote the message, with its "did not start" line under it. if (code === 'triage-route-invalid' || code === 'triage-start-failed') return { text: `Not delivered: ${code === 'triage-start-failed' ? 'the Triage session did not start' : 'Triage did not start because the model route\'s answer is not usable'}. The message is in the conversation with the Console's note; it was not sent again.` }; // This one can come before or after the message is written. - if (code === 'triage-dir-unsafe') return { text: 'Not delivered: a Triage directory is not safe to use, so Triage did not start. It was not sent again: check the conversation before you send it again.' }; + if (code === 'triage-dir-unsafe') return { text: 'Not delivered: a Triage directory is not safe to use. It was not sent again: check the conversation before you send it again.' }; if (status === 409) return { text: code === 'triage-no-route' ? 'Not sent: no model route is set for Triage. The instance owner sets the route first.' : code === 'triage-route-refused' ? 'Not sent: the model route refused to start Triage.' : 'Not sent: the model route\'s answer is not usable.' }; if (status === 429) { if (code === 'triage-over-cap') { diff --git a/packages/webui/tests/triage-drawer-browser.test.mjs b/packages/webui/tests/triage-drawer-browser.test.mjs index 4a1634a92..dca0f8965 100644 --- a/packages/webui/tests/triage-drawer-browser.test.mjs +++ b/packages/webui/tests/triage-drawer-browser.test.mjs @@ -286,6 +286,7 @@ test('item 3: a send that reached the conversation but did not start Triage says host.h.next = new TriageError('triage-dir-unsafe', 'x'); status = await sendAndWait(f, status); assert.match(status, /Not delivered.*not safe to use.*check the conversation/i); + assert.doesNotMatch(status, /did not start/i, 'this one can come while a session runs'); }); test('item 3: a read that turns sending off hides the box and keeps the draft; one that turns it on again shows it', async t => { @@ -350,25 +351,28 @@ test('item 4: a poll keeps the draft and the cursor, and keeps the scroll positi assert.equal(await f.b.evaluate(`(() => { const s = ${scroller}; return s.scrollHeight - s.scrollTop - s.clientHeight < 4; })()`), true); }); -test('item 4: at the 200-line cap the oldest lines drop, and a scrolled-up reader keeps the same line in view', async t => { +test('item 4: at the 200-line cap the oldest lines drop, and a scrolled-up reader keeps the same lines in view, even with an identical line above', async t => { const line = i => ({ at: new Date(Date.now() - (300 - i) * 60000).toISOString(), from: 'host', text: `line ${i}` }); const transcript = Array.from({ length: 200 }, (_, i) => line(i)); + transcript[4] = transcript[8]; // an identical twin of the line that is first in view const host = fakeHost({ running: true, transcript }); const f = await setup(t, { host, viewport: [1440, 700] }); await open(f); - const firstInView = `(() => { const s = document.querySelector("#triage-transcript"), top = s.getBoundingClientRect().top; const li = [...s.children].find(n => n.getBoundingClientRect().bottom > top + 1); return { text: li.textContent, off: Math.round(li.getBoundingClientRect().top - top) }; })()`; + const firstInView = `(() => { const s = document.querySelector("#triage-transcript"), top = s.getBoundingClientRect().top; const li = [...s.children].find(n => n.getBoundingClientRect().bottom > top + 1); return { text: li.textContent, second: li.nextElementSibling.textContent, off: Math.round(li.getBoundingClientRect().top - top) }; })()`; await f.b.evaluate('document.querySelector("#triage-transcript").scrollTop = 600'); const before = await f.b.evaluate(firstInView); + assert.match(before.text, /line 8$/, 'the twin line is the one in view'); host.h.transcript = [...transcript.slice(3), line(200), line(201), line(202)]; await f.wait('document.querySelector("#triage-transcript").textContent.includes("line 202")', 300); const after = await f.b.evaluate(firstInView); assert.equal(after.text, before.text, 'the same line is first in view'); + assert.equal(after.second, before.second, 'and the same line follows it'); assert.ok(Math.abs(after.off - before.off) <= 1, `at the same place: ${before.off} then ${after.off}`); }); test('item 5: markup and control characters in every field stay text: no element, no link, no script', async t => { const BAD = 'linkbold'; - const CTRL = '\u0007\u001b[31m\u202eevil\u200b\u2028\ufeff\u00ad\u2060\u034f\ufe0f\u{E0041}\u{E0100}'; + const CTRL = '\u0007\u001b[31m\u202eevil\u200b\u2028\ufeff\u00ad\u2060\u034f\ufe0f\u{E0041}\u{E0100}\u{E0002}\u17b4\ufff0'; const v = s => `${BAD}${CTRL}${s}`; const snapshot = { snapshotVersion: 1, at: v('at'), console: { state: v('state'), at: v('cat') }, @@ -401,7 +405,7 @@ test('item 5: markup and control characters in every field stay text: no element for (const word of ['owner text', 'triage text', 'host text', 'cmd', 'corg', 'step', 'org', 'oc', 'code', 'active']) assert.ok(out.text.includes(word), `${word} shown as text`); assert.ok(out.text.includes('