From 86d539a95f1f7ca2ab9d442a9d78eb7348bf286c Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 15 Nov 2026 09:46:05 +0000 Subject: [PATCH] feat(hub): radio Morse mode with WPM speed, per-agent pitch and a 0-100 % speech threshold MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Morse keys every picked row whole: class prosign (SOS for MAYDAY), DE with the sender's clear name and the full text, after PARIS timing at the hub's morse.wpm (5-40, default 20) and in the sender's own 550-850 Hz tone from the same sha256 slot as its voice. A higher class cuts a keying row, which keys again whole after it. The speech threshold runs 0-100 % in steps of 10, 100 always open, 0 never. The History card moves into page-radiolog.js to keep page-radioview.js under 500 lines. 🎯 Fix: 85 % 💥 Break: 7 % 💸 Tokens: 100 % ⏱️ Velocity: 100 % 🛡️ Security: 100 % 🏆 Score: 79 🚦 Gate: ⛔ fix 85 % < 90, break 7 % > 5 Co-Authored-By: Claude Opus 5.5 --- docs/requirements/004-radio-set.md | 108 +++++- orchestrator/kvb_orchestrator/engines.py | 30 +- orchestrator/kvb_orchestrator/settings.py | 23 +- orchestrator/kvb_orchestrator/speechgate.py | 19 +- orchestrator/kvb_orchestrator/view.py | 6 +- orchestrator/templates/index.html.j2 | 6 + orchestrator/templates/morse.js | 90 +++++ orchestrator/templates/page-morse.js | 60 ++++ orchestrator/templates/page-radiolog.js | 233 +++++++++++++ orchestrator/templates/page-radioview.js | 259 +-------------- orchestrator/templates/page-settings.js | 1 + orchestrator/templates/page-speech.js | 34 +- orchestrator/templates/radioset.js | 42 ++- orchestrator/templates/style-ui.css | 6 + orchestrator/templates/voice.js | 2 +- tests/e2e/radio_set_kit.py | 65 ++++ tests/e2e/test_hub_radio_e2e.py | 2 +- tests/e2e/test_radio_set_e2e.py | 63 +++- tests/test_hub_morse.py | 347 ++++++++++++++++++++ tests/test_hub_radioset.py | 2 +- tests/test_hub_receipts.py | 2 +- tests/test_hub_speech_gate.py | 33 +- 22 files changed, 1147 insertions(+), 286 deletions(-) create mode 100644 orchestrator/templates/morse.js create mode 100644 orchestrator/templates/page-morse.js create mode 100644 orchestrator/templates/page-radiolog.js create mode 100644 tests/test_hub_morse.py diff --git a/docs/requirements/004-radio-set.md b/docs/requirements/004-radio-set.md index 7db8210..5d068bc 100644 --- a/docs/requirements/004-radio-set.md +++ b/docs/requirements/004-radio-set.md @@ -35,7 +35,7 @@ that someone transmits without the speech engine loading a busy host. hub settings (one passkey per button press). 6. **Threshold**: adjustable in the panel, 30 to 90 % in steps of 10, default 50 %; a signed hub setting `speech.threshold`, since the server enforces - it. Rejected: a fixed 50 %. + it. Rejected: a fixed 50 %. Widened to 0 to 100 % by Morse decision 5. 7. **Log**: tabs Sent (from the operator), Received (to the operator or to all) and All (every radio row the hub logs); filter chips class, sender, recipient and agent plus text search, combined with AND, newest first. @@ -117,7 +117,8 @@ flowchart TD - [x] `GET /api/state` carries `speech.gate` with `threshold`, `cpu` and `open`. - [x] `speech.threshold` accepts only 30 to 90 in steps of 10, default 50, - and changes only with a valid passkey signature. + and changes only with a valid passkey signature (0 to 100 since + Morse decision 5). ### Sound @@ -327,3 +328,106 @@ flowchart TD both browsers, and drives two composers, Reply and Cancel mayday from Home copies in Chromium at 1366 and 390 px. + +## Morse + +### Decisions (operator-confirmed 2026-11-15; do not re-litigate) + +1. **Morse mode**: a fourth mode beside Auto, Quiet and Silence. In Morse + every row the read-aloud filters pick is keyed in Morse by WebAudio, + always whole with no cap: the class prosign, then DE and the sender's + clear name (never its session id), then the full text without the hub's + message mark. The prosign stands in for the procedure word of decision 4; + the hub renders no speech line, so the CPU gate does not apply. Stop + speaking cuts the keying at once, and a mode change cuts it and replans + the row. A row of a higher class (MAYDAY, then PAN-PAN, then SÉCURITÉ) + arriving while a row keys cuts that row, which keys again whole after it, + so a MAYDAY never waits behind a long message (skeptic finding, open for + operator feedback). Rejected: a capped text, the spoken procedure word + before the keying. Out of scope: Gibberlink and a fallback selector (a + later item). +2. **Prosigns**: one table in `radioset.js`, open for operator feedback: + MAYDAY keys SOS as one sign, PAN-PAN "PAN PAN", SÉCURITÉ "SECURITE", + broadcast and newsletter CQ, post KA as one sign, and a call the called + stations' clear names in place of a prosign, so it keys + ` DE `. Letters are case-folded; Ä, Ö, Ü and the + other accented letters with a Morse code of their own key that code, any + other accented letter keys its base letter, and every other character + without a code is skipped. +3. **Speed**: a hub setting `morse.wpm`, whole numbers from 5 to 40, default + 20, saved without a passkey since no server gate depends on it, and set + in the radio gear beside the read-aloud filters, shown as + ` WPM ( dots/min)`. Timing after PARIS: a dot lasts + 1200 / WPM ms, a dash 3 dots, the gap inside a letter 1, between letters + 3 and between words 7. A page loaded before the speed existed keeps the + saved speed when it saves other settings. +4. **Pitch**: each sender keys its own stable tone from 550 to 850 Hz, + picked by the same sha256 slot of its directory key that picks its voice + (`engines.slot`), so there is no second agent mapping; every radio row + of `/api/state` carries it as `pitch`, beside `speaker` (the clear name) + and `called` (the called stations' clear names). Rejected: an agent table + in the browser, one fixed 700 Hz tone. +5. **Threshold 0 to 100 %**: decision 6 widens to 0 to 100 % in steps of 10, + default 50 %. The gate is open while the CPU lies below the threshold; + at 100 % it is always open, also without a fresh CPU sample, and at 0 % + never. The threshold label reads "speak while CPU < X %", "always" at + 100 % and "never" at 0 %. Stored values from 30 to 90 stay valid. + +### Morse Acceptance Criteria + +- [ ] Auto, Quiet, Silence and Morse form the mode group (`aria-pressed`); + Morse survives a reload and the display line shows "Morse". +- [ ] In Morse a row of every class plans exactly one Morse step with its + prosign of Morse decision 2, `DE ` and the row's pitch, + whether the hub speaks or not; the page sends no `/api/tts` request; + the read-aloud filters hold and a MAYDAY always keys. +- [ ] "PARIS" at 20 WPM lasts 50 dot units of 60 ms, 3000 ms with the + closing word gap; a dot lasts 240 ms at 5 WPM and 30 ms at 40 WPM. +- [ ] SOS keyed as one sign lasts 30 dot units, keyed as letters 34. +- [ ] A text of 1000 characters keys whole: one sine oscillator at the + row's pitch, its scheduled stop at the end of the whole timeline. +- [ ] Stop speaking stops the oscillator at once and puts the TX/RX lamp out; + a mode change while keying stops it and plays the new mode's plan. +- [ ] A MAYDAY arriving while a post keys stops that oscillator at once, + keys next, and the post waits in the queue to key again whole; a + PAN-PAN or a post arriving while a MAYDAY keys waits for its end. +- [ ] `morse.wpm` accepts only whole numbers from 5 to 40, default 20; + a bool, a float, a string, an extra key or a missing value is refused + with a ToolError (400); a save needs no passkey, survives a reload, and + a settings sheet without `morse` keeps the saved speed. +- [ ] The radio gear holds a Morse speed slider from 5 to 40 in steps of 1 + whose label ` WPM ( dots/min)` follows the drag and is + saved on release. +- [ ] Every radio row carries `pitch` from 550 to 850 Hz, the same for the + same sender and equal to `engines.pitch_of(source)`, `speaker` with the + clear name and `called`; 200 senders spread over at least 120 pitches + from below 575 to above 825 Hz; voice and pitch both take + `engines.slot`. +- [ ] `speech.threshold` accepts 0 to 100 in steps of 10; at 100 the gate + is open with any sample and without one; at 0 it is shut, busy with a + sample and unknown without; stored values 30 to 90 load unchanged. +- [ ] The threshold slider runs from 0 to 100 in steps of 10 and its label + reads "speak while CPU < X %", "always" at 100 % and "never" at 0 %. +- [ ] At 1920, 1366 and 390 px in Chromium and Firefox the Morse mode, the + gear with the speed and the keying caption cause no horizontal scroll. + +### Morse Tests + +- **Unit**: `tests/test_hub_morse.py`: PARIS timing at three speeds, case + folding, umlauts and skipped characters, SOS as one sign, the speed label, + the plan of every class with its prosign, DE with the clear name, the + whole text, the filters, the threshold labels, and in a vm sandbox of + `page-speech.js` with `page-morse.js` the oscillator at the row's pitch + and speed, Stop and a mode change; the pitch range, spread and shared + slot; `morse.wpm` validation and `completed`. + `tests/test_hub_speech_gate.py`: thresholds 0 to 100, the gate at 0 and + 100 %, stored values 30 to 90. +- **Integration**: hub HTTP tests: `morse.wpm` refused out of range, saved + without a passkey, kept by a sheet without it; `/api/state` rows carry + `pitch`, `speaker` and `called`. +- **E2E**: `tests/e2e/test_radio_set_e2e.py` in Chromium and Firefox at + 1920, 1366 and 390 px: Morse pressed, the speed slider and its label, the + saved speed, one sine oscillator at the sender's pitch and no `/api/tts` + request, Stop cuts it; screenshots `--radio-morse-keying` + and `-stopped` under `E2E_OUT` for operator feedback; the faceplate step + checks the four modes and the threshold slider from 0 to 100. diff --git a/orchestrator/kvb_orchestrator/engines.py b/orchestrator/kvb_orchestrator/engines.py index a8c486d..19475ca 100644 --- a/orchestrator/kvb_orchestrator/engines.py +++ b/orchestrator/kvb_orchestrator/engines.py @@ -44,6 +44,7 @@ HEARING_HOUR = 3600 HEARING_BUDGET = 5 * STT_SECONDS NOISE = re.compile(r"\[[^\]\n]{0,40}\]") PLACEHOLDERS = frozenset({0, 0xFFFFFFFF}) +PITCH = (550, 850) def voice_models(folder: Path) -> list[Path]: @@ -92,6 +93,18 @@ def unreachable(path: Path, part: str, mode: int, ability: str) -> str: return f"{part} {path} is missing or not {ability}" +def slot(key: str, count: int) -> int: + """Args: + key: the speaker's session id or directory key. + count: how many slots there are, at least 1. + + Returns: + The slot sha256(key) picks from count: the one mapping from a speaker + to its voice and to its Morse pitch. + """ + return int(digest(key), 16) % count + + def voice_of(key: str, pool: list[str], operator: str) -> str: """Args: key: the speaker's session id or directory key; HUMAN is the operator. @@ -101,11 +114,24 @@ def voice_of(key: str, pool: list[str], operator: str) -> str: Returns: operator for HUMAN or when the pool is empty, otherwise the voice - sha256(key) picks from the pool. + the speaker's slot picks from the pool. """ if key == HUMAN or not pool: return operator - return pool[int(digest(key), 16) % len(pool)] + return pool[slot(key, len(pool))] + + +def pitch_of(key: str) -> int: + """Args: + key: the speaker's session id or directory key, as voice_of takes it. + + Returns: + The speaker's Morse tone in Hz from PITCH[0] to PITCH[1], picked by + the same slot as its voice, so the same speaker always keys the same + tone, installed voices or not. + """ + low, high = PITCH + return low + slot(key, high - low + 1) def wav_seconds(body: bytes, seconds: int) -> float: diff --git a/orchestrator/kvb_orchestrator/settings.py b/orchestrator/kvb_orchestrator/settings.py index 615c720..e140b82 100644 --- a/orchestrator/kvb_orchestrator/settings.py +++ b/orchestrator/kvb_orchestrator/settings.py @@ -11,12 +11,15 @@ from .errors import ToolError from .fields import FIELDS, NAME_LIMIT, expect from .rates import METRICS, PERIOD_NAMES from .records import read_json, write_atomic +from .speechgate import ALWAYS THEMES = ("sky", "light", "dark", "custom") ESTIMATIONS = ("none", "points") TRENDS = ("off", "regression", "velocity") TREND_DAYS = (1, 365) -THRESHOLDS = tuple(range(30, 91, 10)) +THRESHOLDS = tuple(range(0, ALWAYS + 1, 10)) +WPM = (5, 40) +LATE = ("rates", "morse") RADIO_MOVED = ("sounds", "squelch") SPEECH_MOVED = ("on", "classes", "muted") COLOR = re.compile(r"#[0-9a-f]{6}") @@ -37,6 +40,7 @@ SETTINGS = { "channels": {"browser": True, "sounds": True, "aloud": True, "title": True}, "streams": [], "speech": {"threshold": 50}, + "morse": {"wpm": 20}, "space": { "graph": {"axis": "none", "yaw": 30.0, "pitch": 20.0, "zoom": 1.0, "pan_x": 0.0, "pan_y": 0.0}, "sky": {"azimuth": 180.0, "altitude": 0.0, "fov": 180.0}, @@ -154,6 +158,15 @@ def speech_setting(raw: object) -> dict: return {"threshold": threshold} +def morse_setting(raw: object) -> dict: + entry = section(raw, "morse", tuple(SETTINGS["morse"])) + low, high = WPM + wpm = entry["wpm"] + if isinstance(wpm, bool) or not isinstance(wpm, int) or not low <= wpm <= high: + raise ToolError(f"morse.wpm must be a whole number from {low} to {high} words per minute") + return {"wpm": wpm} + + def space_setting(raw: object) -> dict: entry = section(raw, "space", tuple(SETTINGS["space"])) graph = section(entry["graph"], "space.graph", tuple(SETTINGS["space"]["graph"])) @@ -205,6 +218,7 @@ def valid_settings(raw: object) -> dict: "channels": channels_setting(data["channels"]), "streams": [stream_entry(entry, index) for index, entry in enumerate(data["streams"])], "speech": speech_setting(data["speech"]), + "morse": morse_setting(data["morse"]), "space": space_setting(data["space"]), "estimation": data["estimation"], "trend": trend_setting(data["trend"]), @@ -215,10 +229,11 @@ def valid_settings(raw: object) -> dict: def completed(raw: object, saved: dict) -> object: """Returns: - raw with the saved rates when it names none, as a page loaded before - the rates chip existed sends it; anything else unchanged. + raw with the saved value of each LATE section it names none of, as a + page loaded before the rates chip or the Morse speed existed sends + it; anything else unchanged. """ - return {**raw, "rates": saved["rates"]} if isinstance(raw, dict) and "rates" not in raw else raw + return {**{key: saved[key] for key in LATE if key not in raw}, **raw} if isinstance(raw, dict) else raw def radio_moved(stored: object) -> object: diff --git a/orchestrator/kvb_orchestrator/speechgate.py b/orchestrator/kvb_orchestrator/speechgate.py index 552ab55..951f7f6 100644 --- a/orchestrator/kvb_orchestrator/speechgate.py +++ b/orchestrator/kvb_orchestrator/speechgate.py @@ -12,6 +12,7 @@ from .records import READ_FLAGS, epoch, parse_line FRESH = 120 TAIL = 1 << 16 +ALWAYS = 100 def tail_lines(path: Path, size: int) -> list[str]: @@ -65,12 +66,14 @@ class CpuGate: def state(self) -> dict: """Returns: - {"threshold", "cpu", "open"}: open only while the latest fresh - sample lies below the threshold; cpu None without one. + {"threshold", "cpu", "open"}: open while the latest fresh sample + lies below the threshold, and at a threshold of ALWAYS even + without one, so a threshold of 0 never opens; cpu None without a + fresh sample. """ cpu = latest_cpu(self.samples, self.clock()) limit = self.threshold() - return {"threshold": limit, "cpu": cpu, "open": cpu is not None and cpu < limit} + return {"threshold": limit, "cpu": cpu, "open": limit >= ALWAYS or (cpu is not None and cpu < limit)} def admit(self, line: str) -> None: """Args: @@ -79,14 +82,12 @@ class CpuGate: same few lines per voice and outlives the cache trim. Returns: - None when the line may render; otherwise it raises Held busy - while the latest fresh sample is at or above the threshold and - Held unknown without a fresh sample. + None when the line may render; otherwise, while the gate is shut, + it raises Held unknown without a fresh sample and Held busy with + one. """ if line in PROCEDURE_LINES: return gate = self.state() - if gate["cpu"] is None: - raise Held("unknown") if not gate["open"]: - raise Held("busy") + raise Held("unknown" if gate["cpu"] is None else "busy") diff --git a/orchestrator/kvb_orchestrator/view.py b/orchestrator/kvb_orchestrator/view.py index be2bc3b..04a79bc 100644 --- a/orchestrator/kvb_orchestrator/view.py +++ b/orchestrator/kvb_orchestrator/view.py @@ -15,6 +15,7 @@ from .council import ( silence_of, ) from .crons import queue_entries +from .engines import pitch_of from .errors import ToolError from .events import KINDS, VIEWS from .fields import decode, instant, single @@ -107,8 +108,9 @@ class View: source = directory.key(row["from"], row["ts"]) targets = [directory.key(name, row["ts"]) for name in row["to"]] called = [directory.at(key, row["ts"]) or name for key, name in zip(targets, row["to"], strict=True)] - word, rest = phrase_parts(row["class"], directory.at(source, row["ts"]) or row["from"], called, row["text"]) - spoken = {"speech": joined((word, rest)), "word": word, "rest": rest, "voice": self.speech.voice_of(source)} + speaker = directory.at(source, row["ts"]) or row["from"] + word, rest = phrase_parts(row["class"], speaker, called, row["text"]) + spoken = {"speech": joined((word, rest)), "word": word, "rest": rest, "voice": self.speech.voice_of(source), "pitch": pitch_of(source), "speaker": speaker, "called": called} read = read_of(inlined, row["ts"]) radio.append({**row, "source": source, "targets": targets, "now": directory.now(source), **spoken, **read}) grant_rows = [{**grant, "target": directory.key(grant["to"], grant["ts"])} for grant in grants(history, (begin, end), claims, tasks)] diff --git a/orchestrator/templates/index.html.j2 b/orchestrator/templates/index.html.j2 index 507f620..b15a071 100644 --- a/orchestrator/templates/index.html.j2 +++ b/orchestrator/templates/index.html.j2 @@ -493,6 +493,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi {% include "radioset.js" %} +{% include "morse.js" %} + {% include "receipts.js" %} {% include "bubbles.js" %} @@ -620,12 +622,16 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi {% include "page-radioview.js" %} +{% include "page-radiolog.js" %} + {% include "page-composer.js" %} {% include "page-settings.js" %} {% include "page-speech.js" %} +{% include "page-morse.js" %} + {% include "page-mic.js" %} {% include "page-bubbles.js" %} diff --git a/orchestrator/templates/morse.js b/orchestrator/templates/morse.js new file mode 100644 index 0000000..120df15 --- /dev/null +++ b/orchestrator/templates/morse.js @@ -0,0 +1,90 @@ +const Morse = (() => { + "use strict"; + const CODES = { + a: ".-", b: "-...", c: "-.-.", d: "-..", e: ".", f: "..-.", g: "--.", h: "....", i: "..", j: ".---", k: "-.-", l: ".-..", m: "--", + n: "-.", o: "---", p: ".--.", q: "--.-", r: ".-.", s: "...", t: "-", u: "..-", v: "...-", w: ".--", x: "-..-", y: "-.--", z: "--..", + 0: "-----", 1: ".----", 2: "..---", 3: "...--", 4: "....-", 5: ".....", 6: "-....", 7: "--...", 8: "---..", 9: "----.", + ".": ".-.-.-", ",": "--..--", "?": "..--..", "'": ".----.", "!": "-.-.--", "/": "-..-.", "(": "-.--.", ")": "-.--.-", "&": ".-...", + ":": "---...", ";": "-.-.-.", "=": "-...-", "+": ".-.-.", "-": "-....-", _: "..--.-", "\"": ".-..-.", $: "...-..-", "@": ".--.-.", + ä: ".-.-", æ: ".-.-", à: ".--.-", å: ".--.-", ç: "-.-..", è: ".-..-", é: "..-..", ñ: "--.--", ö: "---.", ø: "---.", ü: "..--", ß: "...--..", + }; + const UNITS = {dot: 1, dash: 3, inner: 1, letter: 3, word: 7}; + const PARIS = 50; + const MINUTE = 60000; + const SPEED = {min: 5, max: 40, step: 1}; + + function codeOf(char) { + const folded = char.toLowerCase(); + const base = folded.normalize("NFD").charAt(0); + if (Object.hasOwn(CODES, folded)) { + return CODES[folded]; + } + return Object.hasOwn(CODES, base) ? CODES[base] : ""; + } + + /** + * @param {string} text clear text. + * @returns {Array>} its words, each the codes of its letters, case-folded; a letter with an accent and no code of its own keys its base letter, any other character without a code is skipped and a word left without one is dropped. + */ + function words(text) { + return String(text).normalize("NFC").split(/\s+/).map((word) => [...word].map(codeOf).filter(Boolean)).filter((codes) => codes.length); + } + + /** + * @param {string} text a prosign such as SOS. + * @returns {Array>} one word holding one sign: the codes of its letters keyed without the gap between letters; none for a text without a code. + */ + function joined(text) { + const sign = words(text).flat().join(""); + return sign ? [[sign]] : []; + } + + /** + * @param {number} wpm the speed in words per minute. + * @returns {number} the length of one dot in ms after PARIS: a word is 50 dot units. + */ + function dot(wpm) { + return MINUTE / (PARIS * wpm); + } + + function letterUnits(code, at, tones) { + let end = at; + [...code].forEach((mark, index) => { + const length = mark === "-" ? UNITS.dash : UNITS.dot; + tones.push([end, length]); + end += length + (index < code.length - 1 ? UNITS.inner : 0); + }); + return end; + } + + /** + * @param {Array>} signs words of letter codes, as words and joined give them. + * @param {number} wpm the speed in words per minute. + * @returns {{tones: Array>, ms: number}} every tone as [start, length] in ms and the whole length in ms, each word closed by the gap between words as PARIS counts it. + */ + function timeline(signs, wpm) { + const tones = []; + let at = 0; + for (const word of signs) { + word.forEach((code, letter) => { + at = letterUnits(code, at, tones) + (letter < word.length - 1 ? UNITS.letter : 0); + }); + at += UNITS.word; + } + const unit = dot(wpm); + return {tones: tones.map(([start, length]) => [start * unit, length * unit]), ms: at * unit}; + } + + /** + * @param {number} wpm the speed in words per minute. + * @returns {string} the speed as the radio shows it, with the dot units per minute after PARIS. + */ + function rate(wpm) { + return `${wpm} WPM (${wpm * PARIS} dots/min)`; + } + + return {SPEED, CODES, words, joined, dot, timeline, rate}; +})(); +if (typeof module === "object" && module.exports) { + module.exports = Morse; +} diff --git a/orchestrator/templates/page-morse.js b/orchestrator/templates/page-morse.js new file mode 100644 index 0000000..e37229b --- /dev/null +++ b/orchestrator/templates/page-morse.js @@ -0,0 +1,60 @@ + const MORSE_EDGE = 0.005; + + function morseSigns(step) { + return [...(step.joined ? Morse.joined(step.sign) : Morse.words(step.sign)), ...Morse.words(step.text)]; + } + + function keyEdge(param, at, length, level) { + const edge = Math.min(MORSE_EDGE, length / 4); + param.setValueAtTime(0, at); + param.linearRampToValueAtTime(level, at + edge); + param.setValueAtTime(level, at + length - edge); + param.linearRampToValueAtTime(0, at + length); + } + + /** + * @param {AudioContext} sound the page's audio context. + * @param {object} item the row that sounds now. + * @param {object} step the Morse step the radio set planned: sign, joined, text and pitch. + * @returns {Promise} whether the whole message was keyed to its end; false when Stop or a mode change cut it or its tone is silent. + */ + function keyMorse(sound, item, step) { + const level = loudness(item.tone); + const {tones, ms} = Morse.timeline(morseSigns(step), settings.morse.wpm); + if (level <= 0 || !tones.length) { + return Promise.resolve(false); + } + const source = sound.createOscillator(); + const gain = sound.createGain(); + const start = sound.currentTime; + const seconds = ms / 1000; + source.type = "sine"; + source.frequency.value = step.pitch; + gain.gain.setValueAtTime(0, start); + tones.forEach(([at, length]) => keyEdge(gain.gain, start + at / 1000, length / 1000, level)); + source.connect(gain).connect(sound.destination); + voicePace(item, Infinity, seconds); + const ended = sounded(item, source, seconds); + source.start(start); + source.stop(start + seconds); + return ended.then(() => speech.item === item && !item.cut); + } + + async function setMorseSpeed(wpm) { + if (wpm !== settings.morse.wpm && await saveSettings({...settings, space: savedSpace(), morse: {wpm}})) { + toast("Morse speed saved", [`The radio keys Morse at ${Morse.rate(wpm)}.`], true); + } + redrawFilters(); + } + + function morseSpeed() { + const {wpm} = settings.morse; + const shown = h("output", {class: "morse-rate"}, Morse.rate(wpm)); + const input = h("input", {type: "range", class: "knob", ...Morse.SPEED, value: wpm, ...named("Morse speed", "Morse speed: words per minute after PARIS, for every browser of this hub"), on: { + input: (event) => { + shown.textContent = Morse.rate(Number(event.target.value)); + }, + change: (event) => setMorseSpeed(Number(event.target.value)), + }}); + return h("label", {class: "morse-speed"}, h("span", {}, "Morse speed"), input, shown); + } diff --git a/orchestrator/templates/page-radiolog.js b/orchestrator/templates/page-radiolog.js new file mode 100644 index 0000000..a681b50 --- /dev/null +++ b/orchestrator/templates/page-radiolog.js @@ -0,0 +1,233 @@ + 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"}; + const COPIED = 1600; + const FOLDED_READERS = 3; + + function keepLog(change) { + keepRadio({log: {...radioSet.log, ...change}}); + } + + 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 = 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 = 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"}, 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), + 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 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)]); + for (const dom of liveParts("logs")) { + if (sig !== dom.sig) { + dom.sig = sig; + drawLogPart(dom, entry); + } + } + } + + function drawLogPart(dom, entry) { + const counts = RadioSet.counts(state.radio, HUMAN, state.messages); + 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); + 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); + 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 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", 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; + } diff --git a/orchestrator/templates/page-radioview.js b/orchestrator/templates/page-radioview.js index 8e05016..c611702 100644 --- a/orchestrator/templates/page-radioview.js +++ b/orchestrator/templates/page-radioview.js @@ -4,11 +4,8 @@ auto: ["bi-volume-up", "Auto", "Auto: speech while the host CPU lies below the threshold, otherwise the noise burst"], quiet: ["bi-soundwave", "Quiet", "Quiet: the noise burst only, never speech; MAYDAY, PAN-PAN and Sécurité still sound their procedure word"], silence: ["bi-volume-mute", "Silence", "Silence: no sound, bubbles and log only; MAYDAY, PAN-PAN and Sécurité still sound their procedure word"], + morse: ["bi-three-dots", "Morse", "Morse: every message keyed whole in Morse, in its sender's own pitch, at the hub's Morse speed; MAYDAY keys SOS"], }; - 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"}; - const COPIED = 1600; - const FOLDED_READERS = 3; const radioParts = {bars: [], devices: [], logs: [], speaks: []}; const liveParts = (kind) => radioParts[kind].filter((part) => part.root.isConnected); @@ -92,9 +89,7 @@ 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"}`; + cpu.title = `${gate.cpu === null ? "No host CPU sample of the last two minutes" : `Host CPU ${fixed(gate.cpu)} %`}, threshold: ${RadioSet.gateLabel(gate.threshold)}${gate.open ? "" : ", so the hub renders no new speech line and the radio plays the burst"}`; } } @@ -126,7 +121,8 @@ value.textContent = event.target.value; change(Number(event.target.value)); }}}); - return {input, value, row: h("div", {class: "knob-row", title: hint}, h("span", {class: "knob-label", title: label}, label), input, value)}; + const name = h("span", {class: "knob-label", title: label}, label); + return {input, value, name, row: h("div", {class: "knob-row", title: hint}, name, input, value)}; } function toneKnob(id, label) { @@ -144,17 +140,22 @@ async function setThreshold(value) { if (value !== settings.speech.threshold && await saveSettings({...settings, space: savedSpace(), speech: {threshold: value}})) { - toast("Speech threshold saved", [`The hub renders new speech only while the host CPU lies below ${value} %.`], true); + toast("Speech threshold saved", [`The hub renders new speech: ${RadioSet.gateLabel(value)}.`], true); } drawRadioSet(); } + function drawGate(gate, value) { + gate.name.textContent = RadioSet.gateLabel(value); + gate.name.title = gate.name.textContent; + gate.value.textContent = `${value} %`; + gate.input.setAttribute("aria-valuetext", gate.name.textContent); + } + function knobs() { const tones = SOUND_KINDS.map(([id, label]) => toneKnob(id, label)); const squelch = knob("Squelch", "Squelch: scales every tone, the speech and the burst; 0 plays none", {min: 0, max: 1, step: 0.05}, (value) => keepRadio({squelch: value})); - const threshold = knob("Threshold", "Speech threshold: the hub renders new speech only while the host CPU lies below it; your passkey signs each change", {min: 30, max: 90, step: 10}, (value) => { - threshold.value.textContent = `${value} %`; - }); + const threshold = knob("Threshold", "Speech threshold: the hub renders new speech only while the host CPU lies below it, always at 100 %, never at 0 %; your passkey signs each change", RadioSet.GATE, (value) => drawGate(threshold, value)); threshold.input.addEventListener("change", (event) => setThreshold(Number(event.target.value))); 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; @@ -294,7 +295,8 @@ return h("div", {class: "radio-read", "aria-label": "Read aloud"}, h("p", {class: "muted"}, state.speech.tts ? "The radio sounds for these classes and agents, each speaker with its own voice; MAYDAY always sounds." : `The hub speaks no line: ${state.speech.tts_off}. The burst and the procedure words stand in.`), h("div", {class: "chips", role: "group", "aria-label": "Classes"}, classes), - agents.length ? h("div", {class: "chips", role: "group", "aria-label": "Agents"}, agents) : null); + agents.length ? h("div", {class: "chips", role: "group", "aria-label": "Agents"}, agents) : null, + morseSpeed()); } function redrawFilters() { @@ -305,235 +307,6 @@ } } - function keepLog(change) { - keepRadio({log: {...radioSet.log, ...change}}); - } - - 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 = 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 = 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"}, 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), - 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 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)]); - for (const dom of liveParts("logs")) { - if (sig !== dom.sig) { - dom.sig = sig; - drawLogPart(dom, entry); - } - } - } - - function drawLogPart(dom, entry) { - const counts = RadioSet.counts(state.radio, HUMAN, state.messages); - 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); - 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); - 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 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", 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() { for (const part of liveParts("devices")) { for (const button of part.face.modes.querySelectorAll("button[data-mode]")) { @@ -551,7 +324,7 @@ 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} %`; + drawGate(threshold, settings.speech.threshold); } drawDisplay(); drawLog(); diff --git a/orchestrator/templates/page-settings.js b/orchestrator/templates/page-settings.js index efb0e6b..dfa9423 100644 --- a/orchestrator/templates/page-settings.js +++ b/orchestrator/templates/page-settings.js @@ -152,6 +152,7 @@ channels: Object.fromEntries(CHANNEL_CHOICES.map(([id]) => [id, channels[id].checked])), streams: settings.streams, speech: settings.speech, + morse: settings.morse, space: savedSpace(), estimation: settings.estimation, trend: settings.trend, diff --git a/orchestrator/templates/page-speech.js b/orchestrator/templates/page-speech.js index cfd73f2..c19b515 100644 --- a/orchestrator/templates/page-speech.js +++ b/orchestrator/templates/page-speech.js @@ -46,10 +46,21 @@ */ function say(...items) { speech.pending = items.reduce((pending, item) => Voice.enqueue(pending, item, SPEECH_QUEUE), speech.pending); + preempt(); pump(); drawBubbles(); } + function preempt() { + const {item, source} = speech; + const [first] = speech.pending; + if (item && source && item.playing === "morse" && first && Voice.rank(first) < Voice.rank(item)) { + speech.item = null; + speech.pending = Voice.enqueue(speech.pending, item, SPEECH_QUEUE); + source.stop(); + } + } + /** * @param {object} item the row that sounds now. * @param {number} span how many of its unread words this sound says: Infinity for the spoken rest, 0 for a procedure word. @@ -213,19 +224,28 @@ await burst(audio, item); continue; } + if (step.kind === "morse") { + voiced = (await keyMorse(audio, item, step)) || voiced; + done -= Number(item.cut); + continue; + } const failed = await spoken(audio, item, step, done); if (failed === "dropped") { done -= 1; continue; } voiced = voiced || (!failed && step.kind === "speech"); - if (failed && failed !== "held") { - speechFailed([failed]); - } - if (failed && step.kind === "speech" && speech.item === item && allows(stepOf(item, done), "burst")) { - item.playing = "burst"; - await burst(audio, item); - } + await fellBack(audio, item, step, done, failed); + } + } + + async function fellBack(audio, item, step, done, failed) { + if (failed && failed !== "held") { + speechFailed([failed]); + } + if (failed && step.kind === "speech" && speech.item === item && allows(stepOf(item, done), "burst")) { + item.playing = "burst"; + await burst(audio, item); } } diff --git a/orchestrator/templates/radioset.js b/orchestrator/templates/radioset.js index 23a6e05..da69b60 100644 --- a/orchestrator/templates/radioset.js +++ b/orchestrator/templates/radioset.js @@ -1,7 +1,7 @@ const RadioSet = (() => { "use strict"; const KEY = "kvb-orchestrator.radio"; - const MODES = ["auto", "quiet", "silence"]; + const MODES = ["auto", "quiet", "silence", "morse"]; const TONES = ["mayday", "review", "direct", "radio"]; const CLASSES = ["post", "call", "newsletter", "broadcast", "mayday", "pan-pan", "security"]; const TO_ALL = new Set(["newsletter", "broadcast", "mayday", "pan-pan", "security"]); @@ -11,6 +11,17 @@ const RadioSet = (() => { const MUTED_LIMIT = 200; const BURST = {seconds: 0.6, frequency: 1800, q: 0.9}; const MARK = /\[kvb-orchestrator msg ([0-9a-f]{16})\]/; + const MARKS = new RegExp(MARK.source, "g"); + const GATE = {min: 0, max: 100, step: 10}; + const PROSIGNS = { + mayday: {sign: "SOS", joined: true, called: false}, + "pan-pan": {sign: "PAN PAN", joined: false, called: false}, + security: {sign: "SECURITE", joined: false, called: false}, + broadcast: {sign: "CQ", joined: false, called: false}, + newsletter: {sign: "CQ", joined: false, called: false}, + call: {sign: "", joined: false, called: true}, + post: {sign: "KA", joined: true, called: false}, + }; const DEFAULTS = { mode: "auto", sounds: {mayday: {on: true, volume: 0.9}, review: {on: true, volume: 0.6}, direct: {on: true, volume: 0.5}, radio: {on: false, volume: 0.25}}, @@ -63,15 +74,27 @@ const RadioSet = (() => { } /** - * @param {object} row a radio row of the state with word, rest and voice. + * @param {object} row a radio row of the state with class, called, speaker, pitch and text. + * @returns {{kind: string, sign: string, joined: boolean, text: string, pitch: number}} the whole row keyed in Morse: the class prosign, or the called stations of a call, then DE with the sender's clear name and the full text without the hub's message mark, in the sender's pitch. + */ + function morse(row) { + const {sign, joined, called} = PROSIGNS[row.class]; + return {kind: "morse", sign: called ? row.called.join(" ") : sign, joined, text: `DE ${row.speaker} ${row.text.replace(MARKS, " ")}`, pitch: row.pitch}; + } + + /** + * @param {object} row a radio row of the state with word, rest, voice and the Morse fields. * @param {object} set the radio set. * @param {Object} live tts and open: whether the hub speaks at all and whether its CPU gate is open. - * @returns {Array<{kind: string, text: (string|undefined)}>} what plays, in order: the procedure word line in every mode, then the spoken rest in Auto below the threshold, else the noise burst, nothing more in Silence. + * @returns {Array<{kind: string, text: (string|undefined)}>} what plays, in order: in Morse the whole row keyed once; else the procedure word line in every mode, then the spoken rest in Auto below the threshold, else the noise burst, nothing more in Silence. */ function plan(row, set, live) { if (!picked(row, set)) { return []; } + if (set.mode === "morse") { + return [morse(row)]; + } const word = live.tts && row.voice && row.word ? [{kind: "word", text: row.word}] : []; if (set.mode === "silence") { return word; @@ -88,6 +111,17 @@ const RadioSet = (() => { return {...BURST, gain: loudness}; } + /** + * @param {number} threshold the speech threshold in percent. + * @returns {string} the threshold as the radio labels it: always at the top of the range, never at its bottom, else the CPU percent speech stays below. + */ + function gateLabel(threshold) { + if (threshold >= GATE.max) { + return "always"; + } + return threshold <= GATE.min ? "never" : `speak while CPU < ${threshold} %`; + } + function toAll(row) { return TO_ALL.has(row.class) || !row.to.length; } @@ -167,7 +201,7 @@ const RadioSet = (() => { return {...entry, chips: Object.fromEntries(CHIPS.map((name) => [name, ""])), q: ""}; } - return {KEY, MODES, TONES, CLASSES, TABS, CHIPS, DEFAULTS, valid, picked, plan, burst, toAll, ledgerOf, logRows, counts, choices, cleared}; + return {KEY, MODES, TONES, CLASSES, TABS, CHIPS, DEFAULTS, GATE, PROSIGNS, valid, picked, plan, burst, gateLabel, toAll, ledgerOf, logRows, counts, choices, cleared}; })(); if (typeof module === "object" && module.exports) { module.exports = RadioSet; diff --git a/orchestrator/templates/style-ui.css b/orchestrator/templates/style-ui.css index 3bfd1a7..f5354de 100644 --- a/orchestrator/templates/style-ui.css +++ b/orchestrator/templates/style-ui.css @@ -112,6 +112,9 @@ body.fit .spot-host { flex: none; } .knob-test { grid-column: 5; } .radio-read { display: grid; gap: var(--sp-2); } .radio-read .chips { margin-bottom: 0; } +.morse-speed { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-1) var(--sp-2); min-width: 0; color: var(--muted); font-size: var(--fs-sm); } +.morse-speed .knob { flex: 1 1 8rem; width: auto; } +.morse-rate { font-family: var(--mono); font-variant-numeric: tabular-nums; white-space: nowrap; } .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; } @@ -166,6 +169,9 @@ body.fit .spot-host { flex: none; } .radio-home-radio > .radio-grid { flex: none; grid-template-rows: none; } .radio-home-radio .radio-log { flex: none; height: auto; overflow: visible; } } +@container radio (max-width: 60rem) { + .radio-modes button { gap: 4px; padding-inline: 7px; } +} @container history (max-width: 34rem) { .radio-row, .radio-pick { gap: 4px; } .radio-pick { padding-inline-start: 6px; } diff --git a/orchestrator/templates/voice.js b/orchestrator/templates/voice.js index 1078567..b4296d1 100644 --- a/orchestrator/templates/voice.js +++ b/orchestrator/templates/voice.js @@ -79,7 +79,7 @@ const Voice = (() => { return {value: `${before}${lead}${words}${tail}${after}`, caret: before.length + lead.length + words.length}; } - return {FIELDS, toneOf, loudness, beep, enqueue, frames, wav, spliced}; + return {FIELDS, toneOf, loudness, beep, rank, enqueue, frames, wav, spliced}; })(); if (typeof module === "object" && module.exports) { module.exports = Voice; diff --git a/tests/e2e/radio_set_kit.py b/tests/e2e/radio_set_kit.py index f8706e5..49eb7c2 100644 --- a/tests/e2e/radio_set_kit.py +++ b/tests/e2e/radio_set_kit.py @@ -277,6 +277,71 @@ LIGHT = """(async () => {@HELPERS@@RADIO@ await sleep(1500); return {violations: window.e2eViolations}; })()""" +WPMS = {1920: 12, 1366: 25, 390: 40} +MORSE_SPY = """() => { + (@SPY@)(); + const keyed = window.e2eMorse = []; + const start = OscillatorNode.prototype.start; + OscillatorNode.prototype.start = function keying(...args) { + this.e2e = {frequency: this.frequency.value, type: this.type, start: args[0], stop: null, cut: false}; + keyed.push(this.e2e); + return start.apply(this, args); + }; + const stop = OscillatorNode.prototype.stop; + OscillatorNode.prototype.stop = function unkeying(...args) { + if (this.e2e && args[0] === undefined) { + this.e2e.cut = true; + } else if (this.e2e) { + this.e2e.stop = args[0]; + } + return stop.apply(this, args); + }; +}""".replace("@SPY@", SPY) +MORSE_KEYED = """ + const keyed = () => window.e2eMorse.filter((entry) => entry.stop !== null && entry.stop - entry.start > 1); + const speed = () => spot.querySelector('#radio-gear input[aria-label="Morse speed"]'); + const rate = () => text(spot.querySelector("#radio-gear .morse-rate")); + const gear = () => all(".spot-head button", spot).find((button) => name(button) === "Read aloud"); +""" +MORSE = """(async () => {@HELPERS@@RADIO@@KEYED@ + press("morse"); + await sleep(200); + const mode = [pressed(), field("mode"), spot.querySelector('.radio-modes button[data-mode="morse"]').title]; + if (gear().getAttribute("aria-expanded") !== "true") { + gear().click(); + await sleep(200); + } + const before = [speed().min, speed().max, speed().step, speed().value, rate()]; + speed().value = "@WPM@"; + speed().dispatchEvent(new Event("input", {bubbles: true})); + const dragged = rate(); + speed().dispatchEvent(new Event("change", {bubbles: true})); + const toast = await until(() => all("#toasts .toast strong").map(text).includes("Morse speed saved"), 15000); + await sleep(300); + const saved = [speed().value, rate()]; + const gearFits = fits(); + gear().click(); + await sleep(200); + const at = {tts: audio().tts.length, keyed: keyed().length}; + await cue("alarm"); + refreshNow(); + const playing = await until(() => keyed().length > at.keyed && lamp().dataset.lit === "true", 20000); + const caption = spot.querySelector(".radio-caption"); + return { + mode, before, dragged, toast: Boolean(toast), saved, gearFits, playing: Boolean(playing), keyed: keyed().slice(at.keyed), tts: audio().tts.length - at.tts, + lamp: [text(lamp()), lamp().dataset.lit], caption: [caption.hidden, text(caption.querySelector("strong"))], fits: fits(), + }; +})()""".replace("@KEYED@", MORSE_KEYED) +MORSE_STOP = """(async () => {@HELPERS@@RADIO@@KEYED@ + const last = keyed()[keyed().length - 1]; + const caption = spot.querySelector(".radio-caption"); + const stop = all("button", caption).find((button) => name(button) === "Stop speaking"); + const before = [Boolean(stop), lamp().dataset.lit, last.cut]; + stop.click(); + const quiet = Boolean(await until(() => lamp().dataset.lit === "false", 2000)); + await sleep(500); + return {before, cut: last.cut, quiet, hidden: caption.hidden, later: keyed().filter((entry) => !entry.cut).length}; +})()""".replace("@KEYED@", MORSE_KEYED) def probe(template: str) -> str: diff --git a/tests/e2e/test_hub_radio_e2e.py b/tests/e2e/test_hub_radio_e2e.py index 3bf1d3b..0c70d96 100644 --- a/tests/e2e/test_hub_radio_e2e.py +++ b/tests/e2e/test_hub_radio_e2e.py @@ -304,7 +304,7 @@ class TestHubRadio(base.OrchestratorE2ECase): self.assertEqual((run["direct"], run["question"], run["left"]), (direct, [mayday] if run["cls"] == "mayday" else [], ""), run) self.assertTrue((run["toast"] or "").startswith(f"{labels[run['cls']]} to {'Stage' if direct else 'all'}: sent"), run) self.assertEqual((saved["expanded"], saved["clashes"]), ("true", [{"found": [], "outside": []}] * 2)) - self.assertEqual(saved["tones"], ["MAYDAY / PAN-PAN", "Reviews, asks, decisions", "Post and calls to you", "All radio", "Squelch", "Threshold"]) + self.assertEqual(saved["tones"], ["MAYDAY / PAN-PAN", "Reviews, asks, decisions", "Post and calls to you", "All radio", "Squelch", "speak while CPU < 50 %"]) self.assertEqual([entry[0] for entry in saved["classes"]], ["Post", "Call", "Newsletter", "Broadcast", "MAYDAY", "PAN-PAN", "Sécurité"]) 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])) diff --git a/tests/e2e/test_radio_set_e2e.py b/tests/e2e/test_radio_set_e2e.py index 4bd781d..94d630c 100644 --- a/tests/e2e/test_radio_set_e2e.py +++ b/tests/e2e/test_radio_set_e2e.py @@ -16,7 +16,7 @@ import hub_e2e_kit as base from hub_case import HubCase from hub_engines import log_rows from hub_support import iso -from kvb_orchestrator import errors, phrasing, speechgate +from kvb_orchestrator import engines, errors, phrasing, speechgate from radio_set_kit import ( BURST, BURST_DONE, @@ -26,6 +26,9 @@ from radio_set_kit import ( LIGHT, LOG, LOG_KEPT, + MORSE, + MORSE_SPY, + MORSE_STOP, OUT, SOUND, SOUND_KEPT, @@ -33,6 +36,7 @@ from radio_set_kit import ( THRESHOLD, THRESHOLDS, WORD, + WPMS, probe, ) @@ -132,12 +136,13 @@ class TestRadioSet(HubCase): self.assertEqual(face["display"]["mode"], "Auto") self.assertEqual((face["display"]["cpu"], face["display"]["lamp"]), ("CPU 10 %", ["RX", "false"]), face) self.assertTrue(face["display"]["cls"], face) - self.assertEqual([mode_[:2] for mode_ in face["modes"]], [["Auto", "true"], ["Quiet", "false"], ["Silence", "false"]]) + self.assertEqual([mode_[:2] for mode_ in face["modes"]], [["Auto", "true"], ["Quiet", "false"], ["Silence", "false"], ["Morse", "false"]]) self.assertTrue(all(mode_[2] and mode_[3] for mode_ in face["modes"]), face["modes"]) self.assertEqual([knob[0] for knob in face["knobs"]], ["MAYDAY / PAN-PAN", "Reviews, asks, decisions", "Post and calls to you", "All radio", "Squelch", "Threshold"]) - self.assertEqual(face["knobs"][-1][1:], ["30", "90", "10", "50" if index == 0 or not signed else str(THRESHOLDS[base.WIDTHS[index - 1][0]])]) + shown = "50" if index == 0 or not signed else str(THRESHOLDS[base.WIDTHS[index - 1][0]]) + self.assertEqual(face["knobs"][-1][1:], ["0", "100", "10", shown]) self.assertEqual(len(face["toneToggles"]), 4) - self.assertEqual([label["text"] for label in face["labels"]], [knob[0] for knob in face["knobs"]]) + self.assertEqual([label["text"] for label in face["labels"]], [*(knob[0] for knob in face["knobs"][:-1]), f"speak while CPU < {shown} %"]) for label in face["labels"]: self.assertEqual((label["title"], label["row"]), (label["text"], True), label) self.assertTrue(label["whole"] or width == 390, label) @@ -217,7 +222,7 @@ class TestRadioSet(HubCase): if signed: self.assertEqual(threshold["after"], [value, threshold["before"][1] + 1], threshold) self.assertEqual(threshold["shown"], f"{value} %") - self.assertIn(f"below {value} %", threshold["title"]) + self.assertIn(f"speak while CPU < {value} %", threshold["title"]) else: self.assertEqual(threshold["after"], [threshold["before"][0], threshold["before"][1]], threshold) self.assertIn("Settings: not signed", threshold["toasts"]) @@ -228,6 +233,54 @@ class TestRadioSet(HubCase): self.assertEqual(len(words), 1, "the procedure word line of one voice renders once and then hits the cache") self.assertEqual(self.httpd.hub.settings.get()["speech"]["threshold"], THRESHOLDS[390] if signed else 50) + def morse_steps(self, browser: str) -> list[dict]: + steps = [] + for width, height in base.WIDTHS: + shot = str(OUT / f"{browser}-{width}-radio-morse") + steps += [ + {"width": width, "height": height, "url": f"{self.base}?{width}-morse#stream", "wait": 1200, "probe": probe(MORSE).replace("@WPM@", str(WPMS[width])), "shot": f"{shot}-keying.png", "gesture": True}, + {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(MORSE_STOP), "shot": f"{shot}-stopped.png", "gesture": True}, + ] + return steps + + def check_morse(self, data: dict, browser: str) -> None: + results = iter(data["results"]) + before = 20 + for width, _ in base.WIDTHS: + keying, stopped = next(results), next(results) + wpm = WPMS[width] + with self.subTest(browser=browser, width=width, part="morse keying"): + self.assertNotIn("error", keying, keying) + self.assertEqual(keying["mode"][:2], [["morse"], "Morse"], keying) + self.assertIn("SOS", keying["mode"][2]) + self.assertEqual(keying["before"], ["5", "40", "1", str(before), f"{before} WPM ({before * 50} dots/min)"], keying) + self.assertEqual((keying["dragged"], keying["toast"], keying["saved"]), (f"{wpm} WPM ({wpm * 50} dots/min)", True, [str(wpm), f"{wpm} WPM ({wpm * 50} dots/min)"]), keying) + self.assertTrue(keying["playing"], keying) + self.assertEqual([(entry["frequency"], entry["type"]) for entry in keying["keyed"]], [(engines.pitch_of("s2"), "sine")], keying) + self.assertEqual(keying["tts"], 0, "Morse mode asks the hub for no speech line") + self.assertEqual(keying["lamp"], ["RX", "true"]) + self.assertFalse(keying["caption"][0]) + self.assertTrue(keying["caption"][1].startswith("Stage"), keying) + self.assertEqual((keying["gearFits"], keying["fits"]), ({"page": True, "panel": True}, {"page": True, "panel": True}), keying) + with self.subTest(browser=browser, width=width, part="morse stop"): + self.assertNotIn("error", stopped, stopped) + self.assertEqual(stopped, {"before": [True, "true", False], "cut": True, "quiet": True, "hidden": True, "later": 0}, stopped) + before = wpm + self.assertEqual(self.httpd.hub.settings.get()["morse"], {"wpm": WPMS[390]}) + + def test_chromium_keys_every_row_whole_in_morse_at_the_hub_speed_in_its_sender_pitch_and_stop_cuts_it_at_three_widths(self): + data = self.drive(self.morse_steps("chromium"), None, init=MORSE_SPY) + (OUT / "chromium-radio-morse.json").write_text(json.dumps(data, indent=1), encoding="utf-8") + self.assertEqual(data["errors"], []) + self.check_morse(data, "chromium") + + @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox") + def test_firefox_keys_every_row_whole_in_morse_at_the_hub_speed_in_its_sender_pitch_and_stop_cuts_it_at_three_widths(self): + data = self.drive(self.morse_steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=MORSE_SPY) + (OUT / "firefox-radio-morse.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_morse(data, "firefox") + def test_chromium_plays_the_radio_set_modes_burst_and_procedure_words_and_filters_the_log_at_three_widths(self): data = self.drive(self.steps("chromium", True), self.authenticator(), init=SPY) (OUT / "chromium-radio-set.json").write_text(json.dumps(data, indent=1), encoding="utf-8") diff --git a/tests/test_hub_morse.py b/tests/test_hub_morse.py new file mode 100644 index 0000000..72b2819 --- /dev/null +++ b/tests/test_hub_morse.py @@ -0,0 +1,347 @@ +from __future__ import annotations + +import json +import subprocess +import tempfile +import time +import unittest +from pathlib import Path +from unittest import mock + +from hub_case import HubCase +from hub_support import HUB +from kvb_orchestrator import council, engines, errors, settings + +TEMPLATES = HUB / "templates" +MORSE = TEMPLATES / "morse.js" +RADIOSET = TEMPLATES / "radioset.js" +VOICE = TEMPLATES / "voice.js" +PAGE_SPEECH = TEMPLATES / "page-speech.js" +PAGE_MORSE = TEMPLATES / "page-morse.js" +MARK = "[kvb-orchestrator msg 0123456789abcdef]" +TEXT = f"disk full\nsecond line {MARK}" +SIGNS = { + "mayday": ("SOS", True), "pan-pan": ("PAN PAN", False), "security": ("SECURITE", False), "broadcast": ("CQ", False), + "newsletter": ("CQ", False), "call": ("Skills session", False), "post": ("KA", True), +} +CODES_PROBE = """ +const Morse = require(process.argv[1]); +const RadioSet = require(process.argv[2]); +const input = JSON.parse(process.argv[3]); +console.log(JSON.stringify({ + paris: [5, 20, 40].map((wpm) => ({dot: Morse.dot(wpm), ...Morse.timeline(Morse.words("PARIS"), wpm)})), + words: input.words.map((text) => Morse.words(text)), + joined: [Morse.joined("SOS"), Morse.joined("~ 😀")], + sos: [Morse.timeline(Morse.joined("SOS"), 20).ms, Morse.timeline(Morse.words("SOS"), 20).ms], + rates: [5, 20, 40].map(Morse.rate), + plans: input.plans.map(([row, set, live]) => RadioSet.plan(row, set, live)), + gates: [0, 10, 50, 90, 100].map(RadioSet.gateLabel), + constants: {modes: RadioSet.MODES, gate: RadioSet.GATE, speed: Morse.SPEED, prosigns: RadioSet.PROSIGNS, kept: RadioSet.valid({mode: "morse"}).mode}, +})); +""" +KEYING_PROBE = """ +const fs = require("fs"); +const vm = require("vm"); +const RadioSet = require(process.argv[1]); +const Morse = require(process.argv[2]); +const Voice = require(process.argv[3]); +const code = [process.argv[4], process.argv[5]].map((path) => fs.readFileSync(path, "utf8")).join("\\n"); +const stub = () => undefined; +const settle = async () => { + for (let round = 0; round < 60; round += 1) { + await new Promise((resolve) => setImmediate(resolve)); + } +}; +const row = (source, pitch, cls, text) => ({class: cls, source, from: source, to: [], called: [], speaker: "E", pitch, voice: "v", word: "", rest: "x", text, ts: 1000}); +function radio(plays) { + const run = {oscillators: [], buffers: [], fetches: 0, gains: []}; + class Source { + constructor() { + Object.assign(this, {type: "", frequency: {value: 0}, buffer: null, ended: null, started: null, stops: []}); + } + connect(node) { + return node; + } + addEventListener(type, ended) { + this.ended = ended; + } + start(when) { + this.started = when; + if (plays) { + setImmediate(() => this.ended && this.ended()); + } + } + stop(when) { + this.stops.push(when === undefined ? "now" : when); + if (when === undefined) { + setImmediate(() => this.ended && this.ended()); + } + } + } + const param = () => { + const events = []; + run.gains.push(events); + const log = (kind) => (value, at) => events.push([kind, value, at]); + return {value: 0, setValueAtTime: log("set"), linearRampToValueAtTime: log("ramp"), exponentialRampToValueAtTime: log("exp")}; + }; + const made = (list) => () => { + const node = new Source(); + list.push(node); + return node; + }; + const audio = { + currentTime: 0, sampleRate: 8000, destination: {}, createOscillator: made(run.oscillators), createBufferSource: made(run.buffers), + createGain: () => ({gain: param(), connect: (node) => node}), + createBiquadFilter: () => ({type: "", frequency: {value: 0}, Q: {value: 0}, connect: (node) => node}), + createBuffer: (channels, frames) => ({getChannelData: () => new Float32Array(frames)}), + }; + const sandbox = { + RadioSet, Morse, Voice, radioSet: RadioSet.valid({mode: "morse", classes: RadioSet.CLASSES}), + state: {now: 1000, messages: [], speech: {tts: false, gate: {open: false}}}, + speech: {pending: [], busy: false, warned: 0, current: null, source: null, loading: null, timer: 0, item: null}, + settings: {bubbles: false, music: {on: false, volume: 0.4}, morse: {wpm: 20}}, SPEECH_QUEUE: 20, SPEECH_QUIET: 60000, SOUND_SLACK: 2, HUMAN: "Operator", + Bubbles: {reading: () => 0.001}, wordsRead: () => 0, saidOf: (item) => item.words, + keep: stub, drawRadioSet: stub, drawBubbles: stub, drawSpeaker: stub, duck: stub, clearBubbles: stub, silenceBeeps: stub, toast: stub, + performance: {now: () => 0}, window: {setTimeout: () => 0, clearTimeout: stub}, context: () => audio, + fetch: async () => { + run.fetches += 1; + return {ok: false, status: 503, headers: {get: () => "application/json"}, text: async () => ""}; + }, + }; + vm.runInNewContext(code, sandbox); + run.sandbox = sandbox; + run.say = (item) => sandbox.say({voice: item.voice, tone: "direct", cls: item.class, who: item.source, line: item.text, words: [item.text], silent: false, row: item}); + run.idle = () => !sandbox.speech.busy && !sandbox.speech.pending.length && sandbox.speech.source === null; + return run; +} +const shape = (node) => ({type: node.type, frequency: node.frequency.value, started: node.started, stops: node.stops}); +const ons = (run) => run.gains[0].filter(([kind, value]) => kind === "ramp" && value > 0).length; +(async () => { + const whole = radio(true); + whole.say(row("s1", 640, "mayday", "E")); + await settle(); + const fast = radio(true); + fast.sandbox.settings.morse.wpm = 40; + fast.say(row("s1", 640, "mayday", "E")); + await settle(); + const two = radio(true); + two.say(row("s1", 600, "post", "E")); + two.say(row("s2", 800, "post", "E")); + await settle(); + const cut = radio(false); + cut.say(row("s1", 640, "security", "E ".repeat(500))); + await settle(); + const playing = [cut.oscillators.length, cut.sandbox.speech.source === cut.oscillators[0]]; + cut.sandbox.cancelSpeech(); + await settle(); + const switched = radio(false); + switched.say(row("s1", 640, "security", "E")); + await settle(); + switched.sandbox.keepRadio({mode: "quiet"}); + await settle(); + const urgent = radio(false); + urgent.say(row("s1", 600, "post", "E ".repeat(200))); + await settle(); + urgent.say(row("s2", 800, "mayday", "E")); + await settle(); + const calm = radio(false); + calm.say(row("s1", 600, "mayday", "E ".repeat(200))); + await settle(); + calm.say(row("s2", 800, "pan-pan", "E")); + calm.say(row("s3", 700, "post", "E")); + await settle(); + const keyed = (run) => ({oscillators: run.oscillators.map((node) => [node.frequency.value, node.stops.includes("now")]), pending: run.sandbox.speech.pending.map((item) => item.cls)}); + console.log(JSON.stringify({ + urgent: keyed(urgent), + calm: keyed(calm), + whole: {oscillators: whole.oscillators.map(shape), buffers: whole.buffers.length, fetches: whole.fetches, ons: ons(whole), idle: whole.idle()}, + fast: fast.oscillators.map(shape), + two: two.oscillators.map((node) => node.frequency.value), + cut: {playing, oscillators: cut.oscillators.map(shape), idle: cut.idle()}, + switched: {oscillators: switched.oscillators.map(shape), buffers: switched.buffers.length}, + })); +})(); +""" + + +def node(probe: str, *args: str) -> dict: + done = subprocess.run(["node", "-e", probe, *args], capture_output=True, text=True, timeout=60, check=True) + return json.loads(done.stdout) + + +def radio_row(cls: str, text: str) -> dict: + return {"class": cls, "source": "s1", "from": "Docs", "to": ["Skills session"], "called": ["Skills session"], "speaker": "Docs", "pitch": 612, "voice": "", "word": "", "rest": "", "text": text} + + +def radio_set(mode: str, muted: list[str]) -> dict: + return {"mode": mode, "classes": list(council.CLASSES), "muted": muted, "sounds": {}, "squelch": 1, "log": {}} + + +class TestMorseCode(unittest.TestCase): + @classmethod + def setUpClass(cls): + offline, online = {"tts": False, "open": False}, {"tts": True, "open": True} + plans = [[radio_row(name, TEXT), radio_set("morse", []), offline] for name in council.CLASSES] + plans += [ + [radio_row("security", TEXT), radio_set("morse", []), online], + [radio_row("security", TEXT), radio_set("morse", ["s1"]), offline], + [radio_row("mayday", TEXT), radio_set("morse", ["s1"]), offline], + [radio_row("broadcast", "word " * 600), radio_set("morse", []), offline], + ] + words = ["PARIS", "paris", "Grüße, Ëva! 😀 ~ À ÿ"] + cls.data = node(CODES_PROBE, str(MORSE), str(RADIOSET), json.dumps({"words": words, "plans": plans})) + + def test_paris_at_20_wpm_lasts_exactly_50_dot_units_of_60_ms(self): + slow, normal, fast = self.data["paris"] + self.assertEqual((normal["dot"], normal["ms"]), (60, 50 * 60)) + self.assertEqual((slow["dot"], slow["ms"], fast["dot"], fast["ms"]), (240, 50 * 240, 30, 50 * 30)) + self.assertEqual(len(normal["tones"]), 14) + self.assertEqual(normal["tones"][:4], [[0, 60], [120, 180], [360, 180], [600, 60]]) + self.assertEqual(normal["tones"][4], [(11 + 3) * 60, 60]) + self.assertEqual(normal["tones"][-1], [42 * 60, 60]) + self.assertEqual(normal["ms"] - sum(normal["tones"][-1]), 7 * 60, "the closing word gap is 7 dot units") + + def test_letters_case_fold_umlauts_key_their_code_or_base_letter_and_the_rest_is_skipped(self): + upper, lower, mixed = self.data["words"] + self.assertEqual(upper, [[".--.", ".-", ".-.", "..", "..."]]) + self.assertEqual(lower, upper) + self.assertEqual(mixed, [["--.", ".-.", "..--", "...--..", ".", "--..--"], [".", "...-", ".-", "-.-.--"], [".--.-"], ["-.--"]]) + + def test_a_prosign_keys_its_letters_without_the_letter_gap(self): + self.assertEqual(self.data["joined"], [[["...---..."]], []]) + self.assertEqual(self.data["sos"], [30 * 60, 34 * 60]) + + def test_the_speed_label_names_words_and_dot_units_per_minute(self): + self.assertEqual(self.data["rates"], ["5 WPM (250 dots/min)", "20 WPM (1000 dots/min)", "40 WPM (2000 dots/min)"]) + self.assertEqual(self.data["constants"]["speed"], {"min": settings.WPM[0], "max": settings.WPM[1], "step": 1}) + + def test_every_class_keys_its_prosign_then_de_with_the_clear_name_and_the_whole_text_in_the_sender_pitch(self): + plans = self.data["plans"] + for index, name in enumerate(council.CLASSES): + sign, joined = SIGNS[name] + with self.subTest(name=name): + self.assertEqual(plans[index], [{"kind": "morse", "sign": sign, "joined": joined, "text": f"DE Docs {TEXT.replace(MARK, ' ')}", "pitch": 612}]) + self.assertNotIn("s1", plans[index][0]["text"]) + self.assertNotIn("kvb-orchestrator", plans[index][0]["text"]) + online, muted, mayday, long = plans[len(council.CLASSES):] + self.assertEqual(online, plans[list(council.CLASSES).index("security")], "Morse needs neither the speech engine nor an open CPU gate") + self.assertEqual((muted, mayday[0]["sign"]), ([], "SOS"), "the read-aloud filters hold in Morse, a MAYDAY always keys") + self.assertEqual(long[0]["text"].count("word"), 600, "Morse keys the whole text, with no cap") + self.assertEqual(self.data["constants"]["prosigns"], {name: {"sign": "" if name == "call" else sign, "joined": joined, "called": name == "call"} for name, (sign, joined) in SIGNS.items()}) + + def test_morse_is_a_fourth_mode_and_the_threshold_labels_read_never_and_always_at_the_ends(self): + constants = self.data["constants"] + self.assertEqual((constants["modes"], constants["kept"]), (["auto", "quiet", "silence", "morse"], "morse")) + self.assertEqual(constants["gate"], {"min": settings.THRESHOLDS[0], "max": settings.THRESHOLDS[-1], "step": settings.THRESHOLDS[1] - settings.THRESHOLDS[0]}) + self.assertEqual(self.data["gates"], ["never", "speak while CPU < 10 %", "speak while CPU < 50 %", "speak while CPU < 90 %", "always"]) + + +class TestMorseKeying(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.data = node(KEYING_PROBE, str(RADIOSET), str(MORSE), str(VOICE), str(PAGE_SPEECH), str(PAGE_MORSE)) + + def test_one_sine_oscillator_keys_the_whole_row_at_the_hub_speed_in_the_row_pitch_without_speech(self): + whole = self.data["whole"] + self.assertEqual(whole["oscillators"], [{"type": "sine", "frequency": 640, "started": 0, "stops": [64 * 60 / 1000]}]) + self.assertEqual((whole["buffers"], whole["fetches"], whole["ons"], whole["idle"]), (0, 0, 15, True)) + self.assertEqual(self.data["fast"][0]["stops"], [64 * 30 / 1000]) + self.assertEqual(self.data["two"], [600, 800]) + + def test_stop_cuts_a_long_message_at_once(self): + cut = self.data["cut"] + self.assertEqual(cut["playing"], [1, True]) + self.assertEqual(cut["oscillators"][0]["stops"], [4092 * 60 / 1000, "now"], "a 1000 character text keys whole for minutes until Stop cuts it") + self.assertEqual((len(cut["oscillators"]), cut["idle"]), (1, True)) + + def test_a_higher_class_cuts_the_keying_row_which_keys_again_whole_after_it(self): + self.assertEqual(self.data["urgent"], {"oscillators": [[600, True], [800, False]], "pending": ["post"]}) + self.assertEqual(self.data["calm"], {"oscillators": [[600, False]], "pending": ["pan-pan", "post"]}, "a lower or equal class waits for the whole row") + + def test_a_mode_change_cuts_the_keying_and_replans_the_row(self): + switched = self.data["switched"] + self.assertEqual(switched["oscillators"][0]["stops"], [100 * 60 / 1000, "now"]) + self.assertEqual((len(switched["oscillators"]), switched["buffers"]), (1, 1)) + + +class TestMorsePitch(unittest.TestCase): + def test_every_speaker_keys_one_stable_pitch_inside_550_to_850_hz_and_speakers_spread_over_it(self): + keys = [f"s{number}" for number in range(200)] + pitches = [engines.pitch_of(key) for key in keys] + self.assertEqual(pitches, [engines.pitch_of(key) for key in keys]) + self.assertTrue(all(550 <= pitch <= 850 for pitch in pitches), pitches) + self.assertGreaterEqual(len(set(pitches)), 120) + self.assertLess(min(pitches), 575) + self.assertGreater(max(pitches), 825) + + def test_pitch_and_voice_come_from_the_one_speaker_slot(self): + pool = ["a:0", "b:0", "c:0"] + with mock.patch.object(engines, "slot", lambda key, count: count - 1): + self.assertEqual((engines.voice_of("s1", pool, "op"), engines.pitch_of("s1")), ("c:0", 850)) + with mock.patch.object(engines, "slot", lambda key, count: 0): + self.assertEqual((engines.voice_of("s1", pool, "op"), engines.pitch_of("s1")), ("a:0", 550)) + self.assertEqual(engines.pitch_of("s1") - 550, engines.slot("s1", 301)) + self.assertEqual(engines.voice_of("s1", pool, "op"), pool[engines.slot("s1", len(pool))]) + + +class TestMorseSetting(unittest.TestCase): + def test_the_speed_is_a_whole_number_from_5_to_40_words_per_minute_and_20_by_default(self): + self.assertEqual((settings.SETTINGS["morse"], settings.WPM), ({"wpm": 20}, (5, 40))) + for value in (5, 6, 20, 39, 40): + with self.subTest(value=value): + self.assertEqual(settings.morse_setting({"wpm": value}), {"wpm": value}) + for value in (4, 41, 0, -20, 20.0, True, False, "20", None, [20]): + with self.subTest(value=value), self.assertRaises(errors.ToolError): + settings.morse_setting({"wpm": value}) + for raw in ({}, {"wpm": 20, "extra": 1}, "20", None): + with self.subTest(raw=raw), self.assertRaises(errors.ToolError): + settings.morse_setting(raw) + + def test_a_page_or_a_file_from_before_the_speed_keeps_the_saved_or_the_default_speed(self): + saved = {**settings.SETTINGS, "morse": {"wpm": 33}, "rates": {"period": "day", "metrics": ["tasks", "cpu"]}} + older = {key: value for key, value in saved.items() if key not in ("morse", "rates")} + self.assertEqual(settings.completed(older, saved), saved) + self.assertEqual(settings.completed({**older, "morse": {"wpm": 7}}, saved)["morse"], {"wpm": 7}) + self.assertEqual(settings.completed("flat", saved), "flat") + with tempfile.TemporaryDirectory() as folder: + file = Path(folder) / "settings.json" + file.write_text(json.dumps({**older, "latitude": 52.5}), encoding="utf-8") + loaded = settings.Settings(file).get() + self.assertEqual((loaded["morse"], loaded["latitude"]), ({"wpm": 20}, 52.5)) + + +class TestMorseHttp(HubCase): + def save(self, payload: dict) -> tuple[int, dict, bytes]: + return self.post_json("/api/settings", {**payload, "proof": None}, self.guard(self.host)) + + def test_the_speed_is_validated_saved_without_a_passkey_and_survives_a_reload(self): + current = self.snapshot()["settings"] + self.assertEqual(current["morse"], {"wpm": 20}) + for wrong in ({"wpm": 4}, {"wpm": 41}, {"wpm": "20"}, {"wpm": True}, {"wpm": 20.5}, {}, {"wpm": 20, "dots": 1000}, 20): + with self.subTest(wrong=wrong): + self.assertEqual(self.save({**current, "morse": wrong})[0], 400) + status, _, body = self.post_json("/api/settings/sign", {**current, "morse": {"wpm": 33}}, self.guard(self.host)) + self.assertEqual((status, json.loads(body)["payload"]), (200, None)) + status, _, body = self.save({**current, "morse": {"wpm": 33}}) + self.assertEqual((status, json.loads(body)["settings"]["morse"]), (200, {"wpm": 33}), body) + self.assertEqual(settings.Settings(self.state / "settings.json").get()["morse"], {"wpm": 33}) + sheet = {key: value for key, value in self.snapshot()["settings"].items() if key != "morse"} + status, _, body = self.save({**sheet, "bubbles": True}) + self.assertEqual((status, json.loads(body)["settings"]["morse"]), (200, {"wpm": 33}), body) + self.assertEqual(self.snapshot()["settings"]["morse"], {"wpm": 33}) + + def test_every_radio_row_carries_the_sender_pitch_its_clear_name_and_the_called_names(self): + self.claim("s1", "Docs") + self.claim("s2", "Skills") + now = time.time() + self.write_council({"news.jsonl": self.jsonl([ + {"ts": now - 30, "from": "Docs", "to": ["Skills"], "text": "gate red", "class": "call", "v": 2}, + {"ts": now - 20, "from": "Skills", "to": [], "text": "MAYDAY disk full", "class": "mayday", "v": 2}, + ])}) + rows = [(row["source"], row["speaker"], row["called"], row["pitch"]) for row in self.snapshot()["radio"]] + self.assertEqual(rows, [("s1", "Docs", ["Skills"], engines.pitch_of("s1")), ("s2", "Skills", [], engines.pitch_of("s2"))]) + self.assertNotEqual(engines.pitch_of("s1"), engines.pitch_of("s2")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hub_radioset.py b/tests/test_hub_radioset.py index 7d3db2d..a4f41d7 100644 --- a/tests/test_hub_radioset.py +++ b/tests/test_hub_radioset.py @@ -595,7 +595,7 @@ class TestTransmit(unittest.TestCase): self.assertEqual(self.data["stalled"], {"before": [False, True], "after": [True, None], "waits": [2500], "stops": 1}) def test_every_mode_button_keeps_the_mode_before_it_resumes_the_audio_context(self): - self.assertEqual(self.data["pressed"], [{"mode": "auto"}, "context", {"mode": "quiet"}, "context", {"mode": "silence"}, "context"]) + self.assertEqual(self.data["pressed"], [{"mode": "auto"}, "context", {"mode": "quiet"}, "context", {"mode": "silence"}, "context", {"mode": "morse"}, "context"]) class TestSpeechModes(unittest.TestCase): diff --git a/tests/test_hub_receipts.py b/tests/test_hub_receipts.py index 088c78f..c7f73f2 100644 --- a/tests/test_hub_receipts.py +++ b/tests/test_hub_receipts.py @@ -41,7 +41,7 @@ const fs = require("fs"); const vm = require("vm"); const Receipts = require(process.argv[1]); const RadioSet = require(process.argv[2]); -const code = ["page-dom.js", "page-stream.js", "page-radioview.js", "page-agent.js"].map((name) => fs.readFileSync(`${process.argv[3]}/${name}`, "utf8")).join("\\n"); +const code = ["page-dom.js", "page-stream.js", "page-radioview.js", "page-radiolog.js", "page-agent.js"].map((name) => fs.readFileSync(`${process.argv[3]}/${name}`, "utf8")).join("\\n"); const input = JSON.parse(process.argv[4]); class Node { constructor(tag) { diff --git a/tests/test_hub_speech_gate.py b/tests/test_hub_speech_gate.py index 48dc682..d213020 100644 --- a/tests/test_hub_speech_gate.py +++ b/tests/test_hub_speech_gate.py @@ -88,6 +88,23 @@ class TestCpuGate(unittest.TestCase): stale.admit(LINE) self.assertEqual((held.exception.reason, stale.state()["open"]), ("unknown", False)) + def test_one_hundred_percent_keeps_the_gate_open_and_zero_percent_keeps_it_shut(self): + now = 1_800_000_000.0 + for rows in ([{"t": now - 1, "cpu": 100.0}], [{"t": now - 1, "cpu": 99.9}], [{"t": now - 121, "cpu": 5.0}], []): + with self.subTest(threshold=100, rows=rows): + gate = gate_over(rows, 100, now) + self.assertTrue(gate.state()["open"]) + self.assertIsNone(gate.admit(LINE)) + for rows, reason in (([{"t": now - 1, "cpu": 0.0}], "busy"), ([{"t": now - 1, "cpu": 12.0}], "busy"), ([], "unknown")): + with self.subTest(threshold=0, rows=rows): + gate = gate_over(rows, 0, now) + self.assertFalse(gate.state()["open"]) + with self.assertRaises(errors.Held) as held: + gate.admit(LINE) + self.assertEqual(held.exception.reason, reason) + self.assertEqual(gate_over([{"t": now - 1, "cpu": 89.0}], 90, now).state()["open"], True) + self.assertEqual(gate_over([{"t": now - 1, "cpu": 90.0}], 90, now).state()["open"], False) + def test_a_procedure_word_line_passes_under_load_and_without_a_sample(self): now = 1_800_000_000.0 for rows in ([{"t": now - 1, "cpu": 99.0}], []): @@ -121,12 +138,13 @@ class TestProcedureWords(unittest.TestCase): class TestThresholdSetting(unittest.TestCase): - def test_only_thirty_to_ninety_in_steps_of_ten_and_fifty_by_default(self): + def test_only_zero_to_one_hundred_in_steps_of_ten_and_fifty_by_default(self): self.assertEqual(settings.SETTINGS["speech"], {"threshold": 50}) - for value in (30, 40, 50, 60, 70, 80, 90): + self.assertEqual(settings.THRESHOLDS, (0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)) + for value in (0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100): with self.subTest(value=value): self.assertEqual(settings.speech_setting({"threshold": value}), {"threshold": value}) - for value in (20, 25, 35, 95, 100, 0, 50.0, True, "50", None, [50]): + for value in (-10, 5, 25, 35, 95, 110, 50.0, True, False, "50", None, [50]): with self.subTest(value=value), self.assertRaises(errors.ToolError): settings.speech_setting({"threshold": value}) for raw in ({}, {"threshold": 50, "on": True}, "50"): @@ -150,6 +168,13 @@ class TestThresholdSetting(unittest.TestCase): (folder / "settings.json").write_text(json.dumps(kept), encoding="utf-8") self.assertEqual(settings.Settings(folder / "settings.json").get()["speech"], {"threshold": 70}) + def test_every_threshold_stored_before_the_widening_still_loads(self): + folder = scratch() + for value in (30, 40, 50, 60, 70, 80, 90): + with self.subTest(value=value): + (folder / "settings.json").write_text(json.dumps({**settings.SETTINGS, "speech": {"threshold": value}}), encoding="utf-8") + self.assertEqual(settings.Settings(folder / "settings.json").get()["speech"], {"threshold": value}) + class TestHandedVoices(unittest.TestCase): def test_procedure_lines_render_under_load_only_for_voices_the_hub_hands_out_and_outlive_the_trim(self): @@ -272,7 +297,7 @@ class TestSpeechGateHttp(HubCase): self.assertEqual((status, json.loads(body)["settings"]["speech"]), (200, {"threshold": 70}), body) self.assertEqual(self.snapshot()["speech"]["gate"]["threshold"], 70) self.assertEqual(settings.Settings(self.state / "settings.json").get()["speech"], {"threshold": 70}) - for wrong in (35, 100, 20, "70", 70.0): + for wrong in (35, 110, -10, "70", 70.0): with self.subTest(wrong=wrong): self.assertEqual(self.post_json("/api/settings/sign", {**current, "speech": {"threshold": wrong}}, good)[0], 400) self.host_cpu(60.0, 5)