diff --git a/docs/requirements/004-radio-set.md b/docs/requirements/004-radio-set.md index 4da0de0..e2ce466 100644 --- a/docs/requirements/004-radio-set.md +++ b/docs/requirements/004-radio-set.md @@ -53,6 +53,16 @@ that someone transmits without the speech engine loading a busy host. Silence also pauses music and the station (not part of 004's scope); Silence also mutes the procedure word (an emergency call could go unheard). +11. **Short windows** (operator-picked 2026-11-14): a window too short for + the two-column radio uses the stacked phone flow instead of a further + packed tier: `#main` keeps its full height under the header, the radio + sits in the page flow above it and the page scrolls; "only History + scrolls" holds only on the two-column side. The two-column side needs, + measured in all six states in Chromium and Firefox with MAYDAY: 45rem + (720 px) high from 80rem (1280 px) wide, 46.5rem (744 px) from 61rem + (976 px) wide and 61rem (976 px) from 48rem (768 px) wide. Rejected: one + height for every width (61rem would stack a 1366 × 768 laptop, 44rem + misses the Orbit stage under MAYDAY by up to 20 px), a third packed tier. ## Approach @@ -146,6 +156,146 @@ flowchart TD sender → recipient and text; a click opens the full message. - [x] Tab, chips and search survive a reload in the same browser. +### Layout and history rows (operator 2026-11-14) + +- [ ] The radio shows a Device card on the left (display line, Auto, Quiet + and Silence, the six level sliders one per row with label, slider, + value and test button, the internet stations folded in a details) and, + on the right, the Speak card above the History card. +- [ ] Every knob label starts at the same x position (one label column). +- [ ] At 1920, 1366, 960 and 390 px the document's `scrollWidth` is at most + `innerWidth`, and no element of the radio reaches outside its card. +- [ ] In the Stream view inside the radio only the history row list has + `scrollHeight` above `clientHeight`, with `overflow-y: auto`, + `scrollbar-width: thin` and a `scrollbar-color` from the palette; + `#main` carries a palette `scrollbar-color` as well, so Firefox draws + no light scrollbar beside a squeezed view. +- [ ] At 390 px the cards stack in the order Device, Speak, History and the + page scrolls; on the two-column side of decision 11, tablets included, + the Device card sits left and the Speak card above the History card on + the right, with the radio bar above Speak. +- [ ] On the two-column side the open radio takes at most 46vh. At + 1280 × 720, 1366 × 768, 1440 × 900, 1536 × 864, 1920 × 1080, + 1024 × 768, 1680 × 1050, 820 × 1180, 768 × 1024 and at the band + edges 800 × 976, 960 × 976, 976 × 744, 1024 × 744 and 1366 × 720, in + the two-column layout, in the Stream view and in the Orbit fit view, + idle, with + the internet radio fold open on three stations, with a recorded voice + note attached, while the radio speaks a real reading and under the + MAYDAY banner with a short and with a 295-character text: `#main` is + at least + `0.54 × innerHeight − top of the radio spot` px high (what the old + 46vh spot cap left), the document is no wider and no taller than the + viewport, the history list is the only scroller inside the radio and + at least 60 px high with two whole rows, the Device and Speak cards + show whole, the Orbit stage keeps at least 12 % of the viewport + height, and the centre of every visible control, the RX/TX lamp, the + CPU field and the Device title resolves by `elementFromPoint` to + itself. +- [ ] The internet radio fold opens its stations as a popover anchored to + the fold toggle and off the layout flow, at most `min(12rem, 28vh)` + high and scrolling inside itself beyond that. It opens upward over + the level sliders when the room above holds it and downward + otherwise, and never grows past the room on its side, so its box + stays inside the viewport and inside every clipping ancestor, in the + spot and on the Home tiles at every width, and it shows at least one + whole station row. The global menu handlers close it like every + `details.menu`: Escape and a click outside close it. A menu hands the + focus back to its toggle only when the focus was inside it; a click + elsewhere never moves the focus, and a History tab or chip keeps the + focus across the redraw its click causes. The controls the popover + covers while open are the only ones exempt from the centre check. +- [ ] An attached voice note sits in the composer row: beside the message + field in the packed layout, beside Record and PTT otherwise; it never + takes height from the history list. In the packed layout a Play/Pause + button of at least 24 × 24 px plays it in place of the native player, + and the Attach checkbox keeps the visible label "Attach". +- [ ] The speaking caption covers no control and no lamp: in the packed + layout it shows over the class and mode fields of the display, between + the RX/TX lamp and the CPU field, names the speaker without the word + "speaking", keeps the spoken line at least 4rem wide with an ellipsis, + and its Stop speaking button stays clickable at 24 × 24 px. +- [ ] Under the MAYDAY banner the open radio keeps the `#main` floor and the + 12 % Orbit stage: in the packed layout a fit view + with the open radio pads `#main` by 12 px and the shell bottom by + 16 px instead of 24 px and 32 px. The banner keeps one line at any + text length: the text ends in an ellipsis, carries the full text in + its title and in the alert region, and Cancel mayday stays visible. + The state poll redraws the banner only when the MAYDAY changes: an + unchanged MAYDAY causes no mutation in the alert region and keeps the + focus on Cancel mayday, and a changed text replaces the banner + content once, so it is announced once. +- [ ] On the two-column side up to 66rem (1056 px) high, and below 56rem + (896 px) wide at any height, the radio packs + tighter instead of scrolling: the display sits in the Device head row, + the six level sliders keep one 24 px row each, the Speak card holds + title, star, channel and recipient in one row (DOM order equals screen + order) and message, voice note, Record and PTT in the next (the + channel hint moves into the channel's title), and the History search + sits in the History head row, each where its card is wide enough; a + narrower card wraps them into the next rows. The History filter chips + wrap beside the Clear filters button, never above it. +- [ ] Below 48rem wide and below the heights of decision 11 every view, fit + or not, gives the view below the stacked radio the full height under + the header: the page scrolls, the Orbit stage keeps at least 24 % of + the viewport height, the page never scrolls sideways, the History + chips never overlap its tabs or search, and every radio control + resolves to itself once page scroll brings it into view. At 800 × 600, + 1024 × 600, 1280 × 600 and 1366 × 657 this holds in the six states. +- [ ] A closed radio spot takes no box at any width, and closing it in a + fit view gives the Orbit stage its height back. +- [ ] Every history row has the same height, below two text lines, with + `white-space: nowrap`; a long text shows an ellipsis (`scrollWidth` + above `clientWidth`) and every row keeps at least 30 px of text. +- [ ] The reader and acknowledger avatars of a row sit after the text inside + the row box and overlap each other with at least 10 px of each face in + view; a History card wider than 34rem shows at most eight faces and + `+N` for the rest, a narrower one at most three and `+N`. +- [ ] A click on a row opens the hub popup with the full text, sender, + recipient, class, time and every reader with name, read time ("read + about" for a sighting, "read, time unknown" without one) and + acknowledgement, without a stray text node. +- [ ] A redraw of the History card patches it in place: rows keep their + node by a key unique in the log (the ledger id of a sent row, else + time, sender and the occurrence index among rows of the same time and + sender), and tabs and chips keep theirs, so a focused row button or + tab keeps the focus across new radio rows and the minute tick, Enter + on it opens its own message even beside a twin of the same time and + sender, and a redraw that changes no tab fires no `focusin`. When a + filter, search or time range removes the focused row, the focus moves + to the nearest remaining row, else to the list. +- [ ] Copy in the popup writes the full message text through + `navigator.clipboard.writeText`; the button's text and accessible name + turn to "Copied" or "Not copied", and a polite status region inside the + popup says the result in words. +- [ ] Reply closes the popup and prefills the Speak card of the same radio: + channel Post, recipient the sender, focus in the message field. A row + of a pinned Home tile fills the composer of that tile, else a pinned + Home Speak or Radio tile, and opens the radio spot only when Home holds + no composer. +- [ ] Esc and a click outside the popup close it. +- [ ] The whole radio, the Device card, the Speak card and the History card + each carry a Home star (`radio`, `radio-device`, `radio-speak`, + `radio-log`) that covers no control. +- [ ] Each pinned part renders on Home as a live instance without ids or + stars of its own: a new radio row appears in the pinned History and + Radio tiles without a reload, and a mode pressed in the pinned Device + tile shows in every radio display. +- [ ] The pinned whole radio carries the Read aloud filters and Cancel + mayday of the spot; Cancel mayday lifts an active mayday from Home + after the confirmation and the passkey. +- [ ] A new pin gets its panel's own size: Radio 12 × 7, Device 6 × 6, + Speak 6 × 5, History 6 × 5 cells. At that size and after a resize to + 12 × 9, 5 × 7, 7 × 6 and 8 × 4 cells, a pinned History or two column + Radio tile at 1920, 1366, 960 and 390 px has the history list as its + only scroller, inside the tile and at least two rows high, and a + Device or Speak tile has none; a Radio tile at 390 px stacks its cards + and scrolls its tile body as its only scroller, its list unscrolled. +- [ ] Every composer keeps its own draft, recording, voice note and Attach + box: a new composer starts empty, a send from one never clears + another's recording, and Record in one composer stops a recording + running in another, whose transcript and note stay in that other one. + ### Tests - **Unit**: gate busy, unknown, cache hit and open; threshold validation; @@ -157,4 +307,22 @@ flowchart TD - **E2E**: Playwright in Chromium and Firefox at 1920, 1366 and 390 px: mode buttons, burst through a spy on the AudioContext, procedure word under load, the settings dialog without a radio section, the log tabs and - filters. + filters; `tests/e2e/test_radio_layout_e2e.py` measures the layout, the + popup, Copy, Reply, the Home tiles and the fit view at 1920, 1366, 960 + and 390 px, the open radio in Stream and Orbit at the nine screen sizes, + the five band-edge sizes and the four short sizes of the layout criteria, + each against the contract of its side of decision 11, in six + states on the real code paths (idle, stations open, a recorded voice + note, a real reading through the mocked synthesizer, MAYDAY banner with a + short and a long text) after the view transition settles, the station + popover's placement, whole rows, Escape and outside click in the spot and + on the Home tiles at 1366, 1280 and 390 px, and where the focus lands + after mouse presses on a History tab and on blank `#main` with Day/Night + or the stations open at 1366 and 390 px in both browsers, the focus on + a keyboard-focused row button and tab across new rows and a forced minute + tick, focus and Enter on two rows of the same time and sender, the focus + of a row a filter or the search removes, and the banner's alert region + across two polls with an unchanged and a changed MAYDAY at 1366 px in + both browsers, and drives + two composers, Reply and Cancel mayday from Home copies in Chromium at + 1366 and 390 px. diff --git a/orchestrator/templates/index.html.j2 b/orchestrator/templates/index.html.j2 index 39abc2e..1a90de3 100644 --- a/orchestrator/templates/index.html.j2 +++ b/orchestrator/templates/index.html.j2 @@ -59,9 +59,9 @@ h1 { margin: 0; font-size: var(--fs-lg); font-weight: 680; letter-spacing: -.01e .badge.urgent { background: var(--accent); color: var(--on-accent); } .badge.alarm { background: var(--alarm); color: #fff; } .tools { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 6px; } -.banner { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-3); padding: var(--sp-2) var(--sp-5); background: var(--alarm); color: #fff; font-weight: 650; } +.banner { display: flex; align-items: center; gap: var(--sp-3); padding: var(--sp-2) var(--sp-5); background: var(--alarm); color: #fff; font-weight: 650; } .banner[hidden] { display: none; } -.banner .text { flex: 1; margin: 0; } +.banner .text { flex: 1; min-width: 0; margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .banner .btn { border-color: rgb(255 255 255 / 70%); background: transparent; color: #fff; } .menu { position: relative; } .menu > summary { display: inline-flex; align-items: center; gap: 6px; padding: 5px 12px; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--panel); font-weight: 580; cursor: pointer; list-style: none; } @@ -212,6 +212,7 @@ body.pane .shell { display: flex; flex: 1; flex-direction: column; min-height: 0 body.pane main { flex: 1; min-height: 0; overflow: auto; } body.fit .shell, body.fit main, body.fit .graph, body.fit .stage-card, body.fit .stage { display: flex; flex: 1; flex-direction: column; min-height: 0; } body.fit main { padding-bottom: var(--sp-5); } +body.fit .stage > .empty { min-height: 0; overflow: auto; } body.fit .stage svg, body.fit .stage canvas.space, body.fit .graph3d { flex: 1; height: auto; min-height: 0; max-height: none; } .legend { display: flex; flex-wrap: wrap; gap: 6px 16px; padding: 6px 10px 4px; color: var(--muted); font-size: var(--fs-sm); } .legend span { display: inline-flex; align-items: center; gap: 6px; } diff --git a/orchestrator/templates/page-board.js b/orchestrator/templates/page-board.js index 0caab6c..f3e5679 100644 --- a/orchestrator/templates/page-board.js +++ b/orchestrator/templates/page-board.js @@ -79,35 +79,18 @@ spotDom.toggle.setAttribute("aria-expanded", String(open)); window.requestAnimationFrame(refresh3d); if (open) { - spotDom.text.focus(); + spotDom.speak.text.focus(); } } - function toggleGear() { - const open = spotDom.gearBox.hidden; - spotDom.gearBox.replaceChildren(...(open ? [radioFilters()] : [])); - spotDom.gearBox.hidden = !open; - spotDom.gear.setAttribute("aria-expanded", String(open)); - window.requestAnimationFrame(refresh3d); - } - function radioSpot() { - const {form, recipient, text} = composerForm(); - const gearBox = h("div", {class: "radio-gear", id: "radio-gear", hidden: true}); - const gear = iconBtn("bi-funnel", "Read aloud", "btn small ghost spot-toggle", toggleGear, "Read aloud: the classes and agents the radio sounds for"); - gear.setAttribute("aria-expanded", "false"); - gear.setAttribute("aria-controls", "radio-gear"); - const [, label, , hint] = actionOf("clear-mayday"); - const clear = iconBtn("bi-life-preserver", label, "btn small danger", () => confirmAct("clear-mayday", []), hint); - const {face, log, station} = radioSide(); - const panel = h("section", {class: "card radio-spot", id: "radio-spot", "aria-label": "Radio", hidden: !ui.spot}, - h("div", {class: "spot-head"}, h("h3", {class: "group-title"}, "Radio"), h("span", {class: "spacer"}), gear, clear), face, gearBox, - h("div", {class: "spot-body"}, h("div", {class: "radio-side"}, form, station), log)); + const {bar, speak, grid} = radioBody(true); + const panel = h("section", {class: "card radio-spot", id: "radio-spot", "data-panel": "radio", "aria-label": "Radio", hidden: !ui.spot}, bar.root, grid); const toggle = document.getElementById("radio-open"); toggle.setAttribute("aria-expanded", String(ui.spot)); toggle.addEventListener("click", () => openSpot(!ui.spot)); document.getElementById("spot-host").replaceChildren(panel); - spotDom = {panel, toggle, gear, gearBox, text, clear, recipient, names: ""}; + spotDom = {panel, toggle, speak}; } function openRadio() { @@ -115,13 +98,8 @@ } function drawSpot() { - spotDom.clear.disabled = !state.silence; - const names = agentNames(); - if (JSON.stringify(names) !== spotDom.names) { - spotDom.names = JSON.stringify(names); - const chosen = spotDom.recipient.value; - spotDom.recipient.replaceChildren(...names.map((name) => h("option", {value: name, selected: name === chosen}, name))); - } + drawBars(); + drawSpeak(); } function agentsToolbar() { diff --git a/orchestrator/templates/page-boot.js b/orchestrator/templates/page-boot.js index 2fb2d88..7e98bc9 100644 --- a/orchestrator/templates/page-boot.js +++ b/orchestrator/templates/page-boot.js @@ -16,7 +16,8 @@ document.getElementById("palette-open").addEventListener("click", openPalette); document.getElementById("settings-open").addEventListener("click", settingsSheet); document.getElementById("bubbles-toggle").addEventListener("click", toggleBubbles); - document.addEventListener("click", (event) => closeMenus(event.target instanceof Element ? event.target.closest("details.menu") : null)); + document.addEventListener("click", (event) => closeMenus(event.target instanceof Element ? event.target.closest(MENUS) : null)); + document.addEventListener("scroll", placeStations, {capture: true, passive: true}); document.addEventListener("fullscreenchange", () => { if (!document.fullscreenElement) { document.body.classList.remove("leitstand"); @@ -36,6 +37,7 @@ window.addEventListener("resize", redrawSky); window.addEventListener("resize", refresh3d); window.addEventListener("resize", placePopup); + window.addEventListener("resize", placeStations); skyPanel(); radioSpot(); radio.element = radioElement(); diff --git a/orchestrator/templates/page-composer.js b/orchestrator/templates/page-composer.js index 86cbd93..296ab41 100644 --- a/orchestrator/templates/page-composer.js +++ b/orchestrator/templates/page-composer.js @@ -9,7 +9,7 @@ mayday: "MAYDAY: all agents pause writing steps until you cancel it.", }; const VOICE_POLL = 700; - const composer = {voice: "", recorder: null, timer: 0, started: 0}; + const composer = {live: null}; function confirmMayday() { return window.confirm("Send a mayday to all? All agents pause writing steps until you cancel it."); @@ -36,10 +36,25 @@ } function attachVoice(parts, note) { - composer.voice = note; + parts.voice = note; parts.attach.checked = false; parts.replay.hidden = !note; - parts.replay.replaceChildren(...(note ? [icon("bi-soundwave"), h("span", {class: "muted"}, "Voice message"), voiceReplay(note), h("label", {class: "check"}, parts.attach, "Attach recording"), iconBtn("bi-trash", "Remove recording", "btn small ghost", () => attachVoice(parts, ""))] : [])); + const audio = note ? voiceReplay(note) : null; + parts.replay.replaceChildren(...(note ? [icon("bi-soundwave"), h("span", {class: "muted voice-words"}, "Voice message"), audio, playToggle(audio), h("label", {class: "check"}, parts.attach, h("span", {}, "Attach", h("span", {class: "voice-words"}, " recording"))), iconBtn("bi-trash", "Remove recording", "btn small ghost", () => attachVoice(parts, ""))] : [])); + } + + function playToggle(audio) { + const button = iconBtn("bi-play-fill", "Play voice message", "btn small ghost voice-play", () => (audio.paused ? audio.play().catch((error) => toast("Playback failed", [String(error)], false)) : audio.pause())); + const show = () => { + const label = audio.paused ? "Play voice message" : "Pause voice message"; + button.setAttribute("aria-label", label); + button.title = label; + button.querySelector("use").setAttribute("href", audio.paused ? "#bi-play-fill" : "#bi-pause-fill"); + }; + for (const kind of ["play", "pause", "ended"]) { + audio.addEventListener(kind, show); + } + return button; } async function heardNote(note) { @@ -92,13 +107,20 @@ parts.record.replaceChildren(icon(on ? "bi-stop-fill" : "bi-record-circle"), on ? "Stop" : "Record"); } - function stopRecording() { - if (composer.recorder && composer.recorder.state === "recording") { - composer.recorder.stop(); + function stopRecording(parts) { + if (parts && parts.recorder && parts.recorder.state === "recording") { + parts.recorder.stop(); + } + } + + function freeMicrophone(parts) { + if (composer.live && composer.live !== parts) { + stopRecording(composer.live); } } async function startRecording(parts) { + freeMicrophone(parts); let media = null; try { media = await navigator.mediaDevices.getUserMedia({audio: {channelCount: 1, echoCancellation: true, noiseSuppression: true}}); @@ -115,19 +137,24 @@ }); recorder.addEventListener("stop", () => { media.getTracks().forEach((track) => track.stop()); - window.clearInterval(composer.timer); - composer.recorder = null; + window.clearInterval(parts.timer); + parts.recorder = null; + if (composer.live === parts) { + composer.live = null; + } recordLabel(parts, false); keepRecording(new Blob(chunks, {type: recorder.mimeType}), parts); }, {once: true}); - Object.assign(composer, {recorder, started: Date.now()}); + freeMicrophone(parts); + Object.assign(parts, {recorder, started: Date.now()}); + composer.live = parts; recorder.start(); recordLabel(parts, true); - composer.timer = window.setInterval(() => { - const seconds = Math.floor((Date.now() - composer.started) / 1000); + parts.timer = window.setInterval(() => { + const seconds = Math.floor((Date.now() - parts.started) / 1000); parts.status.textContent = `Recording ${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")} of at most ${state.speech.seconds} s`; if (seconds >= state.speech.seconds) { - stopRecording(); + stopRecording(parts); } }, 250); } @@ -136,33 +163,31 @@ const channel = h("select", {class: "field"}, CHANNELS.map(([id, label]) => h("option", {value: id}, label))); const recipient = h("select", {class: "field"}); const toField = h("label", {}, "To", recipient); - const text = h("textarea", {"aria-label": "Message", placeholder: "Message to the agents …", maxlength: 20000, on: {input: (event) => { - ui.draft = event.target.value; - }}}); - text.value = ui.draft; + const text = h("textarea", {"aria-label": "Message", placeholder: "Message to the agents …", maxlength: 20000}); const replay = h("div", {class: "voice-note", hidden: true}); - const hint = h("p", {class: "muted"}); + const hint = h("span", {class: "muted composer-hint"}); const status = h("span", {class: "muted composer-status", "aria-live": "polite"}); const record = h("button", {type: "button", class: "btn small", "aria-pressed": "false", title: "Record: one click starts, another stops; the hub transcribes, you check the text before sending"}); const submit = h("button", {type: "submit", class: "btn primary ptt", title: "PTT: push to transmit the message; your passkey signs it"}, icon("bi-broadcast-pin"), "PTT"); const attach = h("input", {type: "checkbox", title: "Attach recording: the agents get the path of the sound file; otherwise only the checked text goes out"}); - const parts = {record, status, text, replay, attach}; + const parts = {record, status, text, replay, attach, voice: "", recorder: null, timer: 0, started: 0}; recordLabel(parts, false); const gap = micGap(); if (gap) { record.disabled = true; record.title = `Record: ${gap}`; } - record.addEventListener("click", () => (composer.recorder ? stopRecording() : startRecording(parts))); + record.addEventListener("click", () => (parts.recorder ? stopRecording(parts) : startRecording(parts))); const sync = () => { const direct = TO_ONE.some(([id]) => id === channel.value); toField.hidden = !direct; hint.textContent = `${CHANNEL_HINTS[channel.value]} Your passkey signs every message.`; + channel.title = hint.textContent; }; channel.addEventListener("change", sync); sync(); - const form = h("form", {class: "composer"}, h("div", {class: "composer-grid"}, h("label", {}, "Channel", channel), toField), text, replay, hint, - h("div", {class: "actions"}, record, status, h("span", {class: "spacer"}), submit)); + const form = h("form", {class: "composer"}, h("div", {class: "composer-grid"}, h("label", {}, "Channel", channel), toField), text, replay, + h("div", {class: "actions"}, record, status, hint, submit)); form.addEventListener("submit", async (event) => { event.preventDefault(); const direct = TO_ONE.some(([id]) => id === channel.value); @@ -174,14 +199,13 @@ return; } submit.disabled = true; - if (await radioSend({to: direct ? recipient.value : "*", text: text.value, upload: "", cls: channel.value, voice: attach.checked ? composer.voice : ""})) { + if (await radioSend({to: direct ? recipient.value : "*", text: text.value, upload: "", cls: channel.value, voice: attach.checked ? parts.voice : ""})) { text.value = ""; - ui.draft = ""; status.textContent = ""; attachVoice(parts, ""); } submit.disabled = false; }); - attachVoice(parts, composer.voice); - return {form, recipient, text}; + attachVoice(parts, ""); + return {form, recipient, text, channel}; } diff --git a/orchestrator/templates/page-dom.js b/orchestrator/templates/page-dom.js index 7ba8f7d..3ce9f28 100644 --- a/orchestrator/templates/page-dom.js +++ b/orchestrator/templates/page-dom.js @@ -137,10 +137,16 @@ return button; } + const MENUS = "details.menu, details.radio-station"; + function closeMenus(keep) { - for (const menu of document.querySelectorAll("details.menu[open]")) { - if (menu !== keep) { + for (const menu of document.querySelectorAll(MENUS)) { + if (menu.open && menu !== keep) { + const inside = menu.contains(document.activeElement); menu.open = false; + if (inside) { + menu.querySelector("summary").focus({preventScroll: true}); + } } } } diff --git a/orchestrator/templates/page-home.js b/orchestrator/templates/page-home.js index 6ab341a..6db3494 100644 --- a/orchestrator/templates/page-home.js +++ b/orchestrator/templates/page-home.js @@ -1,8 +1,7 @@ const HOME_PATH = "home.pins"; const HOME_FETCH = 3000; const HOME_MESSAGE = 30000; - const HOME_RADIO = 12; - const HOME_MARKS = [['section[aria-label="Radio log"]', "radio-log"], ['section[aria-label="Recently sent"]', "radio-log"]]; + const HOME_MARKS = [['section[aria-label="Recently sent"]', "radio-log"]]; const homeView = {dom: null, pins: [], tiles: new Map(), hosts: new Map(), messages: new Map(), drag: null, mark: () => null, touched: false, fetched: {}}; const homeStore = Panels.store(typeof ViewStore === "object" && ViewStore ? ViewStore : Panels.memory(), HOME_PATH); const homePins = () => homeView.pins; @@ -58,12 +57,10 @@ return entry ? h("ol", {class: "feed"}, eventRow(entry)) : null; } - function homeRadio() { - const rows = state.radio.slice(-HOME_RADIO).reverse(); - return rows.length ? h("ul", {class: "mini"}, rows.map((row) => h("li", {}, - h("div", {class: "row"}, klass(row.class), when(row.ts)), - h("span", {class: "muted"}, `${dash(row.from)} → ${targetsOf(row)}`), - h("span", {}, short(row.text))))) : h("p", {class: "muted"}, "No radio in the chosen time range yet."); + function homeRadio(id) { + const host = homeView.hosts.get(id) || radioPart(id); + homeView.hosts.set(id, host); + return host; } function homeTree(draw) { @@ -142,7 +139,10 @@ } Panels.panel("stream", "Stream", homeStream); - Panels.panel("radio-log", "Radio log", homeRadio); + Panels.panel("radio-log", "Radio log", () => homeRadio("radio-log"), "", [6, 5]); + Panels.panel("radio", "Radio", () => homeRadio("radio"), "", [12, 7]); + Panels.panel("radio-device", "Radio: device", () => homeRadio("radio-device"), "", [6, 6]); + Panels.panel("radio-speak", "Radio: speak", () => homeRadio("radio-speak"), "", [6, 5]); Panels.panel("agents/orbit", "Agents: Orbit", homeOrbit); Panels.panel("agents/chord", "Agents: Chord", () => chord()); Panels.panel("agents/swimlane", "Agents: Swimlane", () => swimlane()); diff --git a/orchestrator/templates/page-radioview.js b/orchestrator/templates/page-radioview.js index 96d4434..8e05016 100644 --- a/orchestrator/templates/page-radioview.js +++ b/orchestrator/templates/page-radioview.js @@ -7,7 +7,10 @@ }; const TAB_LABELS = {sent: ["bi-arrow-up-right", "Sent", "Sent: what you transmitted"], received: ["bi-arrow-down-left", "Received", "Received: radio to you or to all"], all: ["bi-journal-text", "All", "All: every radio row the hub logs"]}; const CHIP_LABELS = {class: "Class", from: "Sender", to: "Recipient", agent: "Agent"}; - let radioDom = null; + const COPIED = 1600; + const FOLDED_READERS = 3; + const radioParts = {bars: [], devices: [], logs: [], speaks: []}; + const liveParts = (kind) => radioParts[kind].filter((part) => part.root.isConnected); function voiceReplay(note) { return typeof note === "string" && NOTE_ID.test(note) ? h("audio", {class: "voice-replay", controls: true, preload: "none", src: `/api/voice/${note}.wav`, "aria-label": "Play voice message"}) : null; @@ -48,43 +51,51 @@ action); } + function nowPlaying() { + const stream = settings.streams[radio.index]; + if (!stream || !radio.state) { + return null; + } + const [kind, label] = stationState(stream, radio.index); + return h("span", {class: "pill station-now", "data-tone": STATION_TONES[kind], title: `${stream.name}: ${label}`}, label); + } + function drawStations() { - if (!radioDom) { - return; - } const sig = JSON.stringify([settings.streams, radio.index, radio.state, radio.note, radio.pick, Math.floor(Date.now() / 60000)]); - if (sig === radioDom.stationsSig) { - return; + for (const part of liveParts("devices")) { + if (sig === part.stationsSig) { + continue; + } + part.stationsSig = sig; + part.now.replaceChildren(...[nowPlaying()].filter(Boolean)); + part.stations.replaceChildren(...(settings.streams.length + ? settings.streams.map(stationRow) + : [h("li", {class: "muted"}, "No station yet: add one with Edit stations.")])); } - radioDom.stationsSig = sig; - radioDom.stations.replaceChildren(...(settings.streams.length - ? settings.streams.map(stationRow) - : [h("li", {class: "muted"}, "No station yet: add one with Edit stations.")])); } function drawDisplay() { - if (!radioDom) { - return; - } - const {lamp, cls, mode, cpu} = radioDom.face; const now = speech.current; const newest = state.radio[state.radio.length - 1]; const shown = now ? now.cls : newest ? newest.class : ""; const gate = state.speech.gate; const playing = Boolean(now && speech.source); const sent = Boolean(playing && now.sent); - lamp.dataset.lit = String(playing); - lamp.dataset.tx = String(sent); - lamp.textContent = sent ? "TX" : "RX"; - lamp.setAttribute("aria-label", playing ? `${sent ? "TX" : "RX"}: sound plays` : "RX: no sound"); - lamp.title = lamp.getAttribute("aria-label"); - cls.textContent = shown ? CLASSES[shown] || shown : "–"; - mode.textContent = MODE_LABELS[radioSet.mode][1]; - cpu.textContent = gate.cpu === null ? "CPU ?" : `CPU ${Math.round(gate.cpu)} %`; - cpu.dataset.open = String(gate.open); - cpu.title = gate.cpu === null - ? `No host CPU sample of the last two minutes: the hub renders no new speech line, threshold ${gate.threshold} %` - : `Host CPU ${fixed(gate.cpu)} %: new speech renders below ${gate.threshold} %${gate.open ? "" : ", so the radio plays the burst"}`; + for (const part of liveParts("devices")) { + const {lamp, cls, mode, cpu} = part.face; + lamp.dataset.lit = String(playing); + lamp.dataset.tx = String(sent); + lamp.textContent = sent ? "TX" : "RX"; + lamp.setAttribute("aria-label", playing ? `${sent ? "TX" : "RX"}: sound plays` : "RX: no sound"); + lamp.title = lamp.getAttribute("aria-label"); + cls.textContent = shown ? CLASSES[shown] || shown : "–"; + mode.textContent = MODE_LABELS[radioSet.mode][1]; + cpu.textContent = gate.cpu === null ? "CPU ?" : `CPU ${Math.round(gate.cpu)} %`; + cpu.dataset.open = String(gate.open); + cpu.title = gate.cpu === null + ? `No host CPU sample of the last two minutes: the hub renders no new speech line, threshold ${gate.threshold} %` + : `Host CPU ${fixed(gate.cpu)} %: new speech renders below ${gate.threshold} %${gate.open ? "" : ", so the radio plays the burst"}`; + } } function drawSpeaker() { @@ -92,17 +103,17 @@ for (const art of document.querySelectorAll(".avatar[data-face]")) { art.classList.toggle("speaking", Boolean(now && art.dataset.face === now.who)); } - if (radioDom) { - const {caption} = radioDom.face; + for (const part of liveParts("devices")) { + const {caption} = part.face; caption.hidden = !now; caption.replaceChildren(...(now ? [ h("span", {class: "speaker-face"}, face(now.who, false)), - h("strong", {}, `${nameOf(now.who)} speaking`), + h("strong", {}, nameOf(now.who), h("span", {class: "caption-verb"}, " speaking")), h("span", {class: "caption-line", title: now.line}, now.line), iconBtn("bi-stop-fill", "Stop speaking", "btn small ghost", cancelSpeech), ] : [])); - drawDisplay(); } + drawDisplay(); if (ui.screen === "agents" && (ui.views.agents === "orbit" || ui.views.agents === "chord")) { stage(); } @@ -115,17 +126,17 @@ value.textContent = event.target.value; change(Number(event.target.value)); }}}); - return {input, value, row: h("label", {class: "knob-row", title: hint}, h("span", {class: "knob-label", title: label}, label), input, value)}; + return {input, value, row: h("div", {class: "knob-row", title: hint}, h("span", {class: "knob-label", title: label}, label), input, value)}; } function toneKnob(id, label) { - const toggle = h("button", {type: "button", class: "btn small ghost icon-only", "aria-pressed": "false", ...named(`${label} tone`), on: {click: () => { + const toggle = h("button", {type: "button", class: "btn small ghost icon-only knob-toggle", "aria-pressed": "false", ...named(`${label} tone`), on: {click: () => { keepRadio({sounds: {...radioSet.sounds, [id]: {...radioSet.sounds[id], on: !radioSet.sounds[id].on}}}); }}}); const level = knob(label, `${label}: tone volume; speech and the burst of these rows play at it`, {min: 0, max: 1, step: 0.05}, (volume) => { keepRadio({sounds: {...radioSet.sounds, [id]: {...radioSet.sounds[id], volume}}}); }); - const test = iconBtn("bi-play-fill", `Test ${label}`, "btn small ghost", () => play(id, loudness(id)), `Test: play the ${label} tone`); + const test = iconBtn("bi-play-fill", `Test ${label}`, "btn small ghost knob-test", () => play(id, loudness(id)), `Test: play the ${label} tone`); level.row.prepend(toggle); level.row.append(test); return {id, toggle, level}; @@ -145,13 +156,12 @@ threshold.value.textContent = `${value} %`; }); threshold.input.addEventListener("change", (event) => setThreshold(Number(event.target.value))); - const check = iconBtn("bi-broadcast", "Radio check", "btn small ghost", () => say({steps: [{kind: "speech", text: state.speech.sample}], voice: state.speech.operator, tone: "direct", cls: "newsletter", who: HUMAN, sent: true, line: "radio check"}), "Radio check: hear the operator's voice once"); + const check = iconBtn("bi-broadcast", "Radio check", "btn small ghost radio-check", () => say({steps: [{kind: "speech", text: state.speech.sample}], voice: state.speech.operator, tone: "direct", cls: "newsletter", who: HUMAN, sent: true, line: "radio check"}), "Radio check: hear the operator's voice once"); check.disabled = !state.speech.tts; - radioDom.knobs = {tones, squelch, threshold, check}; - return [...tones.map((tone) => tone.level.row), squelch.row, threshold.row, h("div", {class: "knob-row"}, check)]; + return {tones, squelch, threshold, check, rows: [...tones.map((tone) => tone.level.row), squelch.row, threshold.row]}; } - function faceplate() { + function faceplate(part) { const lamp = h("span", {class: "radio-lamp", role: "img", "data-lit": "false", "data-tx": "false"}, "RX"); const field = (name) => h("span", {class: "radio-field", "data-field": name}); const [cls, mode, cpu] = [field("class"), field("mode"), field("cpu")]; @@ -163,9 +173,112 @@ context(); }}}, icon(name), label); })); - radioDom.face = {lamp, cls, mode, cpu, caption, modes}; + part.face = {lamp, cls, mode, cpu, caption, modes}; + part.knobs = knobs(); const display = h("div", {class: "radio-display", role: "group", "aria-label": "Display"}, lamp, cls, mode, cpu); - return h("div", {class: "radio-face", role: "group", "aria-label": "Radio set"}, display, caption, modes, h("div", {class: "radio-knobs", role: "group", "aria-label": "Knobs"}, knobs())); + return h("div", {class: "radio-face", role: "group", "aria-label": "Radio set"}, display, caption, modes, part.knobs.check, + h("div", {class: "radio-knobs", role: "group", "aria-label": "Knobs"}, part.knobs.rows)); + } + + function toggleGear(part) { + const open = part.box.hidden; + part.box.replaceChildren(...(open ? [radioFilters()] : [])); + part.box.hidden = !open; + part.gear.setAttribute("aria-expanded", String(open)); + window.requestAnimationFrame(refresh3d); + } + + /** + * @param {boolean} spot whether the bar heads the radio spot. + * @returns {object} the bar part: root, gear, its box and the Cancel mayday button. + */ + function radioBar(spot) { + const part = {box: h("div", {class: "radio-gear", id: spot ? "radio-gear" : null, hidden: true})}; + part.gear = iconBtn("bi-funnel", "Read aloud", "btn small ghost spot-toggle", () => toggleGear(part), "Read aloud: the classes and agents the radio sounds for"); + part.gear.setAttribute("aria-expanded", "false"); + if (spot) { + part.gear.setAttribute("aria-controls", "radio-gear"); + } + const [, label, , hint] = actionOf("clear-mayday"); + part.clear = iconBtn("bi-life-preserver", label, "btn small danger", () => confirmAct("clear-mayday", []), hint); + part.clear.disabled = !state.silence; + part.root = h("div", {class: "spot-bar", "data-star-slot": ""}, h("div", {class: "spot-head"}, spot ? h("h3", {class: "group-title"}, "Radio") : null, h("span", {class: "spacer"}), part.gear, part.clear), part.box); + radioParts.bars.push(part); + return part; + } + + function drawBars() { + for (const part of liveParts("bars")) { + part.clear.disabled = !state.silence; + } + } + + function cardHead(title, ...tools) { + return h("div", {class: "radio-card-head", "data-star-slot": ""}, h("h3", {class: "group-title"}, title), tools); + } + + function stationFold(part) { + part.stations = h("ul", {class: "stations", "aria-label": "Stations"}); + part.now = h("span", {class: "station-now-box"}); + return h("details", {class: "radio-station", on: {toggle: (event) => placeStation(event.currentTarget)}}, + h("summary", {title: "Internet radio: the stations, their schedule and Play or Stop"}, caret(), h("h3", {class: "group-title"}, "Internet radio"), part.now), + h("div", {class: "station-body"}, h("div", {class: "station-tools"}, btn("Edit stations", "btn small ghost", stationsSheet)), part.stations)); + } + + function placeStation(fold) { + if (!fold.open) { + return; + } + const edge = fold.getBoundingClientRect(); + let [top, bottom] = [0, window.innerHeight]; + for (let node = fold.parentElement; node && node !== document.documentElement; node = node.parentElement) { + const look = getComputedStyle(node); + if (look.overflowX !== "visible" || look.overflowY !== "visible") { + const clip = node.getBoundingClientRect(); + [top, bottom] = [Math.max(top, clip.top), Math.min(bottom, clip.bottom)]; + } + } + const [above, below] = [Math.floor(edge.top - top), Math.floor(bottom - edge.bottom)]; + fold.style.removeProperty("--room"); + const up = above >= fold.querySelector(".station-body").offsetHeight || above >= below; + fold.dataset.side = up ? "up" : "down"; + fold.style.setProperty("--room", `${Math.max(0, up ? above : below)}px`); + } + + function placeStations(event) { + for (const fold of document.querySelectorAll("details.radio-station[open]")) { + if (!(event && event.target instanceof Node && fold.contains(event.target))) { + placeStation(fold); + } + } + } + + function deviceCard() { + const part = {stationsSig: ""}; + const face = faceplate(part); + part.root = h("section", {class: "radio-card radio-device", "data-panel": "radio-device", "aria-label": "Device"}, cardHead("Device"), face, stationFold(part)); + radioParts.devices.push(part); + return part; + } + + function speakCard() { + const {form, recipient, text, channel} = composerForm(); + const part = {recipient, text, channel, names: ""}; + part.root = h("section", {class: "radio-card radio-speak", "data-panel": "radio-speak", "aria-label": "Speak"}, cardHead("Speak"), form); + radioParts.speaks.push(part); + return part; + } + + function drawSpeak() { + const names = agentNames(); + const sig = JSON.stringify(names); + for (const part of liveParts("speaks")) { + if (sig !== part.names) { + part.names = sig; + const chosen = part.recipient.value; + part.recipient.replaceChildren(...names.map((name) => h("option", {value: name, selected: name === chosen}, name)), ...(chosen && !names.includes(chosen) ? [h("option", {value: chosen, selected: true}, chosen)] : [])); + } + } } function radioFilters() { @@ -185,8 +298,10 @@ } function redrawFilters() { - if (spotDom && !spotDom.gearBox.hidden) { - spotDom.gearBox.replaceChildren(radioFilters()); + for (const part of liveParts("bars")) { + if (!part.box.hidden) { + part.box.replaceChildren(radioFilters()); + } } } @@ -194,103 +309,284 @@ keepRadio({log: {...radioSet.log, ...change}}); } - function chipSelect(name, values) { - const chosen = radioSet.log.chips[name]; + function chipSelect(name) { const label = CHIP_LABELS[name]; + const select = h("select", {class: "field", "aria-label": label, title: `${label}: filter the log`, on: {change: (event) => keepLog({chips: {...radioSet.log.chips, [name]: event.target.value}})}}); + return h("label", {class: "chip-select", "data-chip": name, "data-active": "false"}, select); + } + + function fillChip(chip, values) { + const name = chip.dataset.chip; + const chosen = radioSet.log.chips[name]; const options = [...new Set([...values, ...(chosen ? [chosen] : [])])]; - const select = h("select", {class: "field", "aria-label": label, title: `${label}: filter the log`, on: {change: (event) => keepLog({chips: {...radioSet.log.chips, [name]: event.target.value}})}}, - h("option", {value: ""}, `${label}: any`), options.map((value) => h("option", {value, selected: value === chosen}, name === "class" ? CLASSES[value] || value : value))); - return h("label", {class: "chip-select", "data-chip": name, "data-active": String(Boolean(chosen))}, select); + const select = chip.querySelector("select"); + const sig = JSON.stringify([options, chosen || ""]); + if (select.sig !== sig) { + select.sig = sig; + select.replaceChildren(h("option", {value: ""}, `${CHIP_LABELS[name]}: any`), ...options.map((value) => h("option", {value, selected: value === chosen}, name === "class" ? CLASSES[value] || value : value))); + } + setAttr(chip, "data-active", String(Boolean(chosen))); + } + + function setAttr(node, name, value) { + if (node.getAttribute(name) !== value) { + node.setAttribute(name, value); + } + } + + function setText(node, value) { + if (node.textContent !== value) { + node.textContent = value; + } + } + + function firstLine(text) { + return text.split("\n").map((part) => part.trim()).find(Boolean) || ""; } function logLine(row) { const message = row.sent ? row : RadioSet.ledgerOf(row, state.messages); const sent = Boolean(message); const [name, label] = sent ? ["bi-arrow-up-right", "Sent"] : ["bi-arrow-down-left", "Received"]; - const first = row.text.split("\n").map((part) => part.trim()).find(Boolean) || ""; - return h("li", {class: "radio-row", "data-dir": sent ? "sent" : "received", "data-class": row.class}, - h("details", {}, h("summary", {}, + const first = firstLine(row.text); + const line = h("li", {class: "radio-row", "data-key": row.key, "data-dir": sent ? "sent" : "received", "data-class": row.class, "data-ts": row.ts, on: {click: (event) => openRadioRow(event.currentTarget.row, event.currentTarget)}}, + h("button", {type: "button", class: "radio-pick", "aria-haspopup": "dialog", title: first}, when(row.ts), h("span", {class: "radio-dir", role: "img", ...named(label)}, icon(name)), klass(row.class), h("span", {class: "radio-route"}, `${row.from} → ${targetsOf(row)}`), - h("span", {class: "radio-line", title: first}, first)), + h("span", {class: "radio-line"}, first)), + foldedReaders(row)); + line.row = row; + return line; + } + + function keepLine(kept, fresh) { + kept.row = fresh.row; + if (kept.outerHTML === fresh.outerHTML) { + return kept; + } + for (const name of ["data-dir", "data-class"]) { + setAttr(kept, name, fresh.getAttribute(name)); + } + const [pick, twin] = [kept.querySelector(".radio-pick"), fresh.querySelector(".radio-pick")]; + setAttr(pick, "title", twin.getAttribute("title")); + pick.replaceChildren(...twin.childNodes); + for (const node of [...kept.children].filter((child) => child !== pick)) { + node.remove(); + } + kept.append(...[...fresh.children].filter((child) => child !== twin)); + return kept; + } + + function patchList(list, lines) { + const before = [...list.children]; + const focused = before.find((node) => node.contains(document.activeElement)) || null; + const old = new Map(before.filter((node) => node.dataset.key).map((node) => [node.dataset.key, node])); + const wanted = lines.map((line) => { + const kept = old.get(line.dataset.key); + old.delete(line.dataset.key); + return kept ? keepLine(kept, line) : line; + }); + const keep = new Set(wanted); + for (const node of before.filter((child) => !keep.has(child))) { + node.remove(); + } + wanted.forEach((node, index) => { + if (list.children[index] !== node) { + list.insertBefore(node, list.children[index] || null); + } + }); + if (focused && !focused.isConnected) { + const at = before.indexOf(focused); + const near = before.filter((node) => node.isConnected && node.querySelector(".radio-pick")).sort((a, b) => Math.abs(before.indexOf(a) - at) - Math.abs(before.indexOf(b) - at))[0]; + (near ? near.querySelector(".radio-pick") : list).focus({preventScroll: true}); + } + } + + function foldedReaders(row) { + const strip = readerRow(row); + const {shown, hidden} = Receipts.strip(row); + const rest = shown.length + hidden.length - FOLDED_READERS; + if (strip && rest > 0) { + strip.append(h("span", {class: "readers-more readers-fold", role: "img", ...named(`${rest} more readers`, [...shown, ...hidden].slice(FOLDED_READERS).map(readLabel).join("\n"))}, `+${rest}`)); + } + return strip; + } + + function readerLine(reader) { + const known = reader.read !== null && reader.read !== undefined; + return h("li", {class: "popup-reader", "data-session": reader.session, "data-acked": String(reader.acked)}, + face(people()[reader.session] ? reader.session : reader.name, false), + h("strong", {}, reader.name), + h("span", {class: "muted"}, known ? `read ${reader.approximate ? "about " : ""}${absolute.format(stampOf(reader.read))}` : "read, time unknown"), + reader.acked ? pill("acknowledged", "ok") : null); + } + + function copyText(text) { + const said = h("span", {class: "radio-said", role: "status", "aria-live": "polite"}); + const button = h("button", {type: "button", class: "btn small radio-copy", ...named("Copy", "Copy: the full message to the clipboard")}, icon("bi-clipboard"), h("span", {}, "Copy")); + const show = (name, word, done, note) => { + button.replaceChildren(icon(name), h("span", {}, word)); + button.setAttribute("aria-label", word); + button.dataset.copied = done; + said.textContent = note; + }; + button.addEventListener("click", async () => { + try { + await navigator.clipboard.writeText(text); + show("bi-clipboard-check", "Copied", "true", "Copied: the full message is on the clipboard"); + } catch { + show("bi-x-circle", "Not copied", "false", "Not copied: the browser refused the clipboard"); + } + window.setTimeout(() => show("bi-clipboard", "Copy", "", ""), COPIED); + }); + return [button, said]; + } + + function replyTarget(list) { + const home = list ? list.closest(".radio-home") : null; + if (!home) { + return spotDom.speak; + } + const homes = liveParts("speaks").filter((part) => part.root.closest(".radio-home")); + return homes.find((part) => home.contains(part.root)) || homes.find((part) => part.root.closest(".radio-home-radio-speak")) || homes[0] || spotDom.speak; + } + + function replyTo(row, list) { + const who = row.from === HUMAN && row.to.length ? row.to[0] : row.from; + const part = replyTarget(list); + closePopup(); + if (part === spotDom.speak) { + openSpot(true); + } + part.channel.value = "post"; + part.channel.dispatchEvent(new Event("change", {bubbles: true})); + if (![...part.recipient.options].some((option) => option.value === who)) { + part.recipient.append(h("option", {value: who}, who)); + } + part.recipient.value = who; + part.text.focus(); + } + + function openRadioRow(row, li) { + const message = row.sent ? row : RadioSet.ledgerOf(row, state.messages); + const {shown, hidden} = Receipts.strip(row); + const readers = [...shown, ...hidden]; + const list = li.closest("ul"); + const anchor = () => (list ? [...list.querySelectorAll(".radio-row")].find((item) => item.dataset.key === row.key) || null : null); + openPopup(`Radio message from ${row.from}`, [ + popupHead(klass(row.class), `${row.from} → ${targetsOf(row)}`), + meta([["Sender", row.from], ["Recipient", targetsOf(row)], ["Class", CLASSES[row.class] || row.class], ["Time", absolute.format(stampOf(row.ts))]]), h("pre", {class: "radio-full"}, row.text), - voiceReplay(message ? message.voice : null)), - readerRow(row)); + voiceReplay(message ? message.voice : null), + h("div", {class: "actions radio-actions"}, + h("button", {type: "button", class: "btn small primary radio-reply", ...named("Reply", "Reply: a post to the sender in the speak card"), on: {click: () => replyTo(row, list)}}, icon("bi-reply"), "Reply"), + copyText(row.text)), + h("h3", {}, readers.length ? `Read by ${readers.length}` : "Read by nobody yet"), + readers.length ? h("ul", {class: "popup-readers"}, readers.map(readerLine)) : null, + ].filter(Boolean), anchor); } function drawLog() { - const dom = radioDom.log; const entry = radioSet.log; const sig = JSON.stringify([state.radio.length, state.radio.length ? state.radio[state.radio.length - 1].ts : 0, state.messages.length, Receipts.signature(state.radio), Receipts.signature(state.messages), entry, Math.floor(Date.now() / 60000)]); - if (sig === dom.sig) { - return; + for (const dom of liveParts("logs")) { + if (sig !== dom.sig) { + dom.sig = sig; + drawLogPart(dom, entry); + } } - dom.sig = sig; + } + + function drawLogPart(dom, entry) { const counts = RadioSet.counts(state.radio, HUMAN, state.messages); - dom.tabs.replaceChildren(...RadioSet.TABS.map((tab) => { - const [name, label, hint] = TAB_LABELS[tab]; - return h("button", {type: "button", role: "tab", "data-tab": tab, "aria-selected": String(tab === entry.tab), title: hint, on: {click: () => keepLog({tab})}}, - icon(name), label, h("span", {class: "count", "aria-label": `${counts[tab]} rows`}, String(counts[tab]))); - })); + for (const button of dom.tabs.children) { + const {tab} = button.dataset; + const count = button.querySelector(".count"); + setAttr(button, "aria-selected", String(tab === entry.tab)); + setAttr(count, "aria-label", `${counts[tab]} rows`); + setText(count, String(counts[tab])); + } const choices = RadioSet.choices(state.radio); - dom.chips.replaceChildren(...RadioSet.CHIPS.map((name) => chipSelect(name, choices[name]))); + for (const chip of dom.chips.children) { + fillChip(chip, choices[chip.dataset.chip]); + } if (document.activeElement !== dom.search && dom.search.value !== entry.q) { dom.search.value = entry.q; } const rows = RadioSet.logRows(state.radio, entry, HUMAN, state.messages); - dom.list.replaceChildren(...(rows.length ? rows.map(logLine) : [h("li", {class: "muted"}, state.radio.length ? "No radio row matches the tab, the chips and the search." : "No radio in the chosen time range yet.")])); + patchList(dom.list, rows.length ? rows.map(logLine) : [h("li", {class: "muted"}, state.radio.length ? "No radio row matches the tab, the chips and the search." : "No radio in the chosen time range yet.")]); } - function radioLog() { - const tabs = h("div", {class: "radio-tabs", role: "tablist", "aria-label": "Log"}); - const chips = h("div", {class: "radio-chips", role: "group", "aria-label": "Log filters"}); + function historyCard() { + const tabs = h("div", {class: "radio-tabs", role: "tablist", "aria-label": "Log"}, RadioSet.TABS.map((tab) => { + const [name, label, hint] = TAB_LABELS[tab]; + return h("button", {type: "button", role: "tab", "data-tab": tab, "aria-selected": "false", title: hint, on: {click: () => keepLog({tab})}}, icon(name), label, h("span", {class: "count"})); + })); + const chips = h("div", {class: "radio-chips", role: "group", "aria-label": "Log filters"}, RadioSet.CHIPS.map(chipSelect)); const search = h("input", {type: "search", class: "field", placeholder: "Search the log …", maxlength: 200, ...named("Search the log"), on: {input: (event) => keepLog({q: event.target.value})}}); const clear = iconBtn("bi-x-circle", "Clear filters", "btn small ghost", () => keepRadio({log: RadioSet.cleared(radioSet.log)}), "Clear filters: every chip and the search"); - const list = h("ul", {class: "radio-log", "aria-label": "Radio log"}); - radioDom.log = {tabs, chips, search, list, sig: ""}; - return h("section", {class: "radio-logbox", "aria-label": "Radio log"}, tabs, h("div", {class: "radio-filters"}, chips, search, clear), list); + const list = h("ul", {class: "radio-log", tabindex: "-1", "aria-label": "Radio log"}); + const part = {tabs, chips, search, list, sig: ""}; + part.root = h("section", {class: "radio-card radio-logbox", "data-panel": "radio-log", "aria-label": "Radio log"}, cardHead("History", tabs, search), h("div", {class: "radio-filters"}, chips, clear), list); + radioParts.logs.push(part); + return part; } function drawRadioSet() { - if (!radioDom) { - return; + for (const part of liveParts("devices")) { + for (const button of part.face.modes.querySelectorAll("button[data-mode]")) { + button.setAttribute("aria-pressed", String(button.dataset.mode === radioSet.mode)); + } + const {tones, squelch, threshold} = part.knobs; + for (const {id, toggle, level} of tones) { + const sound = radioSet.sounds[id]; + toggle.setAttribute("aria-pressed", String(sound.on)); + toggle.replaceChildren(icon(sound.on ? "bi-bell" : "bi-bell-slash")); + toggle.title = `${toggle.getAttribute("aria-label")}: ${sound.on ? "on, a press mutes it" : "off, a press turns it on"}`; + level.input.value = String(sound.volume); + level.value.textContent = sound.volume.toFixed(2); + } + squelch.input.value = String(radioSet.squelch); + squelch.value.textContent = radioSet.squelch.toFixed(2); + threshold.input.value = String(settings.speech.threshold); + threshold.value.textContent = `${settings.speech.threshold} %`; } - for (const button of radioDom.face.modes.querySelectorAll("button[data-mode]")) { - button.setAttribute("aria-pressed", String(button.dataset.mode === radioSet.mode)); - } - const {tones, squelch, threshold} = radioDom.knobs; - for (const {id, toggle, level} of tones) { - const sound = radioSet.sounds[id]; - toggle.setAttribute("aria-pressed", String(sound.on)); - toggle.replaceChildren(icon(sound.on ? "bi-bell" : "bi-bell-slash")); - toggle.title = `${toggle.getAttribute("aria-label")}: ${sound.on ? "on, a press mutes it" : "off, a press turns it on"}`; - level.input.value = String(sound.volume); - level.value.textContent = sound.volume.toFixed(2); - } - squelch.input.value = String(radioSet.squelch); - squelch.value.textContent = radioSet.squelch.toFixed(2); - threshold.input.value = String(settings.speech.threshold); - threshold.value.textContent = `${settings.speech.threshold} %`; drawDisplay(); drawLog(); } function drawRadio() { - if (!radioDom) { - return; - } drawRadioSet(); drawStations(); + drawSpeak(); + drawBars(); } - function radioSide() { - const stations = h("ul", {class: "stations", "aria-label": "Stations"}); - radioDom = {stations, stationsSig: ""}; - const face = faceplate(); - const log = radioLog(); - const station = h("section", {class: "radio-station", "aria-label": "Internet radio"}, h("div", {class: "card-head"}, h("h3", {class: "group-title"}, "Internet radio"), btn("Edit stations", "btn small ghost", stationsSheet)), stations); + /** + * @param {boolean} spot whether the body fills the radio spot rather than a Home tile. + * @returns {object} its bar, device, speak and history parts and the grid holding the three cards. + */ + function radioBody(spot) { + const bar = radioBar(spot); + const device = deviceCard(); + const speak = speakCard(); + const history = historyCard(); window.setTimeout(drawRadio, 0); - return {face, log, station}; + return {bar, device, speak, history, grid: h("div", {class: "radio-grid"}, device.root, h("div", {class: "radio-column"}, speak.root, history.root))}; + } + + /** + * @param {string} id the Home panel id: radio, radio-device, radio-speak or radio-log. + * @returns {Element} a second live instance of that part for a Home tile, without ids and without stars of its own. + */ + function radioPart(id) { + const body = id === "radio" ? radioBody(false) : null; + const made = body ? [body.bar.root, body.grid] : {"radio-device": deviceCard, "radio-speak": speakCard, "radio-log": historyCard}[id]().root; + const root = h("div", {class: `radio-home radio-home-${id}`}, made); + root.querySelectorAll("[data-panel]").forEach((node) => node.removeAttribute("data-panel")); + root.querySelectorAll("[data-star-slot]").forEach((node) => node.removeAttribute("data-star-slot")); + window.setTimeout(drawRadio, 0); + return root; } diff --git a/orchestrator/templates/page-screens.js b/orchestrator/templates/page-screens.js index 621d4fc..70de913 100644 --- a/orchestrator/templates/page-screens.js +++ b/orchestrator/templates/page-screens.js @@ -105,8 +105,12 @@ } const banner = document.getElementById("mayday"); const silence = state.silence; - banner.hidden = !silence; - banner.replaceChildren(...(silence ? [h("p", {class: "text"}, `MAYDAY · ${dash(silence.by)}: ${silence.text}`), iconBtn("bi-x-octagon", "cancel", "btn small", () => confirmAct("clear-mayday", []), "cancel: end the mayday (radio.py clear)")] : [])); + const alarm = silence ? `MAYDAY · ${dash(silence.by)}: ${silence.text}` : ""; + if (banner.alarm !== alarm) { + banner.alarm = alarm; + banner.hidden = !silence; + banner.replaceChildren(...(silence ? [h("p", {class: "text", title: alarm}, alarm), iconBtn("bi-x-octagon", "cancel", "btn small", () => confirmAct("clear-mayday", []), "cancel: end the mayday (radio.py clear)")] : [])); + } document.title = `${state.badges.tasks ? `(${state.badges.tasks}) ` : ""}Agent Orchestrator`; window.setTimeout(measure, 0); } diff --git a/orchestrator/templates/page-state.js b/orchestrator/templates/page-state.js index a66183e..0245aa1 100644 --- a/orchestrator/templates/page-state.js +++ b/orchestrator/templates/page-state.js @@ -32,7 +32,7 @@ let state = JSON.parse(document.getElementById("state").textContent); const KINDS = Object.entries(state.kinds); - const ui = {screen: "stream", views: {agents: "orbit", artifacts: "tree", tasks: "list"}, preset: DAY, from: null, to: null, asOf: null, playing: false, busy: false, offline: false, agent: null, order: null, draft: "", spot: false, nightOff: new Set(), cursor: 0, selected: new Set(), snoozed: false, review: null, file: 0}; + const ui = {screen: "stream", views: {agents: "orbit", artifacts: "tree", tasks: "list"}, preset: DAY, from: null, to: null, asOf: null, playing: false, busy: false, offline: false, agent: null, order: null, spot: false, nightOff: new Set(), cursor: 0, selected: new Set(), snoozed: false, review: null, file: 0}; const filter = {view: "fuer-dich", saved: "", kinds: new Set(state.views["fuer-dich"].kinds), waiting: true, q: "", agent: "", session: "", sub: "", parts: new Set(PARTS.map(([id]) => id))}; const stream = {key: null, events: [], entries: [], last: 0, sessions: {}, busy: false, again: false, dom: null, error: ""}; const tree = {data: null, model: null, busy: false, q: "", open: new Set(), dom: null}; diff --git a/orchestrator/templates/panels.js b/orchestrator/templates/panels.js index 4711c92..180dce3 100644 --- a/orchestrator/templates/panels.js +++ b/orchestrator/templates/panels.js @@ -54,9 +54,10 @@ const Panels = (() => { * @param title - the tile title. * @param render - (size) => Node, size being {w, h} in grid cells. * @param group - optional name of a group of which Home holds one pin at most, such as the 3D views. + * @param size - optional [w, h] in grid cells a new pin of the panel gets; SIZES.panel when left out. */ - function panel(id, title, render, group) { - panels.set(id, {title, render, group: group || ""}); + function panel(id, title, render, group, size) { + panels.set(id, {title, render, group: group || "", size: size || SIZES.panel}); } /** @@ -105,7 +106,7 @@ const Panels = (() => { if (holder) { return {pins, refused: "group", holder}; } - const [w, h] = kind === PANEL ? SIZES.panel : SIZES.item; + const [w, h] = kind === PANEL ? (panels.get(id) || {size: SIZES.panel}).size : SIZES.item; return {pins: [...pins, {kind, id, w, h}], refused: "", holder: null}; } diff --git a/orchestrator/templates/radioset.js b/orchestrator/templates/radioset.js index b42a36d..23a6e05 100644 --- a/orchestrator/templates/radioset.js +++ b/orchestrator/templates/radioset.js @@ -103,14 +103,28 @@ const RadioSet = (() => { } function sentRows(messages, human) { - return messages.map((message) => ({ts: message.created_ts, from: human, to: message.to === "*" ? [] : [message.to], class: message.class || "post", text: message.text, voice: message.voice, sent: true, readers: message.readers, acks: message.acks})); + return messages.map((message) => ({ts: message.created_ts, from: human, to: message.to === "*" ? [] : [message.to], class: message.class || "post", text: message.text, voice: message.voice, sent: true, id: message.id, readers: message.readers, acks: message.acks})); + } + + /** + * @param {Array} rows radio rows in arrival order, or sent rows of the ledger. + * @returns {Array} copies of the rows, each with a key unique in the list and stable while rows arrive: the ledger id of a sent row, else time, sender and the occurrence index among rows of the same time and sender. + */ + function keyed(rows) { + const seen = new Map(); + return rows.map((row) => { + const base = row.sent ? `sent ${row.id}` : `${row.ts} ${row.from}`; + const index = seen.get(base) || 0; + seen.set(base, index + 1); + return {...row, key: `${base} ${index}`}; + }); } function tabRows(rows, tab, human, messages) { if (tab === "sent") { - return sentRows(messages, human); + return keyed(sentRows(messages, human)); } - return rows.filter((row) => tab === "all" || toAll(row) || row.to.includes(human)); + return keyed(rows).filter((row) => tab === "all" || toAll(row) || row.to.includes(human)); } function matches(row, entry) { @@ -128,7 +142,7 @@ const RadioSet = (() => { * @param {object} entry the log part of the radio set: tab, chips and q. * @param {string} human the operator's name. * @param {Array} messages the hub's message ledger; Sent lists it, not radio rows that only claim the operator's name. - * @returns {Array} the rows of the tab that every chip and the search match, newest first. + * @returns {Array} keyed copies of the rows of the tab that every chip and the search match, newest first. */ function logRows(rows, entry, human, messages) { return tabRows(rows, entry.tab, human, messages).filter((row) => matches(row, entry)).sort((a, b) => b.ts - a.ts); diff --git a/orchestrator/templates/style-ui.css b/orchestrator/templates/style-ui.css index 30e9d58..4fdbfb9 100644 --- a/orchestrator/templates/style-ui.css +++ b/orchestrator/templates/style-ui.css @@ -43,7 +43,7 @@ svg .presence-dot { fill: var(--panel); stroke: currentColor; stroke-width: 1; } .presence .glyph { animation: none; } } .stations { display: grid; gap: 4px; margin: 0; padding: 0; list-style: none; } -.station { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1fr) auto auto; align-items: center; gap: var(--sp-2); min-width: 0; padding: 3px 3px 3px 10px; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--sunken); } +.station { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1fr) auto auto; align-items: center; gap: var(--sp-2); min-width: 0; padding: 3px 3px 3px 10px; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--panel); } .station-name, .station-when { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .station-name { font-weight: 600; } .station-when { color: var(--muted); font-size: var(--fs-sm); } @@ -55,71 +55,186 @@ svg .presence-dot { fill: var(--panel); stroke: currentColor; stroke-width: 1; } .station-when { display: none; } } .spot-toggle[aria-expanded="true"] { background: var(--accent-soft); color: var(--accent); } -.radio-spot { display: grid; gap: var(--sp-3); max-height: 46vh; margin-bottom: var(--sp-4); overflow: auto; } +.radio-spot, .radio-home { container: radio / inline-size; min-width: 0; } +.radio-spot { display: grid; gap: var(--sp-3); margin-bottom: var(--sp-4); padding: var(--sp-3); } .radio-spot[hidden], .radio-gear[hidden] { display: none; } -body.fit .spot-host { display: flex; flex: 0 1 auto; flex-direction: column; min-height: 0; } -body.fit .radio-spot { flex: 0 1 auto; min-height: 0; } -.radio-side { display: grid; gap: var(--sp-3); align-content: start; min-width: 0; } -.spot-head { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); } +body.fit .spot-host { flex: none; } +.spot-bar { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; } +.spot-head { display: flex; flex: 1; flex-wrap: wrap; align-items: center; gap: var(--sp-2); min-width: 0; } .night-picks { display: flex; flex-wrap: wrap; gap: 4px var(--sp-3); max-width: 420px; max-height: 30vh; overflow: auto; } .night-picks:empty { display: none; } .agent-night { align-items: center; margin: 0 0 var(--sp-2); } -.spot-body { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 440px), 1fr)); gap: var(--sp-4); align-items: start; } -.radio-gear { min-width: 0; } -.composer { display: grid; gap: var(--sp-2); } +.spot-bar { position: relative; } +.radio-gear { position: absolute; top: calc(100% + var(--sp-1)); right: 0; z-index: 12; width: min(36rem, 100%); min-width: 0; padding: var(--sp-3); border: 1px solid var(--line-strong); border-radius: var(--radius); background: var(--glass-card); box-shadow: var(--shadow-lift); -webkit-backdrop-filter: var(--blur); backdrop-filter: var(--blur); } +.radio-grid { display: grid; grid-template-columns: clamp(22rem, 100% - 34rem - var(--sp-3), 26rem) minmax(0, 1fr); gap: var(--sp-3); min-width: 0; } +.radio-column { display: flex; flex-direction: column; gap: var(--sp-3); min-width: 0; min-height: 0; } +.radio-card { display: flex; flex-direction: column; gap: var(--sp-2); min-width: 0; padding: var(--sp-3); border: 1px solid var(--line); border-radius: var(--radius); background: var(--sunken); } +.radio-card-head { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); min-width: 0; min-height: 30px; } +.radio-card-head .group-title { margin-inline-end: var(--sp-2); } +.composer { display: grid; gap: var(--sp-2); min-width: 0; } .composer-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 180px), 1fr)); gap: var(--sp-2) var(--sp-3); } -.composer-grid label { display: grid; gap: 4px; min-width: 0; color: var(--muted); font-size: var(--fs-sm); } +.composer-grid label { display: grid; grid-template-columns: 4.5em minmax(0, 1fr); align-items: center; gap: var(--sp-2); min-width: 0; color: var(--muted); font-size: var(--fs-sm); } .composer-grid .field { width: 100%; min-width: 0; } +.composer textarea { min-height: 64px; } .composer [hidden] { display: none; } -.composer .actions { margin-top: 0; } +.composer .actions { flex-wrap: wrap; align-items: center; margin-top: 0; } +.composer-hint { flex: 1 1 14em; min-width: 0; margin: 0; font-size: var(--fs-xs); } +.composer .ptt { margin-inline-start: auto; } .composer-status { min-width: 0; overflow-wrap: anywhere; } .voice-note { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); } .voice-replay { max-width: 100%; height: 34px; } -.mini .voice-replay, .bubble .voice-replay, .radio-row .voice-replay { width: 100%; } -.radio-face { display: grid; gap: var(--sp-2); min-width: 0; padding: var(--sp-3); border: 1px solid var(--line-strong); border-radius: var(--radius); background: var(--sunken); } -.radio-display { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2) var(--sp-3); min-width: 0; padding: var(--sp-2) var(--sp-3); border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--panel); font-family: var(--mono); font-size: var(--fs-sm); font-variant-numeric: tabular-nums; } +.voice-note .voice-play { display: none; } +.mini .voice-replay, .bubble .voice-replay, .radio-row .voice-replay, .popup-box .voice-replay { width: 100%; } +.radio-face { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: var(--sp-2); min-width: 0; } +.radio-face > * { grid-column: 1 / -1; } +.radio-face > .radio-modes { grid-column: 1; justify-self: start; } +.radio-face > .radio-check { grid-column: 2; align-self: center; } +.radio-display { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2) var(--sp-3); min-width: 0; padding: 5px var(--sp-3); border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--panel); font-family: var(--mono); font-size: var(--fs-sm); font-variant-numeric: tabular-nums; } .radio-field { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .radio-field[data-field="class"] { font-weight: 700; } +.radio-field[data-field="cpu"] { margin-inline-start: auto; } .radio-field[data-field="cpu"][data-open="false"] { color: var(--warn); } .radio-lamp { display: inline-flex; align-items: center; gap: 5px; padding: 0 8px; border-radius: 999px; background: var(--neutral-soft); color: var(--muted); font-weight: 700; line-height: 20px; } .radio-lamp::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: currentColor; opacity: .5; } .radio-lamp[data-lit="true"] { background: var(--ok-soft); color: var(--ok); } .radio-lamp[data-lit="true"][data-tx="true"] { background: var(--bad-soft); color: var(--bad); } .radio-lamp[data-lit="true"]::before { opacity: 1; box-shadow: 0 0 0 3px color-mix(in srgb, currentColor 25%, transparent); } -.radio-modes { flex-wrap: wrap; justify-self: start; max-width: 100%; } +.radio-modes { flex-wrap: wrap; max-width: 100%; } .radio-modes button { display: inline-flex; align-items: center; gap: 6px; } -.radio-knobs { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 380px), 1fr)); gap: var(--sp-1) var(--sp-4); } -.knob-row { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; color: var(--muted); font-size: var(--fs-sm); } -.knob-label { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.knob { flex: 1 1 80px; min-width: 60px; accent-color: var(--accent); } -.knob-value { flex: none; min-width: 3.5em; font-family: var(--mono); font-variant-numeric: tabular-nums; text-align: right; } +.radio-knobs { display: grid; grid-template-columns: 30px minmax(0, max-content) minmax(3rem, 1fr) 3.2em 30px; align-items: center; gap: 2px var(--sp-2); min-width: 0; } +.knob-row { display: grid; grid-column: 1 / -1; grid-template-columns: subgrid; align-items: center; min-width: 0; min-height: 28px; color: var(--muted); font-size: var(--fs-sm); } +.knob-toggle { grid-column: 1; } +.knob-label { grid-column: 2; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.knob { grid-column: 3; width: 100%; min-width: 0; margin: 0; accent-color: var(--accent); } +.knob-value { grid-column: 4; font-family: var(--mono); font-variant-numeric: tabular-nums; text-align: right; white-space: nowrap; } +.knob-test { grid-column: 5; } .radio-read { display: grid; gap: var(--sp-2); } .radio-read .chips { margin-bottom: 0; } +.radio-station { position: relative; min-width: 0; padding-top: var(--sp-2); border-top: 1px solid var(--line); } +.radio-station > summary { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; min-height: 30px; cursor: pointer; list-style: none; } +.radio-station > summary::-webkit-details-marker { display: none; } +.radio-station > summary .caret { flex: none; color: var(--muted); transform: rotate(-90deg); transition: transform .15s; } +.radio-station[open] > summary .caret { transform: none; } +.station-now-box { display: inline-flex; min-width: 0; margin-inline-start: auto; } +.station-body { position: absolute; inset-inline: 0; bottom: 100%; z-index: 3; display: grid; gap: var(--sp-2); max-height: min(12rem, 28vh, var(--room, 100vh)); padding: var(--sp-2); overflow: hidden auto; overscroll-behavior: contain; border: 1px solid var(--line-strong); border-radius: var(--radius); background: var(--glass-card); box-shadow: var(--shadow-lift); scrollbar-width: thin; -webkit-backdrop-filter: var(--blur); backdrop-filter: var(--blur); } +.radio-station[data-side="down"] > .station-body { top: 100%; bottom: auto; } +.station-tools { display: flex; justify-content: flex-end; } .ptt { min-width: 96px; justify-content: center; } -.radio-logbox { display: grid; gap: var(--sp-2); align-content: start; min-width: 0; } -.radio-tabs { display: flex; flex-wrap: wrap; gap: 2px; padding: 3px; border: 1px solid var(--line); border-radius: 10px; background: var(--sunken); justify-self: start; max-width: 100%; } -.radio-tabs button { display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; border: 0; border-radius: 8px; background: transparent; color: var(--muted); font-size: var(--fs-sm); font-weight: 580; cursor: pointer; } -.radio-tabs button[aria-selected="true"] { background: var(--panel); color: var(--text); box-shadow: var(--shadow); } -.radio-filters { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; min-width: 0; } -.radio-chips { display: flex; flex-wrap: wrap; gap: 6px; min-width: 0; } -.chip-select .field { max-width: 180px; padding: 3px 8px; border-radius: 999px; font-size: var(--fs-sm); } +.radio-tabs { display: flex; flex-wrap: wrap; gap: 2px; max-width: 100%; padding: 3px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); } +.radio-tabs button { display: inline-flex; align-items: center; gap: 6px; padding: 3px 10px; border: 0; border-radius: 8px; background: transparent; color: var(--muted); font-size: var(--fs-sm); font-weight: 580; cursor: pointer; } +.radio-tabs button[aria-selected="true"] { background: var(--sunken); color: var(--text); box-shadow: var(--shadow); } +.radio-filters { display: flex; align-items: center; gap: 6px; min-width: 0; } +.radio-chips { display: flex; flex: 0 1 auto; flex-wrap: wrap; gap: 6px; min-width: 0; } +.chip-select { min-width: 0; } +.chip-select .field { max-width: 160px; padding: 3px 8px; border-radius: 999px; font-size: var(--fs-sm); } .chip-select[data-active="true"] .field { border-color: transparent; background: var(--accent-soft); color: var(--accent); } -.radio-filters input[type="search"] { flex: 1 1 140px; min-width: 0; padding: 4px 10px; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--panel); } -.radio-log { display: grid; gap: 4px; margin: 0; padding: 0; list-style: none; } -.radio-row details { min-width: 0; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--sunken); } -.radio-row summary { display: flex; flex-wrap: wrap; align-items: center; gap: 4px var(--sp-2); min-width: 0; padding: 5px 8px; font-size: var(--fs-sm); cursor: pointer; list-style: none; } -.radio-row summary::-webkit-details-marker { display: none; } +.radio-logbox input[type="search"] { flex: 1 1 0; min-width: 5rem; padding: 4px 10px; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--panel); } +.radio-logbox { flex: 1 1 auto; min-height: 0; container: history / inline-size; } +.radio-log { display: grid; flex: 1 1 0; align-content: start; gap: 4px; height: 0; min-height: clamp(6.5rem, 30vh - 7rem, 24rem); margin: 0; padding: 0 2px 0 0; overflow: hidden auto; overscroll-behavior: contain; list-style: none; scrollbar-width: thin; scroll-margin-top: var(--head); } +.radio-log, .radio-device, .radio-speak, .shell > main { scrollbar-color: color-mix(in srgb, var(--muted) 45%, transparent) transparent; } +.radio-row { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; height: 32px; padding-inline-end: 8px; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--panel); font-size: var(--fs-sm); cursor: pointer; } +.radio-row:hover, .radio-row.picked { border-color: var(--line-strong); } +.radio-row.picked { box-shadow: inset 3px 0 0 var(--accent); } +.radio-pick { display: flex; flex: 1 1 auto; align-items: center; gap: var(--sp-2); min-width: 0; height: 100%; padding: 0 0 0 8px; overflow: hidden; border: 0; border-radius: var(--radius-sm); background: transparent; color: inherit; font: inherit; line-height: 20px; text-align: left; white-space: nowrap; cursor: pointer; } +.radio-pick > * { flex: none; } .radio-row time { color: var(--muted); font-variant-numeric: tabular-nums; } .radio-dir { display: inline-flex; color: var(--muted); } .radio-row[data-dir="sent"] .radio-dir { color: var(--accent); } -.radio-route { font-weight: 600; overflow-wrap: anywhere; } -.radio-line { flex: 1 1 160px; min-width: 0; overflow: hidden; color: var(--muted); text-overflow: ellipsis; white-space: nowrap; } -.radio-full { margin: 0; padding: 6px 10px 8px; border-top: 1px solid var(--line); white-space: pre-wrap; overflow-wrap: anywhere; font-size: var(--fs-sm); } -@media (min-width: 641px) { - .knob-label { flex: none; } +.radio-pick > .radio-route { flex: 0 1 auto; min-width: 2em; max-width: 40%; overflow: hidden; font-weight: 600; text-overflow: ellipsis; } +.radio-pick > .radio-line { flex: 1 1 0; min-width: 0; overflow: hidden; color: var(--muted); text-overflow: ellipsis; } +.radio-row .readers { flex: none; flex-wrap: nowrap; gap: 0; margin: 0; padding-inline-start: 4px; } +.radio-row .reader + .reader, .radio-row .reader + .readers-more { margin-inline-start: -7px; } +.radio-row .reader .avatar { width: 20px; height: 20px; box-shadow: 0 0 0 1.5px var(--panel); } +.radio-row .readers-more { position: relative; line-height: 18px; box-shadow: 0 0 0 1.5px var(--panel); } +.radio-row .readers-fold { display: none; } +.radio-full { margin: 0; padding: var(--sp-2) var(--sp-3); border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--sunken); white-space: pre-wrap; overflow-wrap: anywhere; font-size: var(--fs-sm); } +.popup-readers { display: grid; gap: 6px; margin: 0; padding: 0; list-style: none; } +.popup-reader { display: flex; flex-wrap: wrap; align-items: center; gap: 4px var(--sp-2); min-width: 0; font-size: var(--fs-sm); } +.radio-actions { display: flex; flex-wrap: wrap; gap: var(--sp-2); justify-content: flex-end; } +.radio-copy[data-copied="true"] { border-color: color-mix(in srgb, var(--ok) 55%, var(--line)); color: var(--ok); } +.radio-copy[data-copied="false"] { border-color: color-mix(in srgb, var(--bad) 55%, var(--line)); color: var(--bad); } +.radio-said { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } +.radio-home { display: flex; flex-direction: column; gap: var(--sp-2); height: 100%; } +.radio-home > * { flex: none; } +.radio-home > .radio-grid { flex: 1 1 0; min-height: 0; grid-template-rows: minmax(0, 1fr); } +.radio-home > .radio-card { flex: 1 1 0; min-height: 0; } +.radio-home .radio-log { min-height: 0; } +@container radio (max-width: 52rem) { + .radio-grid { grid-template-columns: minmax(0, 1fr); } + .radio-home-radio > .radio-grid { flex: none; grid-template-rows: none; } + .radio-home-radio .radio-log { flex: none; height: auto; overflow: visible; } +} +@container history (max-width: 34rem) { + .radio-row, .radio-pick { gap: 4px; } + .radio-pick { padding-inline-start: 6px; } + .radio-pick > time { flex: 0 1 auto; min-width: 0; overflow: hidden; font-size: var(--fs-xs); text-overflow: ellipsis; } + .radio-pick > .pill { padding: 0 6px; } + .radio-pick > .radio-route { max-width: 30%; } + .radio-pick > .radio-line { min-width: 4em; } + .radio-row .reader:nth-child(n + 4), .radio-row .readers-more:not(.readers-fold) { display: none; } + .radio-row .readers-fold { display: block; } } @media (max-width: 640px) { - body:not(.fit) .radio-spot { max-height: none; } - .radio-log { max-height: calc(100dvh - var(--head) - var(--sp-3)); overflow-y: auto; overscroll-behavior: contain; scroll-margin-top: var(--head); } - .radio-row summary { gap: 0 var(--sp-2); padding: 3px 8px; line-height: 1.3; } + .radio-spot { padding: var(--sp-2); } +} +@media (width < 48rem), (height < 45rem), (width < 80rem) and (height < 46.5rem), (width < 61rem) and (height < 61rem) { + .radio-spot .radio-log { flex: none; height: auto; min-height: 0; max-height: calc(100dvh - var(--head) - var(--sp-3)); } + body:is(.fit, .pane) .spot-host:has(> .radio-spot:not([hidden])) + main { min-height: calc(100dvh - var(--head) - var(--sp-4)); } +} +@media (min-width: 80rem) and (min-height: 45rem), (min-width: 61rem) and (min-height: 46.5rem), (min-width: 48rem) and (min-height: 61rem) { + .radio-spot:not([hidden]) { grid-template-columns: clamp(22rem, 100% - 34rem - var(--sp-3), 26rem) minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); gap: var(--sp-2) var(--sp-3); max-height: 46vh; margin-bottom: var(--sp-2); padding: var(--sp-2) var(--sp-3); } + .radio-spot > .radio-grid { display: contents; } + .radio-spot > .spot-bar { grid-area: 1 / 2; } + .radio-spot .radio-device { grid-area: 1 / 1 / 3; } + .radio-spot .radio-column { grid-area: 2 / 2; gap: var(--sp-2); } + .radio-spot .radio-speak { flex: none; } + .radio-spot .radio-log { min-height: 4.25rem; } + .radio-spot .composer { grid-template-columns: auto minmax(0, 1fr); } + .radio-spot .composer > * { grid-column: 1 / -1; } + .radio-spot .composer > .voice-note:not([hidden]) { grid-column: 1; } + .radio-spot .composer > .voice-note:not([hidden]) + .actions { grid-column: 2; } +} +@media (min-width: 80rem) and (45rem <= height <= 66rem), (min-width: 61rem) and (46.5rem <= height <= 66rem), (min-width: 48rem) and (61rem <= height <= 66rem), (min-width: 48rem) and (width < 56rem) and (min-height: 61rem) { + body.fit .shell:has(> .spot-host > .radio-spot:not([hidden])) { padding-bottom: var(--sp-4); } + body.fit .spot-host:has(> .radio-spot:not([hidden])) + main { padding-block: var(--sp-3); } + .radio-spot:not([hidden]) { gap: 4px var(--sp-3); margin-bottom: 4px; padding-block: 4px; } + .radio-spot .radio-column { gap: 4px; } + .radio-spot .radio-card { gap: 4px; padding: 4px var(--sp-2); } + .radio-spot .radio-card-head { min-height: 24px; } + .radio-spot .radio-card-head > .star, .radio-spot .knob-row .btn, .radio-spot .radio-check, .radio-spot .radio-filters .btn { padding-block: 2px; } + .radio-spot .radio-device { display: grid; grid-template-columns: auto auto minmax(0, max-content) minmax(0, 1fr) auto auto; align-content: start; gap: 4px var(--sp-2); } + .radio-spot .radio-device > :is(.radio-card-head, .radio-face) { display: contents; } + .radio-spot .radio-device > .radio-card-head > .group-title { grid-area: 1 / 1; margin: 0; } + .radio-spot .radio-device > .radio-card-head > .star { grid-area: 1 / 6; } + .radio-spot .radio-display { display: grid; grid-area: 1 / 2 / 2 / 6; grid-template-columns: subgrid; align-items: center; padding-block: 1px; } + .radio-spot .radio-caption { z-index: 1; grid-area: 1 / 3 / 2 / 5; gap: 4px; min-height: 0; padding: 0 4px; background-color: var(--sunken); background-image: linear-gradient(var(--ok-soft), var(--ok-soft)); } + .radio-spot .radio-caption strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; } + .radio-spot .radio-caption .caption-line { flex: 1 0 4rem; } + .radio-spot .radio-caption .avatar { width: 20px; height: 20px; } + .radio-spot .radio-caption .btn { padding: 4px; } + .radio-spot .radio-modes { grid-area: 2 / 1 / 3 / 6; justify-self: start; padding: 1px; } + .radio-spot .radio-modes button { padding-block: 2px; } + .radio-spot .radio-check { grid-area: 2 / 6; } + .radio-spot .radio-knobs { grid-area: 3 / 1 / 4 / -1; row-gap: 0; } + .radio-spot .knob-row { min-height: 24px; } + .radio-spot .radio-device > .radio-station { grid-column: 1 / -1; padding-top: 4px; } + .radio-spot .radio-station > summary { min-height: 24px; } + .radio-spot .radio-speak { flex-flow: row wrap; align-items: center; gap: 2px var(--sp-2); } + .radio-spot .radio-speak > :is(.radio-card-head, .composer), .radio-spot .radio-speak .composer > .actions { display: contents; } + .radio-spot .radio-speak::before { content: ""; order: 3; flex-basis: 100%; } + .radio-spot .radio-speak .composer-grid { order: 1; flex: 1 1 0; } + .radio-spot .radio-speak .composer-grid .field { padding-block: 2px; } + .radio-spot .radio-speak .star { margin-inline-start: 0; } + .radio-spot .radio-speak textarea { order: 4; flex: 1 1 7rem; height: 32px; min-height: 32px; } + .radio-spot .radio-speak .composer-hint { display: none; } + .radio-spot .radio-speak .actions > * { order: 5; } + .radio-spot .radio-speak .composer-status { flex: 1 1 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .radio-spot .radio-speak .voice-note { order: 4; flex: 0 1 auto; flex-wrap: nowrap; gap: 4px; min-width: 0; } + .radio-spot .radio-speak .voice-note .btn { padding-block: 4px; } + .radio-spot .radio-speak .voice-replay { display: none; } + .radio-spot .radio-speak .voice-note .voice-play { display: inline-flex; } + .radio-spot .radio-speak .voice-words, .radio-spot .caption-verb { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } + .radio-spot .radio-tabs { padding: 1px; } + .radio-spot .radio-tabs button { padding-block: 1px; } + .radio-spot .radio-logbox :is(.radio-filters .field, input[type="search"]) { padding-block: 1px; } } diff --git a/tests/e2e/bidi.mjs b/tests/e2e/bidi.mjs index 3b98978..adff41b 100644 --- a/tests/e2e/bidi.mjs +++ b/tests/e2e/bidi.mjs @@ -10,6 +10,7 @@ import {join} from "node:path"; const [binary, planFile] = process.argv.slice(2); const plan = JSON.parse(readFileSync(planFile, "utf8")); const profile = mkdtempSync(join(tmpdir(), "bidi-")); +writeFileSync(join(profile, "user.js"), ['user_pref("media.navigator.streams.fake", true);', 'user_pref("media.navigator.permission.disabled", true);', ""].join("\n")); const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const port = await new Promise((resolve) => { const probe = createServer().listen(0, "127.0.0.1", () => { diff --git a/tests/e2e/test_orchestrator_e2e.py b/tests/e2e/test_orchestrator_e2e.py index a78915b..aa73ebe 100644 --- a/tests/e2e/test_orchestrator_e2e.py +++ b/tests/e2e/test_orchestrator_e2e.py @@ -398,7 +398,8 @@ OVERLAP = """ found.push(`${called(a.node)} × ${called(b.node)}`); } })); - const outside = boxes.filter(({box}) => box.right > root.getBoundingClientRect().right + 0.5).map(({node}) => called(node)); + const framed = (node) => (getComputedStyle(node).display === "contents" ? framed(node.parentElement) : node); + const outside = boxes.filter(({box}) => box.right > framed(root).getBoundingClientRect().right + 0.5).map(({node}) => called(node)); return {found, outside}; }; """ @@ -464,6 +465,8 @@ MEDIA = """ ADD_STATION = """(async () => {@HELPERS@ const clock = (date) => `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`; location.hash = "#stream/radio"; + const fold = await until(() => document.querySelector("#radio-spot details.radio-station"), 8000); + fold.open = true; const edit = await until(() => all("#radio-spot button").find((button) => text(button) === "Edit stations" && button.getClientRects().length), 8000); edit.click(); const form = await until(() => document.querySelector('.sheet-box form[aria-label="Stations"]'), 8000); @@ -495,6 +498,8 @@ RADIO_STATE = """(async () => {@HELPERS@@MEDIA@ })()""".replace("@HELPERS@", HELPERS).replace("@MEDIA@", MEDIA) RADIO_VIEW = """(async () => {@HELPERS@@MEDIA@ location.hash = "#stream/radio"; + const fold = await until(() => document.querySelector("#radio-spot details.radio-station"), 8000); + fold.open = true; const row = await until(() => all('#radio-spot [data-station="0"]').find((item) => item.getClientRects().length), 8000); if (!row) { const initial = JSON.parse(document.getElementById("state").textContent); @@ -2070,7 +2075,7 @@ class TestOrchestratorE2E(HubCase): self.assertEqual(sent["inline"], ["static", True, True]) self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], CHOICE_CHANNELS, ["Record"])) self.assertEqual(sent["heads"], [["Read aloud", "Read aloud: the classes and agents the radio sounds for"], ["Cancel mayday", "Cancel mayday: lift the radio silence so the agents write again; your passkey signs it"]]) - self.assertEqual((sent["tall"], sent["wide"]), (False, False)) + self.assertEqual((sent["tall"], sent["wide"]), (width == 390, False)) self.assertEqual([run["cls"] for run in sent["runs"]], CHOICE_CHANNELS) for run in sent["runs"]: direct = run["cls"] in ("post", "call") @@ -2082,8 +2087,8 @@ class TestOrchestratorE2E(HubCase): self.assertEqual([entry[1:] for entry in saved["classes"] if entry[0] == "MAYDAY"], [["true", True]]) self.assertEqual((saved["kept"], saved["after"]), ([float(squelch), tone == "true", post == "true"], ["false", False])) self.assertEqual(saved["general"], {"sections": ["Ambience", "Location", "Appearance", "Music", "Notifications", "Passkey"], "radio": 0}) - self.assertEqual((saved["tall"], saved["wide"]), (False, False)) - self.assertEqual(read, {"squelch": float(squelch), "tone": tone == "true", "post": post == "true", "tall": False, "wide": False}) + self.assertEqual((saved["tall"], saved["wide"]), (width == 390, False)) + self.assertEqual(read, {"squelch": float(squelch), "tone": tone == "true", "post": post == "true", "tall": width == 390, "wide": False}) heads = {"post": ["post", "--to", "Stage"], "call": ["send", "call", "--to", "Stage"], "newsletter": ["post"]} radio = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO] sends = [(width, cls) for width, _ in WIDTHS for cls in CHOICE_CHANNELS] @@ -2122,7 +2127,7 @@ class TestOrchestratorE2E(HubCase): self.assertEqual((sent["closed"], sent["open"], sent["inline"]), ([True, "false"], [False, "true", True], ["static", True, True])) self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], CHOICE_CHANNELS, ["Record"])) self.assertEqual(sent["heads"], [["Read aloud", "Read aloud: the classes and agents the radio sounds for"], ["Cancel mayday", hint]]) - self.assertEqual((sent["tall"], sent["wide"]), (False, False)) + self.assertEqual((sent["tall"], sent["wide"]), (width == 390, False)) self.assertEqual([run["cls"] for run in sent["runs"]], CHOICE_CHANNELS) for run in sent["runs"]: direct = run["cls"] in ("post", "call") diff --git a/tests/e2e/test_radio_layout_e2e.py b/tests/e2e/test_radio_layout_e2e.py new file mode 100644 index 0000000..a4a0771 --- /dev/null +++ b/tests/e2e/test_radio_layout_e2e.py @@ -0,0 +1,1258 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import time +import unittest +from pathlib import Path +from unittest import mock + +HERE = Path(__file__).resolve().parent +sys.path[:0] = [str(HERE.parent), str(HERE)] + +import test_orchestrator_e2e as base +from hub_case import HubCase +from kvb_orchestrator import receipts, skill_scripts +from kvb_orchestrator.presence import SNAPSHOT +from kvb_orchestrator.view import RADIO_WINDOW + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/radio-layout-shots")) +LIVE = "f000000000000001" +SILENCE = "f000000000000002" +NEW_ALARM = "disk full again: the cleanup freed too little" +NAMES = ["Skills", "Stage", "Docs", "Atlas", "Beacon", "Comet", "Delta", "Echo", "Falcon", "Harbor"] +SESSIONS = {f"s{index}": name for index, name in enumerate(NAMES, start=1)} +LONG = "Disk at ninety percent on the build host: " + "the gate keeps the swarm waiting while the cache, the images and the logs keep growing; " * 4 +FILLERS = 24 +WIDTHS = (*base.WIDTHS, (960, 800)) +NARROW = (390, 960) +STAGE_SHARE = 0.12 +BANDS = ((1280, 720), (976, 744), (768, 976)) +SHORT = ((800, 600), (1024, 600), (1280, 600), (1366, 657)) +ABOVE = ((800, 976), (960, 976), (976, 744), (1024, 744), (1366, 720)) +LAPTOPS = ((1280, 720), (1366, 768), (1440, 900), (1536, 864), (1920, 1080), (1024, 768), (1680, 1050), (820, 1180), (768, 1024), *ABOVE, *SHORT) +DUPS = ("dup first", "dup second") +VIEWS = ("#stream", "#agents/orbit") +STATES = ("idle", "stations", "voice", "speech", "mayday", "mayday-long") +ALARMS = { + "mayday": "disk full", + "mayday-long": "disk full on the build host: every agent pauses its writing steps until the operator frees space under /var/lib/docker and confirms the cleanup " + "on the radio; the gate queue stays frozen, the deploy of the production worktree waits, and every held test run restarts after the clear of this mayday", +} +BANNER_MAX = 48 +FOCUS_SIZES = ((1366, 768), (390, 844)) +MAIN_SHARE = 0.54 +PLAY_MIN = {"BUTTON": (24, 24), "AUDIO": (200, 30)} +POPOVER_SIZES = ((1366, 768), (1280, 720), (390, 844)) +HOME_RADIO = [{"kind": "panel", "id": "radio-device", "w": 6, "h": 6}, {"kind": "panel", "id": "radio", "w": 12, "h": 7}] +STREAMS = [{"name": f"Station {index}", "url": f"https://radio.example/{index}.mp3", "from": "00:00", "to": "24:00", "days": list(range(7)), "on": False, "via": []} for index in (1, 2, 3)] +PARTS = ["radio", "radio-device", "radio-speak", "radio-log"] +DEFAULTS = {"radio": [12, 7], "radio-device": [6, 6], "radio-speak": [6, 5], "radio-log": [6, 5]} +SIZES = {"radio": [12, 9], "radio-device": [5, 7], "radio-speak": [7, 6], "radio-log": [8, 6]} +LISTED = {"radio-log"} +SCROLLER = {"radio": "radio-log", "radio-device": None, "radio-speak": None, "radio-log": "radio-log"} +PROBES = """ + const transitions = window.e2eTransitions || (window.e2eTransitions = []); + if (document.startViewTransition && !transitions.wrapped) { + const start = document.startViewTransition.bind(document); + document.startViewTransition = (update) => { + const run = start(update); + transitions.push(run); + return run; + }; + transitions.wrapped = true; + } + const settle = () => Promise.all(transitions.map((run) => run.finished.catch(() => null))); + const press = (node) => { + node.dispatchEvent(new MouseEvent("mousedown", {bubbles: true, cancelable: true, view: window})); + if (node.matches('button, input, select, textarea, summary, a[href], [tabindex]')) { + node.focus(); + } else if (document.activeElement) { + document.activeElement.blur(); + } + node.dispatchEvent(new MouseEvent("mouseup", {bubbles: true, cancelable: true, view: window})); + node.click(); + }; + const box = (node) => node.getBoundingClientRect(); + const ownStar = (owner) => all(".star", owner).find((node) => node.closest("[data-panel], [data-item]") === owner) || null; + const openSpot = async () => { + await until(() => typeof Nav === "object" && document.getElementById("radio-spot"), 8000); + const toggle = document.getElementById("radio-open"); + if (toggle.getAttribute("aria-expanded") !== "true") { + toggle.click(); + await sleep(300); + } + return document.getElementById("radio-spot"); + }; + const closeSpot = async () => { + const toggle = document.getElementById("radio-open"); + if (toggle.getAttribute("aria-expanded") === "true") { + toggle.click(); + await sleep(200); + } + }; + const longRow = (root) => all(".radio-row", root).find((item) => text(item.querySelector(".radio-line")).startsWith("Disk at ninety")); + const popup = () => document.getElementById("popup"); + const openRow = async (row) => { + row.querySelector(".radio-pick").click(); + return until(() => popup().open && popup().querySelector(".radio-full") ? popup() : null, 4000); + }; + const shown = (node) => node.getClientRects().length > 0; + const scrolls = (node) => { + const look = getComputedStyle(node); + return (node.scrollHeight > node.clientHeight + 1 && ["auto", "scroll"].includes(look.overflowY)) || (node.scrollWidth > node.clientWidth + 1 && ["auto", "scroll"].includes(look.overflowX)); + }; + const scrollersIn = (root) => [root, ...all("*", root)].filter((node) => node instanceof HTMLElement && node.tagName !== "SELECT" && node.tagName !== "TEXTAREA" && shown(node) && scrolls(node)).map((node) => [...node.classList].at(-1) || node.tagName); + const tile = (id) => document.querySelector(`#main .home-tile[data-pin="panel:${id}"]`); + const pick = (root) => { + const [channel, recipient] = all("select", root.querySelector("form.composer")); + return {channel: channel.value, recipient: recipient.value, toShown: !recipient.closest("label").hidden, focused: document.activeElement === root.querySelector("form.composer textarea")}; + }; +""" +LAYOUT = """(async () => {@HELPERS@@PROBES@ + await ViewStore.update("home.pins", () => []); + const spot = await openSpot(); + spot.querySelector('.radio-tabs [data-tab="all"]').click(); + await until(() => all(".radio-row .reader", spot).length > 20 && longRow(spot), 20000); + await sleep(300); + window.scrollTo(0, 0); + const cardOf = (node) => (node.parentElement && node.parentElement.closest(".radio-card")) || spot; + const wider = all("*", spot).filter((node) => node.tagName !== "OPTION" && shown(node) && box(node).width > 0).filter((node) => { + const own = box(node); + const card = box(cardOf(node)); + return own.left < card.left - 1 || own.right > card.right + 1; + }).map((node) => `${node.tagName}.${node.getAttribute("class")}`); + const list = spot.querySelector(".radio-log"); + const listLook = getComputedStyle(list); + const rows = all(".radio-row", spot); + const lineHeight = parseFloat(getComputedStyle(rows[0].querySelector(".radio-line")).lineHeight); + const lines = rows.map((row) => { + const line = row.querySelector(".radio-line"); + const look = getComputedStyle(line); + return {height: Math.round(box(row).height), nowrap: look.whiteSpace === "nowrap", ellipsis: look.textOverflow === "ellipsis", flat: line.scrollHeight <= line.clientHeight + 1 && row.scrollHeight <= row.clientHeight + 1, fits: row.scrollWidth <= row.clientWidth + 1 && box(row).right <= box(list).right + 1, width: line.clientWidth}; + }); + const long = longRow(spot).querySelector(".radio-line"); + const avatars = rows.filter((row) => row.querySelector(".reader")).map((row) => { + const edge = box(row); + const line = box(row.querySelector(".radio-line")); + const faces = all(".reader .avatar", row).filter(shown).map(box); + return { + total: Number((row.querySelector(".readers").getAttribute("aria-label").match(/\\d+/) || ["0"])[0]), + count: faces.length, + more: all(".readers-more", row).filter(shown).map(text), + inside: faces.every((face) => face.left >= edge.left - 1 && face.right <= edge.right + 1 && face.top >= edge.top - 1 && face.bottom <= edge.bottom + 1), + after: faces.every((face) => face.left >= line.right - 1), + stacked: faces.slice(1).every((face, index) => face.left < faces[index].right), + sliver: faces.length ? Math.min(...faces.map((face, index) => (index + 1 < faces.length ? faces[index + 1].left : face.right) - face.left)) : null, + }; + }); + const [device, speak, history] = ["radio-device", "radio-speak", "radio-log"].map((id) => box(spot.querySelector(`[data-panel="${id}"]`))); + const owners = [spot, ...all("[data-panel]", spot)]; + const controls = all('button, input, select, textarea, summary, [role="tab"]', spot).filter((node) => shown(node) && !node.classList.contains("star")); + const overlap = (a, b) => Math.max(0, Math.min(a.right, b.right) - Math.max(a.left, b.left)) * Math.max(0, Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top)); + const covered = owners.map(ownStar).filter(Boolean).flatMap((star) => controls.filter((node) => !node.contains(star) && overlap(box(star), box(node)) > 1).map((node) => `${star.title} over ${node.getAttribute("aria-label") || text(node)}`)); + const knobs = all(".radio-knobs .knob-row", spot).map((row) => Math.round(box(row.querySelector(".knob-label")).left)); + return { + page: [document.documentElement.scrollWidth, innerWidth], tall: [document.documentElement.scrollHeight, innerHeight, Math.round(box(spot).height)], + wider, scrollers: scrollersIn(spot), + list: {overflowY: listLook.overflowY, scrollbar: [listLook.scrollbarWidth, listLook.scrollbarColor], scrolls: list.scrollHeight > list.clientHeight + 1}, + main: getComputedStyle(document.getElementById("main")).scrollbarColor, + heights: [...new Set(lines.map((line) => line.height))], lineHeight, rows: rows.length, + single: lines.every((line) => line.nowrap && line.ellipsis && line.flat && line.fits), + narrowest: Math.min(...lines.map((line) => line.width)), + long: [long.scrollWidth > long.clientWidth, getComputedStyle(long).textOverflow], + avatars: {rows: avatars.length, most: Math.max(...avatars.map((row) => row.count)), inside: avatars.every((row) => row.inside), after: avatars.every((row) => row.after), stacked: avatars.filter((row) => row.count > 1).every((row) => row.stacked)}, + folds: avatars.map((row) => [row.total, row.count, row.more]), + sliver: Math.min(...avatars.map((row) => row.sliver)), + order: {stacked: device.bottom <= speak.top + 1 && speak.bottom <= history.top + 1 && Math.abs(device.left - speak.left) < 2, beside: device.right <= speak.left && speak.bottom <= history.top + 1 && Math.abs(speak.left - history.left) < 2}, + labels: [...new Set(knobs)].length, + stars: owners.map((owner) => [owner.dataset.panel, Boolean(ownStar(owner))]), covered, + stations: [Boolean(spot.querySelector("details.radio-station")), spot.querySelector("details.radio-station").open], + }; +})()""" +POPUP = """(async () => {@HELPERS@@PROBES@ + const spot = document.getElementById("radio-spot"); + const copied = []; + navigator.clipboard.writeText = (value) => { + copied.push(value); + return Promise.resolve(); + }; + const row = longRow(spot); + row.scrollIntoView({block: "center"}); + await sleep(200); + const dialog = await openRow(row); + if (!dialog) { + return {error: "no popup"}; + } + const card = dialog.querySelector(".popup-box"); + const fields = Object.fromEntries(all("dl.meta > div", card).map((pair) => [text(pair.querySelector("dt")), text(pair.querySelector("dd"))])); + const readers = all(".popup-reader", card).map((item) => ({session: item.dataset.session, name: text(item.querySelector("strong")), time: text(item.querySelector(".muted")), acked: item.dataset.acked})); + const copy = card.querySelector(".radio-copy"); + const said = card.querySelector(".radio-said"); + const heard = () => [copy.getAttribute("aria-label"), said ? text(said) : null]; + const region = said ? [said.getAttribute("role"), said.getAttribute("aria-live"), card.contains(said), shown(said) && box(said).width <= 1] : null; + copy.click(); + const done = await until(() => (copy.dataset.copied === "true" ? text(copy) : null), 3000); + const success = heard(); + const buttons = all(".radio-actions button", card).map(text); + await until(() => copy.getAttribute("aria-label") === "Copy" && copy.dataset.copied === "", 4000); + const reset = heard(); + navigator.clipboard.writeText = () => Promise.reject(new DOMException("Denied", "NotAllowedError")); + copy.click(); + await until(() => copy.dataset.copied === "false", 3000); + const failure = heard(); + return { + open: dialog.open, title: text(card.querySelector(".popup-head h2")), fields, full: dialog.querySelector(".radio-full").textContent, readers, + heading: text(card.querySelector("h3")), buttons, copied, shown: done, region, success, reset, failure, + stray: [...card.childNodes].filter((node) => node.nodeType === 3).map((node) => node.textContent), + inView: (() => { + const edge = box(card); + return edge.left >= 0 && edge.top >= 0 && edge.right <= innerWidth + 1 && edge.bottom <= innerHeight + 1; + })(), + }; +})()""" +CLOSE_REPLY = """(async () => {@HELPERS@@PROBES@ + const spot = document.getElementById("radio-spot"); + (document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await sleep(200); + const escaped = !popup().open; + const dialog = await openRow(longRow(spot)); + const card = box(dialog.querySelector(".popup-box")); + const x = card.left > 8 ? Math.floor(card.left / 2) : Math.ceil((card.right + document.documentElement.clientWidth) / 2); + const hit = document.elementFromPoint(x, Math.round(innerHeight / 2)); + hit.click(); + await sleep(200); + const outside = [hit === popup(), !popup().open]; + await openRow(longRow(spot)); + all(".radio-actions button", popup()).find((button) => text(button) === "Reply").click(); + await sleep(300); + return {escaped, outside, reply: {open: popup().open, ...pick(spot)}}; +})()""" +HOME = """(async () => {@HELPERS@@PROBES@ + const spot = await openSpot(); + const owners = Object.fromEntries(@PARTS@.map((id) => [id, id === "radio" ? spot : spot.querySelector(`[data-panel="${id}"]`)])); + const pressed = {}; + for (const [id, owner] of Object.entries(owners)) { + const star = ownStar(owner); + if (star.getAttribute("aria-pressed") !== "true") { + star.click(); + await sleep(250); + } + pressed[id] = star.getAttribute("aria-pressed"); + } + await until(() => (ViewStore.get("home.pins") || []).length === 4, 5000); + const stored = (ViewStore.get("home.pins") || []).map((pin) => [`${pin.kind}:${pin.id}`, pin.w, pin.h]); + await closeSpot(); + location.hash = "#home"; + await screenShown(8000); + await until(() => @PARTS@.every((id) => tile(id)) && tile("radio-log").querySelector(".radio-row") && tile("radio").querySelector(".radio-row"), 10000); + await sleep(400); + const measure = () => Object.fromEntries(@PARTS@.map((id) => { + const body = tile(id).querySelector(".home-body"); + const list = tile(id).querySelector(".radio-log"); + const edge = box(body); + const rows = list ? all(".radio-row", list).filter((row) => box(row).top >= box(list).top - 1 && box(row).bottom <= box(list).bottom + 1).length : null; + return [id, {scrollers: scrollersIn(tile(id)), rows, inside: list ? box(list).bottom <= edge.bottom + 1 && box(list).top >= edge.top - 1 : null, filled: Math.abs(box(tile(id).querySelector(".radio-home")).height - body.clientHeight + parseFloat(getComputedStyle(body).paddingTop) + parseFloat(getComputedStyle(body).paddingBottom)) <= 2}]; + })); + const fresh = measure(); + const whole = tile("radio"); + const bar = whole.querySelector(".spot-head"); + const gear = bar ? all("button", bar).find((button) => button.getAttribute("aria-label") === "Read aloud") : null; + const clear = bar ? all("button", bar).find((button) => button.getAttribute("aria-label") === "Cancel mayday") : null; + if (gear) { + gear.click(); + await sleep(200); + } + const filters = whole.querySelector(".radio-gear .radio-read"); + const tools = { + gear: gear ? [gear.getAttribute("aria-expanded"), Boolean(filters), filters ? box(filters).bottom <= box(whole).bottom + 1 : null] : null, + clear: clear ? [clear.disabled, clear.title] : null, + }; + if (gear) { + gear.click(); + } + const content = { + tiles: all("#main .home-tile").map((node) => node.dataset.pin), + radio: [".radio-device", ".radio-speak", ".radio-logbox"].map((selector) => Boolean(tile("radio").querySelector(selector))), + device: [text(tile("radio-device").querySelector('[data-field="mode"]')), all(".radio-knobs input[type=range]", tile("radio-device")).length], + speak: [Boolean(tile("radio-speak").querySelector("form.composer textarea")), tile("radio-speak").querySelectorAll("form.composer select option").length > 0], + log: [tile("radio-log").querySelectorAll(".radio-row").length, tile("radio").querySelectorAll(".radio-row").length, document.querySelectorAll("#radio-spot .radio-row").length], + gone: all("#main .home-tile.gone").length, + stars: all("#main .home-tile .home-body .star").length, + ids: all("#main .home-tile .home-body [id]").map((node) => node.id), + }; + const count = (id) => tile(id).querySelectorAll(".radio-row").length; + const before = [count("radio-log"), count("radio")]; + await fetch("/api/voice/@LIVE@", {cache: "no-store"}); + window.dispatchEvent(new Event("focus")); + const first = (id) => text(tile(id).querySelector(".radio-row .radio-line")); + const live = await until(() => (count("radio-log") > before[0] && count("radio") > before[1] && first("radio-log").startsWith("live row") ? [first("radio-log"), first("radio")] : null), 20000); + tile("radio-device").querySelector('.radio-modes button[data-mode="quiet"]').click(); + await sleep(200); + const mode = [text(tile("radio").querySelector('[data-field="mode"]')), text(document.querySelector('#radio-spot [data-field="mode"]'))]; + tile("radio-device").querySelector('.radio-modes button[data-mode="auto"]').click(); + await sleep(200); + const sizes = @SIZES@; + await ViewStore.update("home.pins", (pins) => (pins || []).map((pin) => ({...pin, w: sizes[pin.id][0], h: sizes[pin.id][1]}))); + await until(() => @PARTS@.every((id) => tile(id).dataset.w === String(sizes[id][0]) && tile(id).dataset.h === String(sizes[id][1])), 5000); + await sleep(400); + const resized = measure(); + window.scrollTo(0, 0); + return {pressed, stored, fresh, resized, tools, content, live, mode, wide: document.documentElement.scrollWidth > innerWidth + 1}; +})()""" +FIT = """(async () => {@HELPERS@@PROBES@ + await ViewStore.update("home.pins", () => []); + location.hash = "#agents/orbit"; + await screenShown(8000); + const spot = await openSpot(); + await until(() => spot.querySelector(".radio-row"), 8000); + await sleep(500); + const stage = document.querySelector("#main .stage svg"); + const list = spot.querySelector(".radio-log"); + const result = { + fit: document.body.classList.contains("fit"), tall: document.documentElement.scrollHeight > innerHeight, wide: document.documentElement.scrollWidth > innerWidth + 1, + stage: stage ? Math.round(box(stage).height) : 0, height: innerHeight, scrollers: scrollersIn(spot), + list: list.clientHeight, speak: (() => { + const card = spot.querySelector(".radio-speak"); + return card.scrollHeight <= card.clientHeight + 1; + })(), + }; + await closeSpot(); + await sleep(300); + const after = document.querySelector("#main .stage svg"); + result.closed = {boxes: spot.getClientRects().length, tall: document.documentElement.scrollHeight > innerHeight, stage: after ? Math.round(box(after).height) : 0}; + return result; +})()""" +SPOT = """(async () => {@HELPERS@@PROBES@@SPEAKING@ + await ViewStore.update("home.pins", () => []); + location.hash = "@VIEW@"; + await screenShown(8000); + const spot = await openSpot(); + await until(() => spot.querySelector(".radio-row") && spot.querySelectorAll(".radio-device .station").length === 3, 8000); + await settle(); + await sleep(500); + window.scrollTo(0, 0); + const fits = (node) => node.scrollHeight <= node.clientHeight + 1; + const list = spot.querySelector(".radio-log"); + const fold = spot.querySelector("details.radio-station"); + const form = spot.querySelector(".radio-speak form.composer"); + const note = form.querySelector(".voice-note"); + const display = spot.querySelector(".radio-caption"); + const named = (node) => node.getAttribute("aria-label") || text(node) || node.getAttribute("title") || `${node.tagName}.${node.getAttribute("class")}`; + const blocked = () => { + const layer = spot.querySelector(".radio-station[open] > .station-body"); + const marks = [spot.querySelector(".radio-lamp"), spot.querySelector('[data-field="cpu"]'), spot.querySelector(".radio-device .group-title")]; + const folded = (node) => Boolean(node.closest("details:not([open])")) && !node.closest("summary"); + const found = []; + for (const node of [...all('button, input, select, textarea, summary, audio, [role="tab"]', spot), ...marks].filter((item) => shown(item) && !folded(item) && box(item).width > 0 && box(item).height > 0)) { + window.scrollTo(0, 0); + const seen = box(node); + if (seen.bottom > innerHeight) { + window.scrollBy(0, seen.top + seen.height / 2 - innerHeight / 2); + } + const edge = box(node); + const [x, y] = [edge.left + edge.width / 2, edge.top + edge.height / 2]; + const hit = document.elementFromPoint(x, y); + if (!(list.contains(node) && (y < box(list).top || y > box(list).bottom)) && !(hit === node || node.contains(hit) || (layer && hit && layer.contains(hit) && !layer.contains(node)))) { + found.push(`${named(node)} <- ${hit ? `${hit.tagName}.${hit.getAttribute("class")}#${hit.id}` : "null"}`); + } + } + window.scrollTo(0, 0); + return found; + }; + const stack = () => { + const card = spot.querySelector(".radio-logbox"); + const head = [card.querySelector(".radio-tabs"), card.querySelector('input[type="search"]')].map(box); + const chips = all(".chip-select, .radio-filters > button", card).map(box); + return {head: Math.round(Math.max(...head.map((edge) => edge.bottom))), chips: [Math.round(Math.min(...chips.map((edge) => edge.top))), Math.round(Math.max(...chips.map((edge) => edge.bottom)))], list: Math.round(box(list).top)}; + }; + const measure = () => { + window.scrollTo(0, 0); + const [device, speak, history] = ["radio-device", "radio-speak", "radio-log"].map((id) => box(spot.querySelector(`[data-panel="${id}"]`))); + const svg = document.querySelector("#main .stage svg"); + return { + fit: document.body.classList.contains("fit"), + page: [document.documentElement.scrollWidth, document.documentElement.scrollHeight, innerWidth, innerHeight], + scrollers: scrollersIn(spot), cards: [fits(spot.querySelector(".radio-device")), fits(spot.querySelector(".radio-speak"))], + main: Math.round(box(document.getElementById("main")).height), floor: Math.round(innerHeight * @MAIN@ - box(document.getElementById("spot-host")).top), + full: Math.round(innerHeight - document.getElementById("head").offsetHeight - 16), stack: stack(), beneath: box(document.getElementById("main")).top >= box(spot).bottom - 1, + stage: svg ? Math.round(box(svg).height) : null, + list: list.clientHeight, rows: all(".radio-row", list).filter((row) => box(row).top >= box(list).top - 1 && box(row).bottom <= box(list).bottom + 1).length, + order: device.right <= speak.left && device.right <= history.left && speak.bottom <= history.top + 1 && Math.abs(speak.left - history.left) < 2, + active: {stations: fold.open ? all(".station", fold).filter(shown).length : 0, voice: !note.hidden && shown(note), speech: !display.hidden && shown(display)}, + blocked: blocked(), + banner: (() => { + const node = document.getElementById("mayday"); + if (node.hidden || !shown(node)) { + return null; + } + const words = node.querySelector(".text"); + const cancel = node.querySelector("button"); + const edge = box(cancel); + const hit = document.elementFromPoint(edge.left + edge.width / 2, edge.top + edge.height / 2); + return {height: Math.round(box(node).height), title: words.title, full: words.textContent, cut: words.scrollWidth > words.clientWidth + 1, cancel: Boolean(hit && cancel.contains(hit))}; + })(), + play: [note.querySelector(".voice-play"), note.querySelector("audio")].filter((node) => node && shown(node) && box(node).width > 0).map((node) => [node.tagName, Math.round(box(node).width), Math.round(box(node).height)]), + line: (() => { + const node = display.querySelector(".caption-line"); + return node && shown(node) ? [Math.round(node.clientWidth), text(node).length] : null; + })(), + rem: parseFloat(getComputedStyle(document.documentElement).fontSize), + }; + }; + const wanted = @STATES@; + const states = {}; + for (const name of wanted.filter((state) => state === "idle" || state.startsWith("mayday"))) { + states[name] = measure(); + } + if (wanted.includes("stations")) { + const summary = fold.querySelector("summary"); + summary.focus(); + summary.click(); + await sleep(300); + states.stations = measure(); + document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await sleep(200); + states.stations.closed = [fold.open, document.activeElement === summary]; + } + if (wanted.includes("voice")) { + const record = all("button", form).find((button) => button.hasAttribute("aria-pressed")); + record.click(); + await sleep(1300); + record.click(); + const heard = await until(() => !note.hidden && note.querySelector("audio") && form.querySelector("textarea").value, 30000); + await sleep(300); + states.voice = {...measure(), heard: Boolean(heard)}; + const toggle = note.querySelector(".voice-play"); + if (toggle && shown(toggle)) { + toggle.click(); + states.voice.played = Boolean(await until(() => !note.querySelector("audio").paused && toggle.getAttribute("aria-label") === "Pause voice message", 4000)); + toggle.click(); + states.voice.paused = Boolean(await until(() => note.querySelector("audio").paused && toggle.getAttribute("aria-label") === "Play voice message", 4000)); + } + const trash = all("button", note).find((button) => button.getAttribute("aria-label") === "Remove recording"); + if (trash) { + trash.click(); + } + await sleep(200); + } + if (wanted.includes("speech")) { + const found = await cue("@CUE@"); + await sleep(300); + states.speech = {...measure(), who: found && !found.error ? found.who : found}; + const stop = display.querySelector("button"); + if (stop) { + stop.click(); + } + await until(() => display.hidden, 8000); + } + return states; +})()""" +POP = """(async () => {@HELPERS@@PROBES@ + await ViewStore.update("home.pins", () => @PINS@); + location.hash = "@VIEW@"; + await screenShown(8000); + if (@SPOT@) { + await openSpot(); + } else { + await closeSpot(); + } + await settle(); + await sleep(500); + const outside = (layer) => { + const edge = box(layer); + const clips = [["viewport", {top: 0, bottom: innerHeight, left: 0, right: innerWidth}]]; + for (let node = layer.parentElement; node && node !== document.documentElement; node = node.parentElement) { + const look = getComputedStyle(node); + if (look.overflowX !== "visible" || look.overflowY !== "visible") { + clips.push([`${node.tagName}.${node.getAttribute("class")}`, box(node)]); + } + } + return clips.filter(([, clip]) => edge.top < clip.top - 1 || edge.bottom > clip.bottom + 1 || edge.left < clip.left - 1 || edge.right > clip.right + 1) + .map(([name, clip]) => `${name} [${Math.round(clip.top)},${Math.round(clip.bottom)}] vs [${Math.round(edge.top)},${Math.round(edge.bottom)}]`); + }; + const out = []; + for (const selector of @ROOTS@) { + const root = document.querySelector(selector); + if (!root || !(await until(() => root.querySelectorAll(".station").length === 3, 8000))) { + out.push({selector, error: "no stations"}); + continue; + } + const fold = root.querySelector("details.radio-station"); + const summary = fold.querySelector("summary"); + const layer = fold.querySelector(".station-body"); + fold.scrollIntoView({block: "center"}); + await sleep(200); + summary.focus(); + summary.click(); + await sleep(300); + const whole = all(".station", layer).filter((row) => box(row).top >= box(layer).top - 1 && box(row).bottom <= box(layer).bottom + 1).length; + const opened = {open: fold.open, side: fold.dataset.side, height: Math.round(box(layer).height), outside: outside(layer), whole}; + layer.querySelector(".station button").focus(); + document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await sleep(200); + const escape = [fold.open, document.activeElement === summary]; + summary.click(); + await sleep(300); + const again = {open: fold.open, outside: outside(layer)}; + press(document.getElementById("main")); + await sleep(200); + out.push({selector, opened, escape, again, click: [fold.open, document.activeElement === summary, document.activeElement === document.body]}); + } + return out; +})()""" +FOCUS = """(async () => {@HELPERS@@PROBES@ + await ViewStore.update("home.pins", () => []); + location.hash = "#agents/orbit"; + await screenShown(8000); + const spot = await openSpot(); + await until(() => spot.querySelectorAll(".station").length === 3 && spot.querySelector(".radio-row"), 8000); + await settle(); + await sleep(300); + const fold = spot.querySelector("details.radio-station"); + const night = await until(() => all("details.menu").find((menu) => menu.querySelector("summary").getAttribute("aria-label") === "Day/Night"), 8000); + const label = (node) => (node ? `${node.tagName}.${node.getAttribute("class")}[${node.getAttribute("aria-label") || text(node).slice(0, 24)}]` : "null"); + const tab = () => spot.querySelector('.radio-tabs [role="tab"]:not([aria-selected="true"])'); + const cases = {}; + const run = async (key, menu, target) => { + press(menu.querySelector("summary")); + await sleep(250); + const opened = menu.open; + const node = target(); + press(node); + await sleep(400); + const active = document.activeElement; + cases[key] = {opened, closed: !menu.open, active: label(active), summary: Boolean(active && active.matches("summary")), history: Boolean(active && active.closest(".radio-logbox")), body: active === document.body}; + menu.open = false; + await sleep(150); + }; + await run("night-tab", night, tab); + await run("fold-tab", fold, tab); + await run("night-main", night, () => document.getElementById("main")); + await run("fold-main", fold, () => document.getElementById("main")); + press(fold.querySelector("summary")); + await sleep(250); + fold.querySelector(".station button").focus(); + document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await sleep(200); + cases.escape = {closed: !fold.open, toggle: document.activeElement === fold.querySelector("summary")}; + return cases; +})()""" +LOADS = """ + const loads = {count: 0}; + const send = window.fetch.bind(window); + window.fetch = async (path, init) => { + const response = await send(path, init); + if (String(path).startsWith("/api/state")) { + const json = response.json.bind(response); + response.json = () => json().then((value) => { + loads.count += 1; + return value; + }); + } + return response; + }; + const loaded = async (more, ms) => { + const goal = loads.count + more; + const done = await until(() => loads.count >= goal, ms); + await sleep(300); + return Boolean(done); + }; +""" +ROWS = """(async () => {@HELPERS@@PROBES@@LOADS@ + await ViewStore.update("home.pins", () => []); + location.hash = "#agents/orbit"; + await screenShown(8000); + const spot = await openSpot(); + await until(() => spot.querySelectorAll(".radio-row").length > 2, 8000); + await settle(); + await sleep(300); + const rows = () => spot.querySelectorAll(".radio-row").length; + const deliver = async () => { + const before = rows(); + await fetch("/api/voice/@LIVE@", {cache: "no-store"}); + window.dispatchEvent(new Event("focus")); + const done = await until(() => rows() > before, 20000); + await sleep(300); + return Boolean(done); + }; + const row = spot.querySelectorAll(".radio-row")[1]; + const button = row.querySelector(".radio-pick"); + const held = () => { + const active = document.activeElement; + const owner = active ? active.closest(".radio-row") : null; + return {same: active === button, key: owner ? owner.dataset.key : null, pick: Boolean(active && active.matches(".radio-pick")), body: active === document.body}; + }; + button.focus(); + const start = {...held(), want: row.dataset.key}; + const fresh = {...held(), delivered: await deliver()}; + const real = Date.now; + Date.now = () => real.call(Date) + 60000; + window.dispatchEvent(new Event("focus")); + const tick = {...held(), ticked: await loaded(1, 20000)}; + Date.now = real; + const tab = spot.querySelector('.radio-tabs [role="tab"][aria-selected="true"]'); + tab.focus(); + let focusins = 0; + document.addEventListener("focusin", () => { + focusins += 1; + }, true); + const delivered = [await deliver(), await deliver(), await deliver()]; + return {start, fresh, tick, tabs: {delivered, focusins, same: document.activeElement === tab, tab: document.activeElement.getAttribute("data-tab")}}; +})()""" +KEYS = """(async () => {@HELPERS@@PROBES@ + await ViewStore.update("home.pins", () => []); + location.hash = "#agents/orbit"; + await screenShown(8000); + const spot = await openSpot(); + spot.querySelector('.radio-tabs [role="tab"][data-tab="all"]').click(); + const dups = () => all(".radio-row", spot).filter((node) => text(node.querySelector(".radio-line")).startsWith("dup ")); + await until(() => dups().length === 2, 8000); + await settle(); + await sleep(300); + const rows = () => spot.querySelectorAll(".radio-row").length; + const deliver = async () => { + const before = rows(); + await fetch("/api/voice/@LIVE@", {cache: "no-store"}); + window.dispatchEvent(new Event("focus")); + const done = await until(() => rows() > before, 20000); + await sleep(300); + return Boolean(done); + }; + const line = (node) => (node && node.closest(".radio-row") ? text(node.closest(".radio-row").querySelector(".radio-line")) : null); + const out = {keys: dups().map((node) => node.dataset.key)}; + for (const word of @DUPS@) { + const button = dups().find((node) => text(node.querySelector(".radio-line")) === word).querySelector(".radio-pick"); + button.focus(); + const delivered = await deliver(); + const active = document.activeElement; + const result = {delivered, same: active === button, line: line(active), popup: null}; + if (active && active.matches(".radio-pick")) { + active.click(); + result.popup = await until(() => (popup().open && popup().querySelector(".radio-full") ? popup().querySelector(".radio-full").textContent : null), 4000); + (document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true})); + await until(() => !popup().open, 2000); + } + out[word] = result; + } + const victim = all(".radio-row", spot).find((node) => node.dataset.class === "newsletter"); + victim.querySelector(".radio-pick").focus(); + const chip = spot.querySelector('.chip-select[data-chip="class"] select'); + chip.value = "call"; + chip.dispatchEvent(new Event("change", {bubbles: true})); + await sleep(500); + const near = document.activeElement; + out.filtered = {gone: !victim.isConnected, pick: Boolean(near && near.matches(".radio-pick")), class: near && near.closest(".radio-row") ? near.closest(".radio-row").dataset.class : null}; + const search = spot.querySelector('.radio-logbox input[type="search"]'); + search.value = "no radio row says this"; + search.dispatchEvent(new Event("input", {bubbles: true})); + await sleep(500); + out.emptied = {gone: !spot.querySelector(".radio-row"), list: document.activeElement === spot.querySelector("ul.radio-log")}; + search.value = ""; + search.dispatchEvent(new Event("input", {bubbles: true})); + chip.value = ""; + chip.dispatchEvent(new Event("change", {bubbles: true})); + await sleep(300); + return out; +})()""" +BANNER = """(async () => {@HELPERS@@PROBES@@LOADS@ + await ViewStore.update("home.pins", () => []); + location.hash = "#agents/orbit"; + await screenShown(8000); + const banner = document.getElementById("mayday"); + await until(() => !banner.hidden && banner.querySelector("button"), 8000); + await settle(); + await sleep(300); + const records = []; + new MutationObserver((list) => records.push(...list)).observe(banner, {childList: true, subtree: true, characterData: true, attributes: true}); + const cancel = banner.querySelector("button"); + cancel.focus(); + const polled = await loaded(2, 30000); + const steady = {polled, mutations: records.length, focus: document.activeElement === cancel, body: document.activeElement === document.body}; + records.length = 0; + await fetch("/api/voice/@SILENCE@", {cache: "no-store"}); + const again = await loaded(3, 45000); + const added = records.filter((record) => record.type === "childList" && record.addedNodes.length > 0).length; + return {steady, changed: {polled: again, text: text(banner.querySelector(".text")), added, shown: !banner.hidden, cancel: Boolean(banner.querySelector("button"))}}; +})()""" +COMPOSE_HOME = """(async () => {@HELPERS@@PROBES@ + const bodies = []; + const send = window.fetch.bind(window); + window.fetch = (path, init) => { + if (String(path) === "/api/messages") { + bodies.push(JSON.parse(init.body)); + } + return send(path, init); + }; + window.confirm = () => true; + const spot = await openSpot(); + const spotText = spot.querySelector("form.composer textarea"); + spotText.value = "draft kept in the spot"; + spotText.dispatchEvent(new Event("input", {bubbles: true})); + await ViewStore.update("home.pins", () => [{kind: "panel", id: "radio", w: 12, h: 7}, {kind: "panel", id: "radio-speak", w: 6, h: 5}, {kind: "panel", id: "radio-log", w: 6, h: 5}]); + location.hash = "#home"; + await screenShown(8000); + await until(() => tile("radio-speak") && tile("radio-log") && tile("radio") && tile("radio-log").querySelector(".radio-row"), 10000); + await sleep(400); + const homeSpeak = tile("radio-speak"); + const form = (root) => root.querySelector("form.composer"); + const area = (root) => form(root).querySelector("textarea"); + const record = (root) => all("button", form(root)).find((button) => button.hasAttribute("aria-pressed")); + const note = (root) => { + const audio = form(root).querySelector(".voice-note audio"); + return audio ? audio.getAttribute("src").replace("/api/voice/", "").replace(".wav", "") : null; + }; + const drafts = [area(spot).value, area(homeSpeak).value, area(tile("radio")).value]; + record(spot).click(); + await sleep(1200); + const first = record(spot).getAttribute("aria-pressed"); + record(homeSpeak).click(); + const handed = await until(() => (record(homeSpeak).getAttribute("aria-pressed") === "true" ? [record(spot).getAttribute("aria-pressed"), "true"] : null), 5000); + const spotHeard = await until(() => (note(spot) && area(spot).value.includes("hello from the mic") ? area(spot).value : null), 30000); + const homeBefore = area(homeSpeak).value; + await sleep(800); + record(homeSpeak).click(); + const homeHeard = await until(() => (note(homeSpeak) && area(homeSpeak).value.includes("hello from the mic") ? area(homeSpeak).value : null), 30000); + const notes = [note(spot), note(homeSpeak)]; + const sendFrom = async (root, to, words, attach) => { + const [channel, recipient] = all("select", form(root)); + channel.value = "post"; + channel.dispatchEvent(new Event("change", {bubbles: true})); + await until(() => [...recipient.options].some((option) => option.value === to), 8000); + recipient.value = to; + area(root).value = words; + area(root).dispatchEvent(new Event("input", {bubbles: true})); + const box = form(root).querySelector('.voice-note input[type="checkbox"]'); + if (box) { + box.checked = attach; + } + const shownBefore = new Set(all("#toasts .toast")); + form(root).querySelector('button[type="submit"]').click(); + return until(() => all("#toasts .toast").filter((node) => !shownBefore.has(node)).map(text).find((entry) => entry.startsWith("Post to")), 20000); + }; + const spotSent = await sendFrom(spot, "Stage", "plain text from the spot", false); + const homeAttach = Boolean(form(homeSpeak).querySelector('.voice-note input[type="checkbox"]')); + const homeSent = await sendFrom(homeSpeak, "Docs", "voice from the Home tile", true); + await closeSpot(); + document.getElementById("toasts").replaceChildren(); + return {drafts, first, handed, spotHeard, homeBefore, homeHeard, notes, spotSent, homeAttach, homeSent, bodies: bodies.map((body) => [body.to, body.text, body.voice])}; +})()""" +REPLY_HOME = """(async () => {@HELPERS@@PROBES@ + const spotOpen = () => document.getElementById("radio-open").getAttribute("aria-expanded"); + const reply = async (root) => { + const row = longRow(root); + row.scrollIntoView({block: "center"}); + await sleep(200); + await openRow(row); + all(".radio-actions button", popup()).find((button) => text(button) === "Reply").click(); + await sleep(300); + }; + await reply(tile("radio-log")); + const fromLog = {spot: spotOpen(), popup: popup().open, speak: pick(tile("radio-speak")), whole: pick(tile("radio"))}; + await reply(tile("radio")); + const fromWhole = {spot: spotOpen(), whole: pick(tile("radio"))}; + const sendFrom = async (root, words) => { + const area = root.querySelector("form.composer textarea"); + area.value = words; + area.dispatchEvent(new Event("input", {bubbles: true})); + const shownBefore = new Set(all("#toasts .toast")); + root.querySelector('form.composer button[type="submit"]').click(); + return until(() => all("#toasts .toast").filter((node) => !shownBefore.has(node)).map(text).find((entry) => entry.startsWith("Post to")), 20000); + }; + const sent = await sendFrom(tile("radio"), "reply from the Home radio"); + const questions = []; + window.confirm = (question) => { + questions.push(question); + return true; + }; + const clear = all(".spot-head button", tile("radio")).find((button) => button.getAttribute("aria-label") === "Cancel mayday"); + const enabled = clear ? !clear.disabled : null; + const shownBefore = new Set(all("#toasts .toast")); + if (clear) { + clear.click(); + } + const lifted = await until(() => all("#toasts .toast").filter((node) => !shownBefore.has(node)).map(text).find((entry) => entry.startsWith("Cancel mayday")), 15000); + document.getElementById("toasts").replaceChildren(); + return {fromLog, fromWhole, sent, enabled, questions, lifted, spot: spotOpen()}; +})()""" + + +def columns(width: int, height: int) -> bool: + return any(width >= low and height >= tall for low, tall in BANDS) + + +def probe(template: str) -> str: + return (template.replace("@HELPERS@", base.HELPERS).replace("@PROBES@", PROBES).replace("@LOADS@", LOADS).replace("@SPEAKING@", base.SPEAKING).replace("@PARTS@", json.dumps(PARTS)) + .replace("@SIZES@", json.dumps(SIZES)).replace("@LIVE@", LIVE).replace("@SILENCE@", SILENCE).replace("@DUPS@", json.dumps(DUPS)).replace("@MAIN@", str(MAIN_SHARE))) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestRadioLayout(HubCase): + drive = base.TestOrchestratorE2E.drive + beside = base.TestOrchestratorE2E.beside + authenticator = base.TestOrchestratorE2E.authenticator + speaks = base.TestOrchestratorE2E.speaks + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + now = time.time() + self.claim("s1", "Skills session") + rows = [{"ts": now - 1200 + index * 30, "from": NAMES[index % len(NAMES)], "to": [], "text": f"status line {index}: build {index} green", "class": "newsletter", "v": 2} for index in range(FILLERS)] + self.call = now - 400 + self.long = now - 300 + rows += [ + {"ts": self.call, "from": "Skills", "to": ["Stage", "Docs"], "text": "gate red on main", "class": "call", "v": 2}, + {"ts": self.call + 5, "from": "Stage", "to": ["Skills"], "text": "gate red on main", "class": "receipt", "v": 2, "call": self.call}, + {"ts": self.long, "from": "Stage", "to": [], "text": LONG, "class": "broadcast", "v": 2}, + ] + self.write_council({"news.jsonl": self.jsonl(rows)}) + for sid in SESSIONS: + self.mark(sid, now - 100) + self.sessions() + self.beside(self.sessions) + self.httpd.hub.receipt_reads.times[("s5", self.long)] = self.long + 40 + self.sight() + self.live = 0 + hub = self.httpd.hub + heard = hub.voice_notes.get + + def get(note_id: str) -> dict: + if note_id == SILENCE: + self.silence(NEW_ALARM) + return {"id": note_id, "status": "done", "text": "", "error": "", "seconds": None, "created_ts": None} + if note_id != LIVE: + return heard(note_id) + self.live += 1 + row = {"ts": time.time(), "from": "Docs", "to": [], "text": f"live row {self.live} for Home", "class": "broadcast", "v": 2} + with (self.council / "news.jsonl").open("a", encoding="utf-8") as handle: + handle.write(self.jsonl([row])) + return {"id": note_id, "status": "done", "text": "", "error": "", "seconds": None, "created_ts": None} + + patch = mock.patch.object(hub.voice_notes, "get", get) + patch.start() + self.addCleanup(patch.stop) + + def sessions(self) -> None: + payload = {"written": time.time(), "sessions": {sid: {"name": name, "running": True} for sid, name in SESSIONS.items()}} + written = self.state / f".{SNAPSHOT}.e2e" + written.write_text(json.dumps(payload), encoding="utf-8") + os.replace(written, self.state / SNAPSHOT) + + def sight(self) -> None: + hub = self.httpd.hub + receipts.sighting_pass(hub.scripts.skills, hub.council, hub.receipt_names, hub.receipt_reads, hub.agent_sessions, RADIO_WINDOW, time.time()) + + def mark(self, sid: str, ts: float) -> None: + folder = self.council / receipts.SEEN + folder.mkdir(parents=True, exist_ok=True) + written = folder / f".{sid}.e2e" + written.write_text(json.dumps({"radio": ts}), encoding="utf-8") + os.replace(written, folder / f"{sid}.json") + + def steps(self, browser: str) -> list[dict]: + steps = [] + for width, height in WIDTHS: + shot = str(OUT / f"{browser}-{width}") + steps += [ + {"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}#stream", "wait": 1500, "probe": probe(LAYOUT), "shot": f"{shot}-radio.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(POPUP), "shot": f"{shot}-popup.png", "gesture": True}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(CLOSE_REPLY), "shot": f"{shot}-reply.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(HOME), "shot": f"{shot}-home.png"}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(FIT), "shot": f"{shot}-orbit.png"}, + ] + return steps + + def check_layout(self, layout: dict, size: tuple[int, int], index: int, browser: str) -> None: + width = size[0] + self.assertNotIn("error", layout, layout) + self.assertLessEqual(layout["page"][0], layout["page"][1], layout) + if columns(*size): + self.assertLessEqual(layout["tall"][0], layout["tall"][1], layout) + self.assertEqual(layout["wider"], [], layout) + self.assertEqual(layout["scrollers"], ["radio-log"], layout) + self.assertEqual((layout["list"]["overflowY"], layout["list"]["scrollbar"][0], layout["list"]["scrolls"]), ("auto", "thin", True), layout) + self.assertNotIn(layout["list"]["scrollbar"][1], ("", "auto"), layout) + if browser == "firefox": + self.assertNotIn(layout["main"], ("", "auto"), layout) + self.assertEqual(len(layout["heights"]), 1, layout) + self.assertLess(layout["heights"][0], 2 * layout["lineHeight"], layout) + self.assertTrue(layout["single"], layout) + self.assertGreaterEqual(layout["narrowest"], 30, layout) + self.assertEqual(layout["rows"], FILLERS + 2 + index, layout) + self.assertEqual(layout["long"], [True, "ellipsis"], layout) + self.assertGreaterEqual(layout["avatars"].pop("rows"), 2, layout) + cap = 3 if width in NARROW else 8 + self.assertEqual(layout["avatars"], {"most": cap, "inside": True, "after": True, "stacked": True}, layout) + self.assertEqual(layout["folds"], [[total, min(total, cap), [f"+{total - cap}"] if total > cap else []] for total, _, _ in layout["folds"]], layout) + self.assertGreaterEqual(layout["sliver"], 10, layout) + self.assertTrue(layout["order"]["stacked" if width == 390 else "beside"], layout) + self.assertEqual(layout["labels"], 1, layout) + self.assertEqual(layout["stars"], [[part, True] for part in PARTS], layout) + self.assertEqual(layout["covered"], [], layout) + self.assertEqual(layout["stations"], [True, False], layout) + + def check_popup(self, popup: dict) -> None: + self.assertNotIn("error", popup, popup) + self.assertTrue(popup["open"], popup) + self.assertEqual(popup["title"], "Stage → all", popup) + self.assertEqual(list(popup["fields"]), ["Sender", "Recipient", "Class", "Time"], popup) + self.assertEqual((popup["fields"]["Sender"], popup["fields"]["Recipient"], popup["fields"]["Class"]), ("Stage", "all", "Broadcast"), popup) + self.assertTrue(popup["fields"]["Time"], popup) + self.assertEqual((popup["full"], popup["stray"]), (LONG, []), popup) + self.assertEqual(popup["heading"], f"Read by {len(popup['readers'])}", popup) + self.assertGreater(len(popup["readers"]), 8, popup) + self.assertLessEqual({reader["name"] for reader in popup["readers"]}, set(NAMES), popup) + timed = [reader for reader in popup["readers"] if reader["time"] != "read, time unknown"] + self.assertEqual([(reader["session"], reader["name"]) for reader in timed], [("s5", "Beacon")], popup) + self.assertRegex(timed[0]["time"], r"^read about \S.*\d", popup) + self.assertEqual(popup["buttons"], ["Reply", "Copied"], popup) + self.assertEqual((popup["copied"], popup["shown"]), ([LONG], "Copied"), popup) + self.assertEqual(popup["region"], ["status", "polite", True, True], popup) + self.assertEqual(popup["success"], ["Copied", "Copied: the full message is on the clipboard"], popup) + self.assertEqual(popup["reset"], ["Copy", ""], popup) + self.assertEqual(popup["failure"], ["Not copied", "Not copied: the browser refused the clipboard"], popup) + self.assertTrue(popup["inView"], popup) + + def check_home(self, home: dict, width: int) -> None: + self.assertEqual(home["pressed"], {part: "true" for part in PARTS}, home) + self.assertEqual(home["stored"], [[f"panel:{part}", *DEFAULTS[part]] for part in PARTS], home) + for moment in ("fresh", "resized"): + for part in PARTS: + with self.subTest(moment=moment, tile=part): + found = home[moment][part] + stacked = width == 390 and part == "radio" + expected = ["home-body"] if stacked else [SCROLLER[part]] if SCROLLER[part] else [] + self.assertEqual(found["scrollers"], expected, home[moment]) + if found["rows"] is not None and not stacked: + self.assertGreaterEqual(found["rows"], 2, home[moment]) + self.assertTrue(found["inside"], home[moment]) + self.assertTrue(found["filled"], home[moment]) + self.assertEqual(home["tools"]["gear"], ["true", True, True], home) + self.assertEqual(home["tools"]["clear"], [True, "Cancel mayday: lift the radio silence so the agents write again; your passkey signs it"], home) + content = home["content"] + self.assertEqual(content["tiles"], [f"panel:{part}" for part in PARTS], home) + self.assertEqual(content["radio"], [True, True, True], home) + self.assertEqual(content["device"], ["Auto", 6], home) + self.assertEqual(content["speak"], [True, True], home) + self.assertEqual(content["log"][0], content["log"][2], home) + self.assertEqual(content["log"][1], content["log"][2], home) + self.assertEqual((content["gone"], content["stars"], content["ids"]), (0, 0, []), home) + self.assertIsNotNone(home["live"], home) + self.assertEqual(home["live"][0], home["live"][1], home) + self.assertEqual(home["mode"], ["Quiet", "Quiet"], home) + self.assertFalse(home["wide"], home) + + def check_fit(self, fit: dict, size: tuple[int, int]) -> None: + self.assertTrue(fit["fit"], fit) + self.assertFalse(fit["wide"], fit) + self.assertTrue(fit["speak"], fit) + self.assertEqual((fit["closed"]["boxes"], fit["closed"]["tall"]), (0, False), fit) + self.assertGreaterEqual(fit["closed"]["stage"], 2 * STAGE_SHARE * fit["height"], fit) + self.assertEqual(fit["scrollers"], ["radio-log"], fit) + if not columns(*size): + self.assertTrue(fit["tall"], fit) + self.assertGreaterEqual(fit["stage"], 2 * STAGE_SHARE * fit["height"], fit) + else: + self.assertGreater(fit["closed"]["stage"], fit["stage"], fit) + self.assertFalse(fit["tall"], fit) + self.assertGreaterEqual(fit["stage"], STAGE_SHARE * fit["height"], fit) + self.assertGreaterEqual(fit["list"], 60, fit) + + def silence(self, words: str) -> None: + now = time.time() + self.write_council({"radio-silence.json": {"since": now - 60, "until": now + 3600, "by": "Docs", "text": words}}) + + def stations(self) -> None: + hub = self.httpd.hub + hub.settings.put({**hub.settings.get(), "streams": STREAMS}, hub.settings.get()) + + def laptop_steps(self, browser: str, states: list[str]) -> list[dict]: + places = [(width, height, view) for width, height in LAPTOPS for view in VIEWS] + return [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}x{height}-{states[-1]}#stream" if view == VIEWS[0] else None, "wait": 1500 if view == VIEWS[0] else 0, "gesture": True, + "probe": probe(SPOT.replace("@VIEW@", view).replace("@STATES@", json.dumps(states)).replace("@CUE@", f"layout-cue-{index}")), + "shot": str(OUT / f"{browser}-{width}x{height}-{view[1:].replace('/', '-')}-{states[-1]}.png")} for index, (width, height, view) in enumerate(places)] + + def laptops(self, browser: str, *driver: str) -> dict: + self.stations() + self.speaks(tuple(f"layout-cue-{index}" for index in range(len(LAPTOPS) * len(VIEWS)))) + runs = [self.drive(self.laptop_steps(browser, [state for state in STATES if state not in ALARMS]), None, *driver)] + for state, words in ALARMS.items(): + self.silence(words) + runs.append(self.drive(self.laptop_steps(browser, [state]), None, *driver)) + return {"results": [{key: value for part in parts for key, value in part.items()} for parts in zip(*(run["results"] for run in runs), strict=True)], "errors": [error for run in runs for error in run["errors"]]} + + def check_laptops(self, data: dict, browser: str) -> None: + results = iter(data["results"]) + for width, height in LAPTOPS: + for view in VIEWS: + states = next(results) + for state in STATES: + with self.subTest(browser=browser, size=f"{width}x{height}", view=view, state=state): + self.check_state(states[state], state, view) + self.check_side(states[state], width, height) + + def check_side(self, found: dict, width: int, height: int) -> None: + self.assertGreaterEqual(found["main"], found["floor"], found) + self.assertLessEqual(found["page"][0], found["page"][2], found) + self.assertLessEqual(found["stack"]["head"], found["stack"]["chips"][0] + 1, found) + self.assertLessEqual(found["stack"]["chips"][1], found["stack"]["list"] + 1, found) + if columns(width, height): + self.assertLessEqual(found["page"][1], found["page"][3], found) + self.assertEqual(found["scrollers"], ["radio-log"], found) + self.assertTrue(found["order"], found) + if found["fit"]: + self.assertGreaterEqual(found["stage"], STAGE_SHARE * height, found) + return + self.assertGreaterEqual(found["main"], found["full"] - 1, found) + self.assertTrue(found["beneath"], found) + if found["fit"]: + self.assertGreaterEqual(found["stage"], 2 * STAGE_SHARE * height, found) + + def check_state(self, found: dict, state: str, view: str) -> None: + self.assertEqual(found["active"], {"stations": 3 if state == "stations" else 0, "voice": state == "voice", "speech": state == "speech"}, found) + self.assertEqual(found["banner"] is not None, state in ALARMS, found) + if state in ALARMS: + self.assertLessEqual(found["banner"]["height"], BANNER_MAX, found) + self.assertEqual((found["banner"]["title"], found["banner"]["cut"], found["banner"]["cancel"]), (found["banner"]["full"], state == "mayday-long", True), found) + self.assertTrue(found["banner"]["full"].endswith(ALARMS[state]), found) + self.assertEqual(found["blocked"], [], found) + if state == "stations": + self.assertEqual(found["closed"], [False, True], found) + if state == "voice": + self.assertTrue(found["heard"], found) + self.assertEqual(len(found["play"]), 1, found) + kind, width, tall = found["play"][0] + self.assertGreaterEqual(width, PLAY_MIN[kind][0], found) + self.assertGreaterEqual(tall, PLAY_MIN[kind][1], found) + if kind == "BUTTON": + self.assertEqual((found["played"], found["paused"]), (True, True), found) + if state == "speech": + self.assertEqual(found["who"], "Stage speaking", found) + self.assertGreaterEqual(found["line"][0], 4 * found["rem"], found) + self.assertGreater(found["line"][1], 0, found) + self.assertEqual(found["fit"], view != "#stream", found) + self.assertEqual(found["cards"], [True, True], found) + self.assertGreaterEqual(found["list"], 60, found) + self.assertGreaterEqual(found["rows"], 2, found) + + def popover_steps(self, browser: str) -> list[dict]: + self.stations() + tiles = json.dumps([f'#main .home-tile[data-pin="panel:{part}"]' for part in ("radio-device", "radio")]) + places = (("spot", "#stream", "[]", '["#radio-spot"]', "true"), ("home", "#home", json.dumps(HOME_RADIO), tiles, "false"), ("home-spot", "#home", json.dumps(HOME_RADIO), tiles, "true")) + return [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}-pop#stream" if name == "spot" else None, "wait": 1500 if name == "spot" else 0, + "probe": probe(POP.replace("@VIEW@", view).replace("@PINS@", pins).replace("@ROOTS@", roots).replace("@SPOT@", spot)), "shot": str(OUT / f"{browser}-{width}-pop-{name}.png")} + for width, height in POPOVER_SIZES for name, view, pins, roots, spot in places] + + def check_popover(self, data: dict, browser: str) -> None: + results = iter(data["results"]) + for width, _ in POPOVER_SIZES: + for place in ("spot", "home", "home-spot"): + found = next(results) + self.assertEqual(len(found), 1 if place == "spot" else 2, found) + for fold in found: + with self.subTest(browser=browser, width=width, place=place, root=fold["selector"]): + self.assertNotIn("error", fold, fold) + self.assertEqual((fold["opened"]["open"], fold["opened"]["outside"]), (True, []), fold) + self.assertGreaterEqual(fold["opened"]["whole"], 1, fold) + self.assertEqual(fold["escape"], [False, True], fold) + self.assertEqual(fold["again"], {"open": True, "outside": []}, fold) + self.assertEqual(fold["click"], [False, False, True], fold) + + def focus_steps(self, browser: str) -> list[dict]: + self.stations() + return [{"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}-focus#stream", "wait": 1500, "probe": probe(FOCUS), "shot": str(OUT / f"{browser}-{width}-focus.png")} + for width, height in FOCUS_SIZES] + + def check_focus(self, data: dict, browser: str) -> None: + for (width, _), cases in zip(FOCUS_SIZES, data["results"], strict=True): + for key, found in cases.items(): + with self.subTest(browser=browser, width=width, case=key): + if key == "escape": + self.assertEqual(found, {"closed": True, "toggle": True}, found) + continue + self.assertEqual((found["opened"], found["closed"], found["summary"]), (True, True, False), found) + self.assertTrue(found["history"] if key.endswith("tab") else found["body"], found) + + def watch(self, browser: str, kind: str, template: str) -> dict: + width, height = FOCUS_SIZES[0] + step = {"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}-{kind}#stream", "wait": 1500, "probe": probe(template), "shot": str(OUT / f"{browser}-{width}-{kind}.png")} + driver = ("bidi.mjs", os.environ.get("FIREFOX", "firefox")) if browser == "firefox" else () + data = self.drive([step], None, *driver) + (OUT / f"{browser}-radio-{kind}.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + return data["results"][0] + + def check_rows(self, found: dict, browser: str) -> None: + want = {"same": True, "key": found["start"].pop("want"), "pick": True, "body": False} + for moment, done in (("start", None), ("fresh", "delivered"), ("tick", "ticked")): + with self.subTest(browser=browser, moment=moment): + if done: + self.assertTrue(found[moment].pop(done), found) + self.assertEqual(found[moment], want, found) + with self.subTest(browser=browser, moment="tabs"): + self.assertIsNotNone(found["tabs"].pop("tab"), found) + self.assertEqual(found["tabs"], {"delivered": [True, True, True], "focusins": 0, "same": True}, found) + + def twins(self) -> None: + now = time.time() + with (self.council / "news.jsonl").open("a", encoding="utf-8") as handle: + handle.write(self.jsonl([{"ts": now - 50, "from": "Docs", "to": [], "text": words, "class": "broadcast", "v": 2} for words in DUPS])) + + def check_keys(self, found: dict, browser: str) -> None: + with self.subTest(browser=browser, case="keys"): + self.assertEqual(len(set(found["keys"])), len(DUPS), found) + for words in DUPS: + with self.subTest(browser=browser, case=words): + self.assertEqual(found[words], {"delivered": True, "same": True, "line": words, "popup": words}, found) + with self.subTest(browser=browser, case="filtered"): + self.assertEqual(found["filtered"], {"gone": True, "pick": True, "class": "call"}, found) + with self.subTest(browser=browser, case="emptied"): + self.assertEqual(found["emptied"], {"gone": True, "list": True}, found) + + def check_banner(self, found: dict, browser: str) -> None: + with self.subTest(browser=browser, moment="steady"): + self.assertEqual(found["steady"], {"polled": True, "mutations": 0, "focus": True, "body": False}, found) + with self.subTest(browser=browser, moment="changed"): + self.assertTrue(found["changed"].pop("text").endswith(NEW_ALARM), found) + self.assertEqual(found["changed"], {"polled": True, "added": 1, "shown": True, "cancel": True}, found) + + def check(self, data: dict, browser: str) -> None: + results = iter(data["results"]) + for index, (width, height) in enumerate(WIDTHS): + layout, popup, closing, home, fit = (next(results) for _ in range(5)) + with self.subTest(browser=browser, width=width, part="layout"): + self.check_layout(layout, (width, height), index, browser) + with self.subTest(browser=browser, width=width, part="popup"): + self.check_popup(popup) + with self.subTest(browser=browser, width=width, part="close and reply"): + self.assertTrue(closing["escaped"], closing) + self.assertEqual(closing["outside"], [True, True], closing) + self.assertEqual(closing["reply"], {"open": False, "channel": "post", "recipient": "Stage", "toShown": True, "focused": True}, closing) + with self.subTest(browser=browser, width=width, part="home"): + self.check_home(home, width) + with self.subTest(browser=browser, width=width, part="fit view"): + self.check_fit(fit, (width, height)) + + def test_chromium_lays_the_radio_out_without_overflow_one_line_rows_popup_and_four_home_stars_at_four_widths(self): + data = self.drive(self.steps("chromium"), None) + (OUT / "chromium-radio-layout.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + self.check(data, "chromium") + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_lays_the_radio_out_without_overflow_one_line_rows_popup_and_four_home_stars_at_four_widths(self): + data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox")) + (OUT / "firefox-radio-layout.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + self.check(data, "firefox") + + def test_chromium_leaves_the_focus_where_a_click_lands_and_returns_it_to_the_toggle_only_on_escape(self): + data = self.drive(self.focus_steps("chromium"), None) + (OUT / "chromium-radio-focus.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + self.check_focus(data, "chromium") + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_leaves_the_focus_where_a_click_lands_and_returns_it_to_the_toggle_only_on_escape(self): + data = self.drive(self.focus_steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox")) + (OUT / "firefox-radio-focus.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + self.check_focus(data, "firefox") + + def test_chromium_holds_the_focus_on_a_history_row_and_its_tab_across_new_rows_and_the_minute_tick(self): + self.check_rows(self.watch("chromium", "rows", ROWS), "chromium") + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_holds_the_focus_on_a_history_row_and_its_tab_across_new_rows_and_the_minute_tick(self): + self.check_rows(self.watch("firefox", "rows", ROWS), "firefox") + + def test_chromium_keys_twin_rows_apart_and_moves_the_focus_of_a_filtered_out_row_to_the_nearest_row_or_the_list(self): + self.twins() + self.check_keys(self.watch("chromium", "keys", KEYS), "chromium") + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_keys_twin_rows_apart_and_moves_the_focus_of_a_filtered_out_row_to_the_nearest_row_or_the_list(self): + self.twins() + self.check_keys(self.watch("firefox", "keys", KEYS), "firefox") + + def test_chromium_redraws_the_mayday_banner_only_when_the_silence_changes(self): + self.silence(ALARMS["mayday"]) + self.check_banner(self.watch("chromium", "banner", BANNER), "chromium") + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_redraws_the_mayday_banner_only_when_the_silence_changes(self): + self.silence(ALARMS["mayday"]) + self.check_banner(self.watch("firefox", "banner", BANNER), "firefox") + + def test_chromium_keeps_the_main_floor_and_reachable_radio_controls_in_six_states_on_both_sides_of_the_height_threshold(self): + data = self.laptops("chromium") + (OUT / "chromium-radio-laptops.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + self.check_laptops(data, "chromium") + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_keeps_the_main_floor_and_reachable_radio_controls_in_six_states_on_both_sides_of_the_height_threshold(self): + data = self.laptops("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox")) + (OUT / "firefox-radio-laptops.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + self.check_laptops(data, "firefox") + + def test_chromium_places_the_station_popover_inside_every_clip_and_closes_it_on_escape_and_outside_clicks_in_the_spot_and_on_home(self): + data = self.drive(self.popover_steps("chromium"), None) + (OUT / "chromium-radio-popover.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + self.check_popover(data, "chromium") + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_places_the_station_popover_inside_every_clip_and_closes_it_on_escape_and_outside_clicks_in_the_spot_and_on_home(self): + data = self.drive(self.popover_steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox")) + (OUT / "firefox-radio-popover.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], []) + self.check_popover(data, "firefox") + + def test_chromium_home_copies_keep_their_own_composer_record_reply_and_cancel_the_mayday(self): + now = time.time() + self.write_council({"radio-silence.json": {"since": now - 60, "until": now + 3600, "by": "Docs", "text": "disk full"}}) + steps = [] + for width, height in ((1366, 768), (390, 844)): + shot = str(OUT / f"chromium-{width}") + steps += [ + {"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}-copies#stream", "wait": 1500, "probe": probe(COMPOSE_HOME), "shot": f"{shot}-home-composers.png", "gesture": True}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(REPLY_HOME), "shot": f"{shot}-home-reply.png"}, + ] + data = self.drive(steps, self.authenticator()) + (OUT / "chromium-radio-home-copies.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + results = iter(data["results"]) + question = "Lift the radio silence of the active mayday?" + for width in (1366, 390): + composed, replied = next(results), next(results) + with self.subTest(width=width, part="own composer state"): + self.assertEqual(composed["drafts"], ["draft kept in the spot", "", ""], composed) + self.assertEqual((composed["first"], composed["handed"]), ("true", ["false", "true"]), composed) + self.assertIn("hello from the mic", composed["spotHeard"] or "", composed) + self.assertNotIn("hello from the mic", composed["homeBefore"], composed) + self.assertIn("hello from the mic", composed["homeHeard"] or "", composed) + self.assertTrue(all(composed["notes"]) and composed["notes"][0] != composed["notes"][1], composed) + self.assertTrue((composed["spotSent"] or "").startswith("Post to Stage: sent"), composed) + self.assertTrue(composed["homeAttach"], composed) + self.assertTrue((composed["homeSent"] or "").startswith("Post to Docs: sent"), composed) + self.assertEqual(composed["bodies"], [["Stage", "plain text from the spot", ""], ["Docs", "voice from the Home tile", composed["notes"][1]]], composed) + with self.subTest(width=width, part="reply and mayday from Home"): + self.assertEqual(replied["fromLog"], {"spot": "false", "popup": False, "speak": {"channel": "post", "recipient": "Stage", "toShown": True, "focused": True}, + "whole": {"channel": "post", "recipient": replied["fromLog"]["whole"]["recipient"], "toShown": True, "focused": False}}, replied) + self.assertEqual(replied["fromWhole"], {"spot": "false", "whole": {"channel": "post", "recipient": "Stage", "toShown": True, "focused": True}}, replied) + self.assertTrue((replied["sent"] or "").startswith("Post to Stage: sent"), replied) + self.assertEqual((replied["enabled"], replied["questions"]), (True, [question]), replied) + self.assertTrue((replied["lifted"] or "").startswith("Cancel mayday: done"), replied) + self.assertEqual(replied["spot"], "false", replied) + radio = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO] + self.assertEqual([args[:3] for args in radio if args[0] == "post"], [["post", "--to", "Stage"], ["post", "--to", "Docs"], ["post", "--to", "Stage"]] * 2, radio) + self.assertEqual([args for args in radio if args[0] == "clear"], [["clear", "--force", "--session", "Operator"]] * 2, radio) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/test_radio_set_e2e.py b/tests/e2e/test_radio_set_e2e.py index 8f3ea7e..9e2da1c 100644 --- a/tests/e2e/test_radio_set_e2e.py +++ b/tests/e2e/test_radio_set_e2e.py @@ -127,7 +127,7 @@ RADIO = """ await sleep(150); }; const chips = () => Object.fromEntries(all(".chip-select", spot).map((box) => [box.dataset.chip, box.querySelector("select").value])); - const search = () => spot.querySelector('.radio-filters input[type="search"]'); + const search = () => spot.querySelector('.radio-logbox input[type="search"]'); const tab = async (id) => { spot.querySelector(`.radio-tabs [data-tab="${id}"]`).click(); await sleep(150); @@ -187,10 +187,11 @@ LOG = """(async () => {@HELPERS@@RADIO@ all(".radio-filters button", spot).find((button) => name(button) === "Clear filters").click(); await sleep(150); const clearedChips = [chips(), search().value, rows().length]; - const summary = spot.querySelector(".radio-row summary"); - summary.click(); + spot.querySelector(".radio-row .radio-pick").click(); + const full = await until(() => document.getElementById("popup").open && document.querySelector("#popup .radio-full"), 4000); + const opened = [document.getElementById("popup").open, text(full)]; + all("#popup .popup-head button").find((button) => name(button) === "Close").click(); await sleep(150); - const opened = [summary.parentElement.open, text(summary.parentElement.querySelector(".radio-full"))]; await tab("received"); await chip("agent", "Stage"); search().value = "gate"; diff --git a/tests/test_hub_home.py b/tests/test_hub_home.py index 1e67d8b..171fa19 100644 --- a/tests/test_hub_home.py +++ b/tests/test_hub_home.py @@ -62,6 +62,8 @@ const swapped = P.add(P.remove(one.pins, "panel", "agents/3d"), "panel", "tasks/ const both = [...one.pins, {kind: "panel", id: "tasks/3d", w: 6, h: 4}]; out.group = [one.refused, second.refused, second.holder, second.pins.length, swapped.refused, swapped.pins.at(-1).id, P.add(one.pins, "panel", "tasks/gantt").refused, P.firstOfGroup(both, both[4]), P.firstOfGroup(both, both[5]), P.firstOfGroup(both, both[0])]; +P.panel("radio", "Radio", () => "r", "", [12, 7]); +out.sized = [P.add(pins, "panel", "radio").pins.at(-1), P.add(pins, "panel", "tasks/gantt").pins.at(-1), P.add(pins, "task", "work/z").pins.at(-1)]; console.log(JSON.stringify(out)); """ REGISTRY_PROBE = """ @@ -199,7 +201,7 @@ const server = hub([]); const tab = page(server); const {homePress, homeUnpin, homeView, Panels} = tab; const ids = Object.fromEntries(["panel", "task", "message", "artifact", "agent", "ancestry", "nope"].map((kind) => [kind, Boolean(Panels.lookup(kind, kind === "panel" ? "stream" : "x"))])); -const panels = ["stream", "radio-log", "agents/orbit", "agents/chord", "agents/swimlane", "agents/3d", "agents/tree", "agents/hierarchy", "artifacts/orbit", "artifacts/chord", "artifacts/swimlane", "artifacts/3d", +const panels = ["stream", "radio-log", "radio", "radio-device", "radio-speak", "agents/orbit", "agents/chord", "agents/swimlane", "agents/3d", "agents/tree", "agents/hierarchy", "artifacts/orbit", "artifacts/chord", "artifacts/swimlane", "artifacts/3d", "tasks/list", "tasks/board", "tasks/rasci", "tasks/gantt", "tasks/burn", "tasks/3d"].filter((id) => !Panels.lookup("panel", id)); (async () => { homePress("panel", "tasks/gantt", "Gantt"); @@ -402,6 +404,10 @@ class TestHomeReorder(unittest.TestCase): holder = {"kind": "panel", "id": "agents/3d", "w": 6, "h": 4} self.assertEqual(data["group"], ["", "group", holder, 5, "", "tasks/3d", "", True, False, True]) + def test_a_panel_with_its_own_size_is_pinned_at_it_and_the_rest_at_the_default(self): + data = node(REORDER_PROBE, str(PANELS)) + self.assertEqual(data["sized"], [{"kind": "panel", "id": "radio", "w": 12, "h": 7}, PIN, {"kind": "task", "id": "work/z", "w": 4, "h": 3}]) + class TestHomeRegistry(unittest.TestCase): def test_the_registry_finds_panels_and_item_kinds_and_a_missing_item_renders_none(self): @@ -479,7 +485,7 @@ class TestHomePage(unittest.TestCase): dynamic = {f"{tab}/{view}" for tab in re.findall(r'"data-panel": `(\w+)/\$\{view\}`', sources) for view in views[tab]} used = set(re.findall(r'(?:"data-item"|item): `(\w+):', sources)) marked = set(re.findall(r"\['[^']+', \"([^\"]+)\"\]", home)) - self.assertEqual((len(literal), marked), (4, {"radio-log"})) + self.assertEqual((len(literal), marked), (8, {"radio-log"})) literal |= marked self.assertEqual(len(dynamic), 13) self.assertEqual(sorted(literal | dynamic), sorted(registered)) diff --git a/tests/test_hub_radioset.py b/tests/test_hub_radioset.py index 93bd446..7d3db2d 100644 --- a/tests/test_hub_radioset.py +++ b/tests/test_hub_radioset.py @@ -163,11 +163,11 @@ async function stalled() { function pressed() { const calls = []; const sandbox = {RadioSet, h: (tag, attrs, ...children) => ({tag, attrs: attrs || {}, children: children.flat()}), icon: (name) => name, named: (label, hint) => ({"aria-label": label, title: hint})}; - vm.runInNewContext(`${viewCode}\\nradioDom = {};`, sandbox); + vm.runInNewContext(viewCode, sandbox); sandbox.knobs = () => []; sandbox.context = () => calls.push("context"); sandbox.keepRadio = (change) => calls.push(change); - const modes = sandbox.faceplate().children.find((child) => child.attrs["aria-label"] === "Mode"); + const modes = sandbox.faceplate({}).children.find((child) => child.attrs["aria-label"] === "Mode"); modes.children.forEach((button) => button.attrs.on.click()); return calls; } @@ -425,6 +425,7 @@ MESSAGES = [ {"id": "a" * 16, "to": "Stage", "text": "rebase please", "created_ts": 10, "class": "post", "voice": "v0"}, {"id": "b" * 16, "to": "*", "text": "deploy now", "created_ts": 50, "class": "broadcast", "voice": "v0"}, ] +TWINS = [*LOG, {"ts": 90, "from": "Docs", "to": [], "class": "newsletter", "text": "twin one"}, {"ts": 90, "from": "Docs", "to": [], "class": "broadcast", "text": "twin two"}] def run(calls: dict[str, list[list]]) -> dict: @@ -460,6 +461,7 @@ class TestRadioSetModule(unittest.TestCase): "plans": plans, "stored": [["valid", value] for value in stored], "logs": [["logRows", LOG, entry, HUMAN, MESSAGES] for entry in entries], + "twins": [["logRows", TWINS, entry, HUMAN, MESSAGES] for entry in (entries[0], {**entries[0], "chips": {**entries[0]["chips"], "class": "broadcast"}}, entries[1])], "counts": [["counts", LOG, HUMAN, MESSAGES]], "ledger": [["ledgerOf", {"text": f"deploy now [kvb-orchestrator msg {'b' * 16}]"}, MESSAGES], ["ledgerOf", {"text": f"forged [kvb-orchestrator msg {'c' * 16}]"}, MESSAGES], ["ledgerOf", LOG[-1], MESSAGES]], "choices": [["choices", LOG]], @@ -541,6 +543,14 @@ class TestRadioSetModule(unittest.TestCase): self.assertEqual(self.data["choices"][0]["agent"], ["Docs", "Operator", "Skills", "Stage"]) self.assertEqual(self.data["cleared"], [{"tab": "all", "chips": {"class": "", "from": "", "to": "", "agent": ""}, "q": ""}]) + def test_every_log_row_has_a_unique_key_that_a_filter_keeps_and_twins_of_one_time_and_sender_differ(self): + everything, broadcasts, sent = ({row["text"]: row["key"] for row in rows} for rows in self.data["twins"]) + self.assertEqual(len(set(everything.values())), len(TWINS), everything) + self.assertEqual((everything["twin one"], everything["twin two"]), ("90 Docs 0", "90 Docs 1"), everything) + self.assertEqual(broadcasts, {text: everything[text] for text in broadcasts}, broadcasts) + self.assertIn("twin two", broadcasts) + self.assertEqual(sent, {"deploy now": f"sent {'b' * 16} 0", "rebase please": f"sent {'a' * 16} 0"}, sent) + def test_sent_comes_from_the_hub_ledger_and_a_row_only_named_operator_is_not_sent(self): sent = self.data["logs"][1] self.assertEqual([(row["to"], row["class"], row["sent"]) for row in sent], [([], "broadcast", True), (["Stage"], "post", True)])