diff --git a/changelog.d/added-15862-matrix-display.md b/changelog.d/added-15862-matrix-display.md new file mode 100644 index 0000000000..4f75b12c1e --- /dev/null +++ b/changelog.d/added-15862-matrix-display.md @@ -0,0 +1 @@ +- Add experimental, opt-in Matrix Rain and Cascade displays at `?kiosk=1&view=matrix`, with pause, reduced-motion paging, source and freshness labels, and authorized line fetching; the normal tracker is unchanged (#15936, RFC #15862). diff --git a/src/pkg/dashboard/matrix_ui_test.go b/src/pkg/dashboard/matrix_ui_test.go new file mode 100644 index 0000000000..acad70fb52 --- /dev/null +++ b/src/pkg/dashboard/matrix_ui_test.go @@ -0,0 +1,144 @@ +package dashboard + +import ( + "os" + "os/exec" + "strings" + "testing" +) + +func TestMatrixUIWiring(t *testing.T) { + html := indexHTML(t) + read := func(name string) string { + t.Helper() + b, err := os.ReadFile("static-src/" + name) + if err != nil { + t.Fatal(err) + } + return string(b) + } + js := read("js/matrix.js") + for _, forbidden := range []string{"innerHTML", "insertAdjacentHTML", "document.write", "new EventSource"} { + if strings.Contains(js, forbidden) { + t.Errorf("matrix.js contains forbidden sink/stream %q", forbidden) + } + } + for _, want := range []string{"visibilitychange", "prefers-reduced-motion: reduce", "cancelAnimationFrame", "text.textContent = line.line", "source.addEventListener('code-lines'", "hive.matrix.", "mx."} { + if !strings.Contains(js, want) { + t.Errorf("matrix.js missing %q", want) + } + } + for _, want := range []string{"window.HIVE_MATRIX = kiosk && view === 'matrix';", "if(window.HIVE_MATRIX){", "hiveMatrixStart();", "if (window.HIVE_MATRIX) window.hiveMatrixAttach(source);"} { + if !strings.Contains(html, want) { + t.Errorf("generated page missing %q", want) + } + } + css := read("css/matrix.css") + for _, rule := range strings.Split(css, "}") { + selector, _, ok := strings.Cut(strings.TrimSpace(rule), "{") + if !ok { + continue + } + for _, part := range strings.Split(selector, ",") { + if !strings.HasPrefix(strings.TrimSpace(part), "body.matrix-mode ") { + t.Errorf("unscoped Matrix selector %q", part) + } + } + } + manifest := read("manifest.txt") + for _, file := range []string{"js/matrix.js", "css/matrix.css"} { + if !strings.Contains(manifest, file+"\n") { + t.Errorf("manifest missing %s", file) + } + if !strings.Contains(html, read(file)) { + t.Errorf("generated page is missing current %s", file) + } + } +} + +// Exercise browser lifecycle and pull behavior with deterministic DOM/clock +// doubles. No browser dependencies, network or real animation timers required. +func TestMatrixUIBehavior(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node unavailable") + } + cmd := exec.Command(node, "-e", matrixBrowserTest) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("Matrix browser behavior: %v\n%s", err, out) + } +} + +const matrixBrowserTest = ` +const assert = require('assert'); +const fs = require('fs'); +const vm = require('vm'); +const matrix = fs.readFileSync('static-src/js/matrix.js', 'utf8'); +const boot = fs.readFileSync('static-src/js/boot.js', 'utf8').split('})();')[0] + '})();'; +async function scenario(query, reduced = false, status = 200) { + const events = {}, docEvents = {}, raf = new Map(), timers = new Map(), requests = [], draws = []; + let id = 0, responseStatus = status, responseSeq = 1; + const context = {clearRect(){}, fillRect(){}, fillText(...a){draws.push(a)}, drawImage(...a){draws.push(a)}}; + const elements = []; + function el(tag) { const e = {tagName: tag.toUpperCase(), children: [], style: {setProperty(){}}, + classList: {add(){}}, setAttribute(){}, append(...a){this.children.push(...a)}, + appendChild(a){this.children.push(a)}, replaceChildren(...a){this.children = a}, getContext(){return context}}; + elements.push(e); return e; } + const body = el('body'); + const doc = {body, hidden: false, createElement: el, + getElementById(id){return elements.find(e => e.id === id)}, + addEventListener(n, fn){(docEvents[n] ||= []).push(fn)}}; + const motion = {matches: reduced, addEventListener(n, fn){this.change = fn}}; + const win = {location: {href: 'https://hive.test/' + query}, innerWidth: 800, innerHeight: 600, + matchMedia(){return motion}, addEventListener(){}}; + const c = vm.createContext({window: win, document: doc, URL, location: {hash: '#activity'}, + history: {replaceState(){}}, localStorage: {getItem(){return null}, setItem(){}}, + requestAnimationFrame(fn){raf.set(++id, fn); return id}, cancelAnimationFrame(i){raf.delete(i)}, + setTimeout(fn){timers.set(++id, fn); return id}, clearTimeout(i){timers.delete(i)}, setInterval(){}, dashboardSetInterval(){}, + fetch(url){requests.push(url); return Promise.resolve({status: responseStatus, ok: responseStatus === 200, + json(){return Promise.resolve({seq: responseSeq, lines: [{line: '', repo: 'org/repo', pr: 2, path: 'main.go', at: new Date().toISOString()}]})}})}, + Date, Math}); + vm.runInContext(matrix, c); c.hiveMatrixStart = win.hiveMatrixStart; + vm.runInContext(boot, c); + for (const fn of docEvents.DOMContentLoaded || []) fn(); + const flush = async () => {for(let i=0;i<12;i++) await Promise.resolve()}; + await flush(); + if (!win.HIVE_MATRIX) {assert.equal(requests.length, 0); assert(!doc.getElementById('hive-matrix')); return;} + const byClass = n => elements.find(e => e.className === n); + assert.equal(requests[0], '/api/matrix/lines?since=0'); + assert(byClass('matrix-labels').children[0].textContent.includes('public allowlisted repos')); + if (status !== 200) { + assert.equal(raf.size, 0); assert(byClass('matrix-canvas').hidden); + assert(byClass('matrix-notice').textContent.includes(status === 404 ? 'not enabled' : 'Sign in')); + return; + } + if (reduced) { + assert.equal(raf.size, 0); + assert.equal(byClass('matrix-list').children[0].children[1].textContent, ''); + assert(timers.size > 0); + } else { + assert.equal(raf.size, 1); + for (const time of [1, 100]) {const fn = [...raf.values()][0]; raf.clear(); fn(time)} + assert(draws.length > 0); + if (query.includes('cascade')) assert(draws.some(a => a[0] === 'org/repo#2 · main.go')); + } + doc.hidden = true; docEvents.visibilitychange.forEach(fn => fn()); + assert.equal(raf.size, 0); assert.equal(timers.size, 0); + assert.equal(byClass('matrix-labels').children[2].textContent, 'paused'); + doc.hidden = false; docEvents.visibilitychange.forEach(fn => fn()); await flush(); + docEvents.keydown[0]({key: 'p', target: el('body'), preventDefault(){}}); + assert.equal(raf.size, 0); assert.equal(timers.size, 0); + win.hiveMatrixAttach({addEventListener(n, fn){events[n] = fn}}); + responseSeq = 2; events['code-lines'](); await flush(); + assert.equal(requests.at(-1), '/api/matrix/lines?since=1'); + responseStatus = 403; events['code-lines'](); await flush(); + assert(byClass('matrix-canvas').hidden); assert.equal(byClass('matrix-list').children.length, 0); +} +(async () => { + await scenario(''); await scenario('?view=matrix'); await scenario('?kiosk=1'); + await scenario('?kiosk=1&view=matrix'); + await scenario('?kiosk=1&view=matrix&mx.effect=cascade'); + await scenario('?kiosk=1&view=matrix', true); + for (const status of [404, 401, 403]) await scenario('?kiosk=1&view=matrix', false, status); +})().catch(e => {console.error(e); process.exit(1)}); +` diff --git a/src/pkg/dashboard/static-src/css/matrix.css b/src/pkg/dashboard/static-src/css/matrix.css new file mode 100644 index 0000000000..b14b667319 --- /dev/null +++ b/src/pkg/dashboard/static-src/css/matrix.css @@ -0,0 +1,16 @@ +body.matrix-mode #hive-dashboard-root { display: none !important; } +body.matrix-mode #hive-matrix { + --matrix-bg: #000804; + --matrix-fg: #52ed86; + --matrix-surface: #000000; + --matrix-text: #e8f5eb; + --matrix-muted: #b8ccbb; + position: fixed; inset: 0; z-index: 100000; background: var(--matrix-bg); color: var(--matrix-color, var(--matrix-fg)); font: 16px monospace; +} +body.matrix-mode .matrix-canvas { width: 100%; height: 100%; } +body.matrix-mode .matrix-labels { position: absolute; bottom: 1rem; left: 1rem; right: 1rem; padding: var(--sp-3); background: var(--matrix-surface); color: var(--matrix-text); font-size: var(--fs-base); overflow-wrap: anywhere; } +body.matrix-mode .matrix-notice { position: absolute; top: 2rem; left: 1rem; right: 1rem; color: var(--matrix-text); } +body.matrix-mode .matrix-list { position: absolute; inset: 4rem 1rem 8rem; overflow: hidden; } +body.matrix-mode .matrix-list pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: .3rem 0 1rem; } +body.matrix-mode .matrix-list small { color: var(--matrix-muted); } +body.matrix-mode #hive-matrix [hidden] { display: none !important; } diff --git a/src/pkg/dashboard/static-src/js/boot.js b/src/pkg/dashboard/static-src/js/boot.js index 27296dde7a..608cd96c34 100644 --- a/src/pkg/dashboard/static-src/js/boot.js +++ b/src/pkg/dashboard/static-src/js/boot.js @@ -34,8 +34,13 @@ // shared chrome-less layout in css/popout.css keys on (full screen adds it at // runtime); popout-mode and display-mode keep their view-specific rules. (function(){ - var kiosk=false, popout=false, display=false, sound=true, density='', shift=false; - try { var u=new URL(window.location.href); kiosk=u.searchParams.get('kiosk')==='1'; popout=u.searchParams.get('popout')==='1'; display=u.searchParams.get('display')==='1'; density=u.searchParams.get('density')==='tv'?'tv':''; shift=u.searchParams.get('shift')==='1'; sound=new URL(window.location.href).searchParams.get('sound')!=='off'; } catch(e) {} + var kiosk=false, popout=false, display=false, view='', sound=true, density='', shift=false; + try { var u=new URL(window.location.href); kiosk=u.searchParams.get('kiosk')==='1'; view=u.searchParams.get('view'); popout=u.searchParams.get('popout')==='1'; display=u.searchParams.get('display')==='1'; density=u.searchParams.get('density')==='tv'?'tv':''; shift=u.searchParams.get('shift')==='1'; sound=new URL(window.location.href).searchParams.get('sound')!=='off'; } catch(e) {} + window.HIVE_MATRIX = kiosk && view === 'matrix'; + if(window.HIVE_MATRIX){ + document.body.classList.add('matrix-mode'); + document.addEventListener('DOMContentLoaded', function(){ typeof hiveMatrixStart === 'function' && hiveMatrixStart(); }); + } window.HIVE_KIOSK=kiosk; window.HIVE_POPOUT=popout&&!kiosk; window.HIVE_DISPLAY=display&&!kiosk; diff --git a/src/pkg/dashboard/static-src/js/matrix.js b/src/pkg/dashboard/static-src/js/matrix.js new file mode 100644 index 0000000000..4275299dc4 --- /dev/null +++ b/src/pkg/dashboard/static-src/js/matrix.js @@ -0,0 +1,205 @@ +// Matrix is an opt-in display only. Content always comes from the authorized +// pull endpoint; the shared SSE stream carries a content-free nudge. +(function(){ + 'use strict'; + var pull = function(){}; + window.hiveMatrixAttach = function(source){ + if (!window.HIVE_MATRIX) return; + source.addEventListener('code-lines', function(){ pull(); }); + source.addEventListener('open', function(){ pull(); }); + }; + window.hiveMatrixStart = function(){ + if (!window.HIVE_MATRIX || document.getElementById('hive-matrix')) return; + var params = new URL(window.location.href).searchParams; + function option(name, fallback){ + var value = params.get('mx.' + name); + try { + if (value === null) value = localStorage.getItem('hive.matrix.' + name); + else localStorage.setItem('hive.matrix.' + name, value); + } catch(e) {} + return value === null ? fallback : value; + } + function number(name, fallback, min, max){ + var value = Number(option(name, String(fallback))); + return Number.isFinite(value) ? Math.max(min, Math.min(max, value)) : fallback; + } + var effect = option('effect', 'rain') === 'cascade' ? 'cascade' : 'rain'; + var speed = number('speed', 1, 0.1, 5), fps = number('fps', 30, 1, 60); + var palette = option('palette', 'green'); + var colors = {green: '#52ed86', amber: '#ffb347', gold: '#ffd700'}; + var color = colors[palette] || colors.green; + var root = document.createElement('main'); + root.id = 'hive-matrix'; + root.style.setProperty('--matrix-color', color); + document.body.appendChild(root); + function element(tag, className, text){ + var el = document.createElement(tag); + el.className = className; + if (text) el.textContent = text; + root.appendChild(el); + return el; + } + var canvas = element('canvas', 'matrix-canvas'); + canvas.setAttribute('aria-label', 'Pushed code lines · Matrix ' + effect); + var list = element('div', 'matrix-list'); + var notice = element('p', 'matrix-notice', 'Waiting for pushed lines…'); + notice.setAttribute('role', 'status'); + var labels = element('div', 'matrix-labels'); + var source = document.createElement('div'); + source.textContent = 'Source: lines pushed by hive · public allowlisted repos'; + var freshness = document.createElement('div'); + var pausedLabel = document.createElement('div'); + labels.append(source, freshness, pausedLabel); + var ctx = canvas.getContext('2d'); + var motion = window.matchMedia('(prefers-reduced-motion: reduce)'); + var lines = [], lastSeq = 0, lastAt = 0, startedAt = Date.now(); + var enabled = false, manualPause = false, loading = false, pending = false; + var frame = 0, previous = 0, page = 0, pageTimer = 0, drops = []; + var atlas = document.createElement('canvas'), glyphs = new Map(); + var width = 0, height = 0, cell = 20; + function paused(){ return manualPause || document.hidden; } + function resize(){ + width = window.innerWidth; height = window.innerHeight; + canvas.width = width; canvas.height = height; + drops = []; + } + function clearContent(message){ + enabled = false; lines = []; drops = []; glyphs.clear(); + lastSeq = 0; lastAt = 0; + list.replaceChildren(); ctx.clearRect(0, 0, width, height); + notice.textContent = message; + sync(); + } + function updateLabels(){ + var minutes = Math.floor(Math.max(0, Date.now() - (lastAt || startedAt)) / 60000); + freshness.textContent = minutes >= 10 ? 'stale · no new lines for ' + minutes + 'm' : + (lastAt ? 'last line ' + (minutes ? minutes + 'm ago' : 'just now') : 'waiting for first line'); + pausedLabel.textContent = paused() ? 'paused' : 'p / Space to pause'; + } + function caption(line){ return line.repo + '#' + line.pr + ' · ' + line.path; } + function staticPage(){ + list.replaceChildren(); + var latest = lines.slice(-60).reverse(); + if (page * 8 >= latest.length) page = 0; + latest.slice(page * 8, page * 8 + 8).forEach(function(line){ + var row = document.createElement('div'); + var label = document.createElement('small'); + label.textContent = caption(line); + var text = document.createElement('pre'); + text.textContent = line.line; + row.append(label, text); list.appendChild(row); + }); + } + function buildAtlas(){ + // Bounded by the same latest-line window as the renderer. No synthetic + // characters: every glyph in a column belongs to an incoming line. + glyphs.clear(); + lines.forEach(function(line){ Array.from(line.line).forEach(function(g){ + if (!glyphs.has(g)) glyphs.set(g, glyphs.size); + }); }); + atlas.width = 64 * cell; + atlas.height = Math.max(cell, Math.ceil(glyphs.size / 64) * cell); + var ac = atlas.getContext('2d'); + ac.font = '16px monospace'; ac.fillStyle = color; + glyphs.forEach(function(i, g){ ac.fillText(g, (i % 64) * cell, Math.floor(i / 64) * cell + 16); }); + } + function spawn(x){ + var line = lines[Math.floor(Math.random() * lines.length)]; + return {x: x, y: -Math.random() * height, speed: 25 + Math.random() * 65, + line: line, chars: Array.from(line.line)}; + } + function draw(now){ + frame = 0; + if (paused() || motion.matches || !enabled) return; + if (!previous) previous = now; + var elapsed = now - previous; + if (elapsed >= 1000 / fps) { + previous = now; + var dt = Math.min(elapsed, 100) / 1000 * speed; + ctx.fillStyle = effect === 'rain' ? 'rgba(0, 8, 4, 0.18)' : '#000804'; + ctx.fillRect(0, 0, width, height); + ctx.font = '16px monospace'; + if (lines.length) { + var count = effect === 'rain' ? Math.ceil(width / cell) : 12; + while (drops.length < count) drops.push(spawn(effect === 'rain' ? drops.length * cell : Math.random() * width * 0.5)); + drops.forEach(function(drop, i){ + drop.y += drop.speed * dt; + if (drop.y > height + 40) { drops[i] = spawn(drop.x); return; } + if (effect === 'cascade') { + ctx.fillStyle = color; ctx.fillText(drop.line.line, drop.x, drop.y, width - drop.x); + ctx.fillStyle = '#b8ccbb'; ctx.font = '12px monospace'; + ctx.fillText(caption(drop.line), drop.x, drop.y + 18, width - drop.x); + ctx.font = '16px monospace'; + } else if (drop.chars.length) { + var g = drop.chars[Math.floor(drop.y / cell + drop.chars.length * 100) % drop.chars.length]; + var index = glyphs.get(g); + if (index !== undefined) ctx.drawImage(atlas, (index % 64) * cell, Math.floor(index / 64) * cell, cell, cell, drop.x, drop.y, cell, cell); + ctx.fillStyle = '#effff2'; ctx.fillText(g, drop.x, drop.y + 16); + } + }); + } + } + frame = requestAnimationFrame(draw); + } + function sync(){ + if (frame) cancelAnimationFrame(frame); + frame = 0; previous = 0; + clearTimeout(pageTimer); pageTimer = 0; + updateLabels(); + canvas.hidden = motion.matches || !enabled; + list.hidden = !motion.matches || !enabled; + if (!enabled || paused()) return; + if (motion.matches) { + staticPage(); + pageTimer = setTimeout(function(){ page++; sync(); }, 15000); + } else frame = requestAnimationFrame(draw); + } + pull = function(){ + if (loading) { pending = true; return; } + loading = true; pending = false; + fetch('/api/matrix/lines?since=' + lastSeq, {cache: 'no-store', credentials: 'same-origin'}) + .then(function(response){ + if (response.status === 404) { clearContent('Matrix mode is not enabled on this hive'); return null; } + if (response.status === 401 || response.status === 403) { clearContent('Sign in with permission to read Matrix lines'); return null; } + if (!response.ok) throw new Error('Matrix pull failed'); + return response.json(); + }).then(function(data){ + if (!data) return; + var incoming = (Array.isArray(data.lines) ? data.lines : []).filter(function(line){ return typeof line.line === 'string'; }); + var seq = Number(data.seq) || 0; + // A restarted hive can reset its sequence; replace the old backlog. + if (seq < lastSeq) { lines = []; drops = []; } + if (seq !== lastSeq && incoming.length) { + var at = Date.parse(incoming[incoming.length - 1].at); + lastAt = Number.isFinite(at) ? at : Date.now(); + } + lastSeq = seq; + lines = lines.concat(incoming).slice(-120); + enabled = true; + notice.textContent = lines.length ? '' : 'Waiting for pushed lines…'; + if (!motion.matches) buildAtlas(); + sync(); + }).catch(function(){ clearContent('Matrix lines unavailable · retrying'); }) + .finally(function(){ loading = false; if (pending) pull(); }); + }; + document.addEventListener('visibilitychange', function(){ sync(); if (!document.hidden) pull(); }); + document.addEventListener('keydown', function(event){ + if (event.ctrlKey || event.metaKey || event.altKey || event.repeat || + /INPUT|TEXTAREA|SELECT/.test(event.target.tagName) || event.target.isContentEditable) return; + if (event.key === 'p' || event.key === 'P' || event.code === 'Space') { + event.preventDefault(); manualPause = !manualPause; sync(); + } + }); + motion.addEventListener('change', function(){ + ctx.clearRect(0, 0, width, height); + if (!motion.matches) buildAtlas(); + sync(); + }); + window.addEventListener('resize', resize); + resize(); sync(); pull(); + // Recover from missed nudges, endpoint activation and transient failures. + if (typeof dashboardSetInterval === 'function') { + dashboardSetInterval('matrix-poll', function(){ updateLabels(); if (!document.hidden) pull(); }, 30000); + } + }; +})(); diff --git a/src/pkg/dashboard/static-src/js/sse-bootstrap.js b/src/pkg/dashboard/static-src/js/sse-bootstrap.js index fae30573c3..7c013f8bc7 100644 --- a/src/pkg/dashboard/static-src/js/sse-bootstrap.js +++ b/src/pkg/dashboard/static-src/js/sse-bootstrap.js @@ -28,6 +28,7 @@ if (_eventSource) { _eventSource.onerror = null; _eventSource.onmessage = null; _eventSource.close(); _eventSource = null; } const source = new EventSource('/api/events'); _eventSource = source; + if (window.HIVE_MATRIX) window.hiveMatrixAttach(source); _sseOpenedAtMs = Date.now(); _sseLastFrameAtMs = 0; const conn = document.getElementById('conn'); diff --git a/src/pkg/dashboard/static-src/manifest.txt b/src/pkg/dashboard/static-src/manifest.txt index 73d3d76d35..788fee616f 100644 --- a/src/pkg/dashboard/static-src/manifest.txt +++ b/src/pkg/dashboard/static-src/manifest.txt @@ -33,8 +33,10 @@ css/welcome.css css/review-campaigns.css css/kiosk.css css/popout.css +css/matrix.css css/variables.css glue/style-close-body-open.html +js/matrix.js js/boot.js glue/boot-script-close.html html/auth.html diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 9f59abe610..804c03ae55 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -6966,6 +6966,22 @@ body.display-shift #activity-monitor-section { animation: none; } body.display-mode #activity-monitor-panel, body.display-mode #activity-monitor-meta, body.display-mode #activity-monitor-sticky, body.display-mode #activity-monitor-native-queue { transition: none; } } +body.matrix-mode #hive-dashboard-root { display: none !important; } +body.matrix-mode #hive-matrix { + --matrix-bg: #000804; + --matrix-fg: #52ed86; + --matrix-surface: #000000; + --matrix-text: #e8f5eb; + --matrix-muted: #b8ccbb; + position: fixed; inset: 0; z-index: 100000; background: var(--matrix-bg); color: var(--matrix-color, var(--matrix-fg)); font: 16px monospace; +} +body.matrix-mode .matrix-canvas { width: 100%; height: 100%; } +body.matrix-mode .matrix-labels { position: absolute; bottom: 1rem; left: 1rem; right: 1rem; padding: var(--sp-3); background: var(--matrix-surface); color: var(--matrix-text); font-size: var(--fs-base); overflow-wrap: anywhere; } +body.matrix-mode .matrix-notice { position: absolute; top: 2rem; left: 1rem; right: 1rem; color: var(--matrix-text); } +body.matrix-mode .matrix-list { position: absolute; inset: 4rem 1rem 8rem; overflow: hidden; } +body.matrix-mode .matrix-list pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: .3rem 0 1rem; } +body.matrix-mode .matrix-list small { color: var(--matrix-muted); } +body.matrix-mode #hive-matrix [hidden] { display: none !important; } .var-empty{color:var(--muted);font-size:var(--fs-sm);padding:var(--sp-2) var(--sp-0)} .var-section{margin-top:var(--sp-6);border-top:1px solid var(--border);padding-top:var(--sp-5)} .var-heading{font-weight:600;font-size:var(--fs-sm);margin-bottom:var(--sp-4)} @@ -6983,6 +6999,211 @@