diff --git a/orchestrator/kvb_orchestrator/settings.py b/orchestrator/kvb_orchestrator/settings.py index 87d4da7..0660a1c 100644 --- a/orchestrator/kvb_orchestrator/settings.py +++ b/orchestrator/kvb_orchestrator/settings.py @@ -33,7 +33,7 @@ SETTINGS = { "theme": "sky", "colors": {"top": "#0b1020", "bottom": "#2b3a67", "accent": "#8fadff"}, "music": {"on": False, "volume": 0.4}, - "notify": True, + "channels": {"browser": True, "sounds": True, "aloud": True, "title": True}, "streams": [], "speech": {"threshold": 50}, "space": { @@ -188,7 +188,7 @@ def valid_settings(raw: object) -> dict: "theme": data["theme"], "colors": {key: color(colors[key], f"colors.{key}") for key in SETTINGS["colors"]}, "music": {"on": flag(music["on"], "music.on"), "volume": number_in(music["volume"], "music.volume", 0.0, 1.0)}, - "notify": flag(data["notify"], "notify"), + "channels": channels_setting(data["channels"]), "streams": [stream_entry(entry, index) for index, entry in enumerate(data["streams"])], "speech": speech_setting(data["speech"]), "space": space_setting(data["space"]), @@ -216,6 +216,22 @@ def radio_moved(stored: object) -> object: return {**others, "speech": rest} if rest else others +def channels_setting(raw: object) -> dict: + entry = section(raw, "channels", tuple(SETTINGS["channels"])) + return {name: flag(entry[name], f"channels.{name}") for name in SETTINGS["channels"]} + + +def notify_moved(stored: object) -> object: + """Returns: + The stored settings with the old notify flag as the browser channel + and every other channel on; stored channels win over the flag. + """ + if not isinstance(stored, dict) or "notify" not in stored: + return stored + kept = {key: value for key, value in stored.items() if key != "notify"} + return {"channels": {**SETTINGS["channels"], "browser": stored["notify"]}, **kept} + + def migrated(stored: object) -> object: """Returns: The stored settings in the current shape: the radio set moved to the @@ -223,7 +239,7 @@ def migrated(stored: object) -> object: it may have been saved without the passkey, so the hub never dials it unsigned; re-adding it with the passkey resolves its redirects. """ - stored = radio_moved(stored) + stored = notify_moved(radio_moved(stored)) streams = stored.get("streams") if isinstance(stored, dict) else None if not isinstance(streams, list): return stored diff --git a/orchestrator/templates/page-alerts.js b/orchestrator/templates/page-alerts.js index a7cb36d..13f851a 100644 --- a/orchestrator/templates/page-alerts.js +++ b/orchestrator/templates/page-alerts.js @@ -42,6 +42,19 @@ button.disabled = permission !== "default"; } + /** + * @param {object} before the channels of the settings the page held until now. + */ + function syncChannels(before) { + if (before.sounds && !settings.channels.sounds) { + silenceBeeps(); + } + if (before.aloud && !settings.channels.aloud) { + cancelSpeech(); + } + drawTitle(); + } + async function askNotify() { if ("Notification" in window) { await Notification.requestPermission(); @@ -58,13 +71,13 @@ const newRadio = state.radio.filter((row) => !known.radio.has(`${row.ts}|${row.from}|${row.text.slice(0, 40)}`)); const direct = newRadio.filter((row) => row.to.includes(HUMAN)); const present = {mayday: newAlarms.length > 0, review: fresh.some((item) => item.kind !== "operator"), direct: direct.length > 0, radio: newRadio.length > 0}; - const kind = radioSet.mode === "silence" ? null : Voice.beep(present, tones(), SOUND_KINDS.map(([id]) => id)); + const kind = radioSet.mode === "silence" || !settings.channels.sounds ? null : Voice.beep(present, tones(), SOUND_KINDS.map(([id]) => id)); if (kind) { play(kind, loudness(kind)); } const lead = kind ? Math.max(...TONES[kind].map(([, at, length]) => at + length)) : 0; window.setTimeout(() => speakRows(newRadio), lead * 1000); - if (settings.notify && "Notification" in window && Notification.permission === "granted") { + if (settings.channels.browser && "Notification" in window && Notification.permission === "granted") { for (const row of newAlarms) { new Notification(`${row.class === "mayday" ? "Mayday" : "Pan-Pan"} from ${dash(row.from)}`, {body: row.text.slice(0, 200), tag: `alarm-${row.ts}`, requireInteraction: row.class === "mayday"}); } diff --git a/orchestrator/templates/page-constants.js b/orchestrator/templates/page-constants.js index 64990e4..ed511e9 100644 --- a/orchestrator/templates/page-constants.js +++ b/orchestrator/templates/page-constants.js @@ -55,6 +55,7 @@ const STATE_TIMEOUT = 15000; const THEME_CHOICES = [["sky", "Sky (follows the light outside)"], ["light", "Always light"], ["dark", "Always dark"], ["custom", "Custom colors"]]; const COLOR_FIELDS = [["top", "Sky at the top"], ["bottom", "Sky at the horizon"], ["accent", "Accent"]]; + const CHANNEL_CHOICES = [["browser", "Desktop notifications when the browser allows them"], ["sounds", "Sound tones"], ["aloud", "Read radio aloud"], ["title", "Waiting count in the tab title"]]; const STAGE_LABELS = {night: "Night", astronomical: "Astronomical twilight", nautical: "Nautical twilight", civil: "Civil twilight", golden: "Golden hour", day: "Day"}; const WEEKDAYS = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"]; const COMPASS = [["N", "North"], ["NE", "Northeast"], ["E", "East"], ["SE", "Southeast"], ["S", "South"], ["SW", "Southwest"], ["W", "West"], ["NW", "Northwest"]]; diff --git a/orchestrator/templates/page-screens.js b/orchestrator/templates/page-screens.js index 621d4fc..ee8909f 100644 --- a/orchestrator/templates/page-screens.js +++ b/orchestrator/templates/page-screens.js @@ -107,10 +107,14 @@ 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)")] : [])); - document.title = `${state.badges.tasks ? `(${state.badges.tasks}) ` : ""}Agent Orchestrator`; + drawTitle(); window.setTimeout(measure, 0); } + function drawTitle() { + document.title = `${settings.channels.title && state.badges.tasks ? `(${state.badges.tasks}) ` : ""}Agent Orchestrator`; + } + function toggleLeitstand() { const on = !document.body.classList.contains("leitstand"); document.body.classList.toggle("leitstand", on); diff --git a/orchestrator/templates/page-settings.js b/orchestrator/templates/page-settings.js index 284f9f1..0462369 100644 --- a/orchestrator/templates/page-settings.js +++ b/orchestrator/templates/page-settings.js @@ -1,6 +1,7 @@ let redirectsTold = ""; function adoptSettings(next) { + const before = settings.channels; settings = next; settingsSig = JSON.stringify(next); if (space.edits === space.saved) { @@ -14,6 +15,7 @@ syncRadio(); musicButton(); syncBubbles(); + syncChannels(before); } async function saveSettings(next) { @@ -125,7 +127,7 @@ judge(); const musicOn = h("input", {type: "checkbox", checked: settings.music.on}); const volume = h("input", {type: "range", min: 0, max: 1, step: 0.05, value: settings.music.volume, "aria-label": "Overall volume"}); - const notify = h("input", {type: "checkbox", checked: settings.notify}); + const channels = Object.fromEntries(CHANNEL_CHOICES.map(([id]) => [id, h("input", {type: "checkbox", name: `channel-${id}`, checked: settings.channels[id]})])); const form = h("form", {class: "settings"}, ambience(), h("section", {}, h("h3", {}, "Location"), h("p", {class: "muted"}, "Sun, moon and stars stand where you see them from here, looking south; under 🔭 Sky (key h) you turn the view. Decimal degrees, north and east positive."), @@ -133,8 +135,8 @@ h("section", {}, h("h3", {}, "Appearance"), h("label", {}, "Colors", theme), custom, verdict), h("section", {}, h("h3", {}, "Music"), h("p", {class: "muted"}, "Generative ambient music, made offline: calm with an empty inbox, a little tenser when something waits, quieter under messages."), h("div", {class: "grid"}, h("label", {class: "check"}, musicOn, "Music on"), h("label", {}, "Overall volume (music and radio)", volume))), - h("section", {}, h("h3", {}, "Notifications"), h("p", {class: "muted"}, "Mode, tones, squelch, the speech threshold, reading aloud and the stations sit in the radio panel behind the radio button in the header."), - h("label", {class: "check"}, notify, "Show desktop notifications when the browser allows them")), + h("section", {}, h("h3", {}, "Notifications"), h("p", {class: "muted"}, "Each channel switches one way the hub tells you about something new. Which kinds sound and which classes are read aloud, the mode, squelch, speech threshold and stations sit in the radio panel behind the radio button in the header."), + h("fieldset", {class: "grid channels"}, h("legend", {}, "Notification channels"), CHANNEL_CHOICES.map(([id, label]) => h("label", {class: "check"}, channels[id], label)))), passkeySection(), h("div", {class: "sheet-foot"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), h("button", {type: "submit", class: "btn primary"}, "Save"))); form.addEventListener("submit", async (event) => { @@ -146,7 +148,7 @@ theme: theme.value, colors: Object.fromEntries(COLOR_FIELDS.map(([id]) => [id, colors[id].value])), music: {on: musicOn.checked, volume: Number(volume.value)}, - notify: notify.checked, + channels: Object.fromEntries(CHANNEL_CHOICES.map(([id]) => [id, channels[id].checked])), streams: settings.streams, speech: settings.speech, space: savedSpace(), diff --git a/orchestrator/templates/page-speech.js b/orchestrator/templates/page-speech.js index 6fb75f8..d1c2613 100644 --- a/orchestrator/templates/page-speech.js +++ b/orchestrator/templates/page-speech.js @@ -245,7 +245,7 @@ function speakRows(rows) { for (const row of rows.filter((entry) => entry.ts >= state.now - SPEECH_FRESH)) { - const steps = RadioSet.plan(row, radioSet, liveSpeech()); + const steps = settings.channels.aloud ? RadioSet.plan(row, radioSet, liveSpeech()) : []; if (steps.length || (settings.bubbles && Bubbles.picked(row, radioSet))) { const line = row.text.split("\n").map((part) => part.trim()).find(Boolean) || ""; say({row, voice: row.voice, tone: Voice.toneOf(row, HUMAN), cls: row.class, who: row.source, sent: Boolean(RadioSet.ledgerOf(row, state.messages)), line: short(line), words: Bubbles.words(row.text), silent: !steps.length}); diff --git a/orchestrator/templates/style-ui.css b/orchestrator/templates/style-ui.css index 30e9d58..f65d320 100644 --- a/orchestrator/templates/style-ui.css +++ b/orchestrator/templates/style-ui.css @@ -1,6 +1,8 @@ .rule-form { grid-template-columns: repeat(auto-fill, minmax(min(100%, 200px), 1fr)); } .rule-form > label, .settings .grid > label { min-width: 0; } .rule-form .field, .settings .grid .field { width: 100%; min-width: 0; } +.settings fieldset { min-width: 0; margin: 0; padding: 0; border: 0; } +.settings legend { margin-bottom: var(--sp-2); padding: 0; color: var(--muted); font-size: var(--fs-sm); } .rule-form [hidden] { display: none; } .rule-form > label.check { display: inline-flex; min-height: 34px; } .speaker-face { position: relative; display: inline-grid; flex: none; border-radius: 50%; } diff --git a/tests/e2e/test_notification_channels_e2e.py b/tests/e2e/test_notification_channels_e2e.py new file mode 100644 index 0000000..d5fc575 --- /dev/null +++ b/tests/e2e/test_notification_channels_e2e.py @@ -0,0 +1,142 @@ +from __future__ import annotations + +import json +import os +import shutil +import sys +import unittest +from pathlib import Path + +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 hub_support import ASK +from kvb_orchestrator import settings + +OUT = Path(os.environ.get("E2E_OUT", "/tmp/notification-channels-shots")) +TITLED = r"^\(\d+\) Agent Orchestrator$" +PLAIN = "Agent Orchestrator" +LABELS = [ + ("channel-browser", "Desktop notifications when the browser allows them"), + ("channel-sounds", "Sound tones"), + ("channel-aloud", "Read radio aloud"), + ("channel-title", "Waiting count in the tab title"), +] +ON = {"browser": True, "sounds": True, "aloud": True, "title": True} +KIT = """ + const boxes = (group) => all("input[type=checkbox]", group).map((box) => [box.name, box.checked, words(box.closest("label"))]); + const sheet = async () => { + document.getElementById("settings-open").click(); + const form = await until(() => document.querySelector(".sheet-box form.settings"), 8000); + const group = form ? form.querySelector("fieldset.channels") : null; + if (group) { + group.scrollIntoView({block: "center"}); + await sleep(300); + } + return {form, group}; + }; + const look = (form, group) => { + const box = group.getBoundingClientRect(); + return { + legend: text(group.querySelector("legend")), boxes: boxes(group), sections: all("section > h3", form).map(text), clashes: clashes(form), + inside: box.left >= -1 && box.right <= innerWidth + 1, wide: document.documentElement.scrollWidth > innerWidth + 1, + }; + }; + const save = async (group, on) => { + for (const box of all("input[type=checkbox]", group)) { + if (box.checked !== on) { + box.click(); + } + } + const shown = boxes(group); + group.closest("form").querySelector('button[type="submit"]').click(); + const closed = Boolean(await until(() => !document.querySelector(".sheet-box form.settings"), 8000)); + const titled = Boolean(await until(() => (on ? /@TITLED@/.test(document.title) : document.title === "@PLAIN@"), 8000)); + const stored = (await (await fetch("/api/state", {cache: "no-store"})).json()).settings.channels; + return {shown, closed, titled, title: document.title, stored}; + }; +""" +OPENED = """(async () => {@HELPERS@@OVERLAP@@KIT@ + await screenShown(8000); + await until(() => /@TITLED@/.test(document.title), 8000); + const title = document.title; + const {form, group} = await sheet(); + return group ? {title, ...look(form, group)} : {error: text(document.querySelector(".sheet-box")), title}; +})()""" +SWITCHED = """(async () => {@HELPERS@@OVERLAP@@KIT@ + const group = document.querySelector(".sheet-box fieldset.channels"); + return group ? save(group, @ON@) : {error: "no channel group"}; +})()""" +SAVED_ON = """(async () => {@HELPERS@@OVERLAP@@KIT@ + const group = document.querySelector(".sheet-box fieldset.channels"); + if (!group) { + return {error: "no channel group"}; + } + const saved = await save(group, true); + const again = await sheet(); + return {...saved, reopened: again.group ? boxes(again.group) : null}; +})()""" + + +def fill(probe: str) -> str: + return probe.replace("@HELPERS@", base.HELPERS).replace("@OVERLAP@", base.OVERLAP).replace("@KIT@", KIT).replace("@TITLED@", TITLED).replace("@PLAIN@", PLAIN) + + +@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium") +class TestNotificationChannels(HubCase): + drive = base.TestOrchestratorE2E.drive + authenticator = base.TestOrchestratorE2E.authenticator + + def setUp(self): + super().setUp() + OUT.mkdir(parents=True, exist_ok=True) + self.claim("s1", "Skills session") + self.create_ask({**ASK, "timeout": 3600}) + + def legacy(self) -> None: + file = self.state / "settings.json" + older = {key: value for key, value in settings.SETTINGS.items() if key != "channels"} + file.write_text(json.dumps({**older, "notify": False}), encoding="utf-8") + held = self.httpd.hub.settings + with held.lock: + held.current = settings.Settings(file).get() + + def steps(self, width: int, height: int) -> list[dict]: + page = f"http://{self.host}/?{width}" + return [ + {"width": width, "height": height, "url": f"{page}#stream", "wait": 1200, "probe": fill(OPENED), "shot": str(OUT / f"chromium-{width}-channels-legacy.png")}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": fill(SWITCHED).replace("@ON@", "false"), "shot": None}, + {"width": width, "height": height, "url": f"{page}-reloaded#stream", "wait": 1200, "probe": fill(OPENED.replace("await until(() => /@TITLED@/.test(document.title), 8000);", "await sleep(600);")), "shot": str(OUT / f"chromium-{width}-channels-off-reloaded.png")}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": fill(SAVED_ON), "shot": str(OUT / f"chromium-{width}-channels-on.png")}, + ] + + def check(self, data: dict) -> None: + opened, off, reloaded, back = data["results"] + for found in (opened, off, reloaded, back): + self.assertNotIn("error", found, found) + self.assertEqual(data["errors"], []) + self.assertRegex(opened["title"], TITLED) + self.assertEqual((opened["legend"], opened["boxes"]), ("Notification channels", [[name, name != "channel-browser", label] for name, label in LABELS])) + self.assertEqual(opened["sections"], ["Ambience", "Location", "Appearance", "Music", "Notifications", "Passkey"]) + self.assertEqual((opened["clashes"], opened["inside"], opened["wide"]), ({"found": [], "outside": []}, True, False), opened) + self.assertEqual((off["shown"], off["closed"], off["titled"], off["title"], off["stored"]), ([[name, False, label] for name, label in LABELS], True, True, PLAIN, dict.fromkeys(ON, False)), off) + self.assertEqual((reloaded["title"], reloaded["boxes"], reloaded["clashes"]), (PLAIN, [[name, False, label] for name, label in LABELS], {"found": [], "outside": []}), reloaded) + self.assertEqual((back["closed"], back["titled"], back["stored"], back["reopened"]), (True, True, ON, [[name, True, label] for name, label in LABELS]), back) + self.assertRegex(back["title"], TITLED) + written = json.loads((self.state / "settings.json").read_text(encoding="utf-8")) + self.assertEqual((written["channels"], "notify" in written), (ON, False)) + + def test_chromium_migrates_the_old_notify_flag_and_switches_every_channel_off_and_on_through_a_reload_at_three_widths(self): + authenticator = self.authenticator() + for width, height in base.WIDTHS: + with self.subTest(width=width): + self.legacy() + data = self.drive(self.steps(width, height), authenticator) + (OUT / f"chromium-{width}-channels.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.check(data) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hub_channels.py b/tests/test_hub_channels.py new file mode 100644 index 0000000..76985e8 --- /dev/null +++ b/tests/test_hub_channels.py @@ -0,0 +1,162 @@ +from __future__ import annotations + +import json +import subprocess +import unittest +from pathlib import Path + +from hub_case import HubCase +from hub_support import HUB +from kvb_orchestrator import settings + +TEMPLATES = HUB / "templates" +ON = {"browser": True, "sounds": True, "aloud": True, "title": True} +PROBE = """ +const fs = require("fs"); +const vm = require("vm"); +const [alerts, speechCode] = [fs.readFileSync(process.argv[1], "utf8"), fs.readFileSync(process.argv[2], "utf8")]; +const [RadioSet, Bubbles, Voice] = [require(process.argv[3]), require(process.argv[4]), require(process.argv[5])]; +const ON = {browser: true, sounds: true, aloud: true, title: true}; +function announced(change) { + const heard = {shown: [], played: [], spoken: []}; + class Notification { + constructor(title) { + heard.shown.push(title); + } + } + Notification.permission = "granted"; + const mayday = {ts: 10, from: "Docs", to: [], class: "mayday", text: "disk full"}; + const direct = {ts: 11, from: "Stage", to: ["Operator"], class: "call", text: "gate red"}; + const sandbox = { + Notification, window: {Notification, setTimeout: (run) => run()}, settings: {channels: {...ON, ...change}}, radioSet: {mode: "auto"}, + state: {inbox: [{id: "r1", kind: "review", title: "feat: x"}], radio: [mayday, direct], pending: []}, + known: {inbox: new Set(), alarms: new Set(), radio: new Set(), batches: new Set()}, live: () => true, alarmRows: () => [mayday], keyOf: (item) => item.id, + HUMAN: "Operator", Voice: {beep: () => "mayday"}, tones: () => ({}), loudness: () => 0.5, SOUND_KINDS: [["mayday", "MAYDAY"]], TONES: {mayday: [[880, 0, 0.2]]}, + dash: (value) => value, ITEM_LABELS: {review: "Review"}, + }; + vm.runInNewContext(alerts, sandbox); + sandbox.play = (kind) => heard.played.push(kind); + sandbox.speakRows = (rows) => heard.spoken.push(rows.length); + sandbox.announce(); + return heard; +} +function synced(before, after) { + const calls = []; + const sandbox = {settings: {channels: {...ON, ...after}}, cancelSpeech: () => calls.push("cancel"), drawTitle: () => calls.push("title")}; + vm.runInNewContext(alerts, sandbox); + sandbox.silenceBeeps = () => calls.push("silence"); + sandbox.syncChannels({...ON, ...before}); + return calls; +} +function spoken(aloud, bubbles) { + const said = []; + const sandbox = { + RadioSet, Bubbles, Voice, radioSet: RadioSet.valid({mode: "auto"}), HUMAN: "Operator", SPEECH_FRESH: 300, short: (value) => value, + state: {now: 1000, messages: [], speech: {tts: true, gate: {open: true}}}, settings: {bubbles, channels: {...ON, aloud}}, + }; + vm.runInNewContext(speechCode, sandbox); + sandbox.say = (item) => said.push(item.silent); + sandbox.speakRows([{ts: 1000, from: "Stage", to: [], class: "security", source: "s2", voice: "v2", word: "W", rest: "R", text: "rotate keys now"}]); + return said; +} +console.log(JSON.stringify({ + announced: {on: announced({}), browser: announced({browser: false}), sounds: announced({sounds: false}), quiet: announced({browser: false, sounds: false, aloud: false, title: false})}, + synced: { + sounds: synced({}, {sounds: false}), aloud: synced({}, {aloud: false}), both: synced({}, {sounds: false, aloud: false}), + stays: synced({sounds: false, aloud: false}, {sounds: false, aloud: false}), back: synced({sounds: false, aloud: false}, {}), title: synced({}, {title: false}), + }, + spoken: {on: spoken(true, false), off: spoken(false, false), bubbles: spoken(false, true), both: spoken(true, true)}, +})); +""" + + +class TestChannelSettings(HubCase): + def file(self) -> Path: + return self.state / "settings.json" + + def free_save(self, payload: dict) -> tuple[int, dict]: + good = self.guard(self.host) + status, _, body = self.post_json("/api/settings/sign", payload, good) + self.assertEqual((status, json.loads(body)["payload"]), (200, None), body) + status, _, body = self.post_json("/api/settings", {**payload, "proof": None}, good) + return status, json.loads(body) if status == 200 else {} + + def test_every_channel_is_on_by_default_and_the_hub_keeps_no_notify_flag(self): + current = self.snapshot()["settings"] + self.assertEqual((settings.SETTINGS["channels"], current["channels"]), (ON, ON)) + self.assertNotIn("notify", settings.SETTINGS) + self.assertNotIn("notify", current) + + def test_a_stored_notify_flag_becomes_the_browser_channel_and_every_other_value_survives(self): + current = self.snapshot()["settings"] + older = {**{key: value for key, value in current.items() if key != "channels"}, "latitude": 52.5, "theme": "dark", "estimation": "points"} + for notify in (True, False): + with self.subTest(notify=notify): + self.file().write_text(json.dumps({**older, "notify": notify}), encoding="utf-8") + self.assertEqual(settings.Settings(self.file()).get(), {**older, "channels": {**ON, "browser": notify}}) + self.file().write_text(json.dumps({**older, "notify": False, "channels": {**ON, "title": False}}), encoding="utf-8") + self.assertEqual(settings.Settings(self.file()).get()["channels"], {**ON, "title": False}) + self.file().write_text(json.dumps({**older, "notify": "yes"}), encoding="utf-8") + self.assertEqual(settings.Settings(self.file()).get(), settings.SETTINGS) + self.file().write_text(json.dumps({**older, "notify": False}), encoding="utf-8") + migrated = settings.Settings(self.file()) + migrated.put({**migrated.get(), "theme": "light"}, migrated.get()) + written = json.loads(self.file().read_text(encoding="utf-8")) + self.assertEqual((written["channels"], "notify" in written, written["latitude"], written["theme"]), ({**ON, "browser": False}, False, 52.5, "light")) + + def test_each_channel_switches_off_alone_without_a_passkey_and_survives_a_reload(self): + for chosen in (*({**ON, name: False} for name in ON), dict.fromkeys(ON, False), ON): + with self.subTest(chosen=chosen): + status, saved = self.free_save({**self.snapshot()["settings"], "channels": chosen}) + self.assertEqual((status, saved["settings"]["channels"]), (200, chosen)) + self.assertEqual(json.loads(self.file().read_text(encoding="utf-8"))["channels"], chosen) + self.assertEqual(settings.Settings(self.file()).get()["channels"], chosen) + self.assertEqual(self.snapshot()["settings"]["channels"], chosen) + + def test_channels_are_validated_and_the_old_notify_key_is_refused(self): + current = self.snapshot()["settings"] + good = self.guard(self.host) + without = {key: value for key, value in current.items() if key != "channels"} + wrongs = [{**ON, "browser": value} for value in ("yes", 1, 0, None, [])] + wrongs += [{key: value for key, value in ON.items() if key != "title"}, {**ON, "email": True}, {}, "all", ["browser"], None, True] + payloads = [{**current, "channels": wrong} for wrong in wrongs] + [{**current, "notify": True}, without, {**without, "notify": False}] + for payload in payloads: + with self.subTest(payload=payload.get("channels"), notify=payload.get("notify")): + self.assertEqual(self.post_json("/api/settings", payload, good)[0], 400) + self.assertFalse(self.file().exists()) + self.assertEqual(self.snapshot()["settings"]["channels"], ON) + + +class TestChannelGates(unittest.TestCase): + @classmethod + def setUpClass(cls): + files = [TEMPLATES / name for name in ("page-alerts.js", "page-speech.js", "radioset.js", "bubbles.js", "voice.js")] + done = subprocess.run(["node", "-e", PROBE, *map(str, files)], capture_output=True, text=True, timeout=60, check=True) + cls.data = json.loads(done.stdout) + + def test_the_browser_channel_alone_gates_the_desktop_notifications(self): + announced = self.data["announced"] + self.assertEqual(announced["on"]["shown"], ["Mayday from Docs", "Review waiting", "Radio from Stage"]) + self.assertEqual(announced["browser"], {"shown": [], "played": ["mayday"], "spoken": [2]}) + + def test_the_sound_channel_alone_gates_the_alert_tones(self): + announced = self.data["announced"] + self.assertEqual(announced["on"]["played"], ["mayday"]) + self.assertEqual(announced["sounds"], {"shown": announced["on"]["shown"], "played": [], "spoken": [2]}) + + def test_with_every_channel_off_the_rows_still_reach_the_reader_which_drops_their_audio_itself(self): + self.assertEqual(self.data["announced"]["quiet"], {"shown": [], "played": [], "spoken": [2]}) + + def test_the_read_aloud_channel_plans_no_audible_step_and_keeps_the_silent_bubble(self): + self.assertEqual(self.data["spoken"], {"on": [False], "off": [], "bubbles": [True], "both": [False]}) + + def test_switching_a_channel_off_stops_what_it_already_queued_and_every_switch_redraws_the_title(self): + synced = self.data["synced"] + self.assertEqual(synced["sounds"], ["silence", "title"]) + self.assertEqual(synced["aloud"], ["cancel", "title"]) + self.assertEqual(synced["both"], ["silence", "cancel", "title"]) + self.assertEqual((synced["stays"], synced["back"], synced["title"]), (["title"], ["title"], ["title"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hub_operator_tasks.py b/tests/test_hub_operator_tasks.py index 6538882..a9fe25c 100644 --- a/tests/test_hub_operator_tasks.py +++ b/tests/test_hub_operator_tasks.py @@ -113,7 +113,7 @@ const context = { Nav: require(`${dir}/nav.js`), Diffs: require(`${dir}/diffs.js`), Faces: {of: () => ({parts: []}), SIZE: 64}, state: {badges: {tasks: 3, agents: 0, artifacts: 1}, inbox: [operator, review, ask, decision], messages: [{id: "m1", text: "Feedback on review:0123456789abcdef a.py:1-2: \"x\" fix", created_ts: now}], people: {}, graph: {nodes: []}, silence: null, presence: {}, kinds: {operator: "Operator"}}, ui: {screen: "inbox", views: {tasks: "list"}, selected: new Set(), cursor: 0, snoozed: false, busy: false, review: null, file: 0}, - KINDS: [["operator", "Operator"], ["review", "Review"]], speech: {current: null}, look: {hidden: new Set()}, settings: {}, known: {batches: new Set()}, + KINDS: [["operator", "Operator"], ["review", "Review"]], speech: {current: null}, look: {hidden: new Set()}, settings: {channels: {title: true}}, known: {batches: new Set()}, relative: new Intl.RelativeTimeFormat("en"), absolute: new Intl.DateTimeFormat("en"), calm: {matches: true}, drawn: {screen: "", sig: ""}, proofFor: async (entries, label) => { calls.proofs.push({entries, label}); return {proof: {payload: "p", assertion: "a"}}; }, sendJson: async (path, body) => { calls.posts.push({path, body}); return {ok: true, data: {id: "b1", due: now + 3}}; }, @@ -160,6 +160,12 @@ const badgeState = {keys: [...navButtons.keys()], text: tasksBadge.textContent, state.badges = {tasks: 0, agents: 0, artifacts: 1}; drawStatus(); badgeState.zero = [tasksBadge.hidden, document.title]; +settings.channels.title = false; +state.badges = {tasks: 2, agents: 0, artifacts: 1}; +drawStatus(); +badgeState.untitled = [tasksBadge.textContent, tasksBadge.hidden, document.title]; +settings.channels.title = true; +state.badges = {tasks: 0, agents: 0, artifacts: 1}; const results = { operator: {classes: classes(operatorCard), checkbox: all(operatorCard).filter((el) => el.tag === "input" && el.attrs.type === "checkbox").length, ref: operatorCard.dataset.ref, to: operatorCard.dataset.to, command: all(operatorCard).filter((el) => classes(el).includes("command")).map((el) => [el.dataset.path, all(el).find((inner) => inner.tag === "code").textContent]), @@ -288,6 +294,7 @@ class TestOperatorPage(unittest.TestCase): self.assertEqual(status["keys"], ["home", "stream", "rules", "agents", "artifacts", "tasks", "resources"]) self.assertEqual((status["text"], status["hidden"], status["urgent"], status["title"]), ("3", False, "badge urgent", "(3) Agent Orchestrator")) self.assertEqual(status["zero"], [True, "Agent Orchestrator"]) + self.assertEqual(status["untitled"], ["2", False, "Agent Orchestrator"]) def test_an_operator_task_is_a_stream_card_with_a_checkbox_and_every_action(self): card = self.data["operator"]