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('