Merge branch 'feature/hub-notification-channels' into unify/skills-20261114

# Conflicts:
#	orchestrator/templates/page-alerts.js
#	orchestrator/templates/page-screens.js
#	orchestrator/templates/page-speech.js
This commit is contained in:
Kevin Veen-Birkenbach committed 2026-11-14 22:00:05 +00:00
commit f437c26b05
11 files changed
+362 -13

No files matched your search

+142
View File
@@ -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()
+1 -1
View File
@@ -73,7 +73,7 @@ function page(fault) {
},
Voice: {...Voice, beep: () => null},
RadioSet: {plan: (row) => (["mayday", "security"].includes(row.class) ? [{kind: "burst"}] : []), ledgerOf: () => null},
settings: {bubbles: true, notify: false, music: {}},
settings: {bubbles: true, channels: {browser: false, sounds: true, aloud: true, title: true}, music: {}},
radioSet: {mode: "auto", classes: ["mayday", "pan-pan", "security"], sounds: {}, squelch: 1},
state: {now: 1000, radio: [], inbox: [], pending: [], messages: [], speech: {tts: false, gate: {open: false}}},
known: {inbox: null, alarms: null, radio: null, batches: new Set(), now: null},
+162
View File
@@ -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(), now: null}, 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, quietBubbles: () => null,
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()
+8 -1
View File
@@ -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]),
@@ -283,6 +289,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"]