feat(orchestrator): Gibberlink radio mode with ggwave and a fallback selector (018)
A new radio mode sends each spoken row as ggwave frames of at most 140 bytes: frame 1 carries the full session id, later frames its 8-character prefix, each with n/m. engines.sound_of() gives every speaker one of the four audible ggwave protocols that decode every frame length, plus its own stereo position, by a stable hash. The vendored ggwave 0.4.0 (MIT, LICENSE kept, sha256 pinned in test_hub_artifacts) runs only in the /gibberlink encoder page, sandboxed into an opaque origin with eval and WebAssembly but no connection; the hub page frames it (frame-src 'self') and review pages refuse framing (frame-ancestors 'none'). The radio gear gains a fallback selector (Gibberlink, Morse, Hiss) for rows that speech cannot play. Accepted MEDUSA false positives (security.py accept after kvb-think-criticize, 2026-11-17): engines.py FTSCAN-231 INF-SCAN-2638 INF-SCAN-2057 STG009 B603; handler.py FTSC-SCAN-089 B105 EXA002 EXA006; view.py WEB-FLASK-004 FINE-043 LO002. 🎯 Fix: 91 % 💥 Break: 4 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 87 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
af3555e88b
commit
621dc7536f
23 files changed
+1021
-34
No files matched your search
@@ -472,7 +472,7 @@ The global install also runs the Agent Orchestrator, a local review page in whic
|
|||||||
|
|
||||||
Stream → Radio (`#stream/radio`) is the hub's radio interface. Its station list shows one line per station, the full name in the tooltip, with its state and a play or stop button; when the browser blocks autoplay, the stream fails or the CSP refuses its origin, the row and a toast say so, and one click starts the station. New stations play daily around the clock. While the hub reads a message aloud, the speaking agent pulses there and in the Orbit and Chord views, under the caption "<Agent> speaking" with the message's first line; under `prefers-reduced-motion` the ring stays still. The speech bubble icon in the header (a hub setting, kept across reloads) puts a bubble at each speaking agent in the Agents graph, 3D, Hierarchy, Radio and Stream views, or in a caption bar at the bottom when the view does not show that agent: the agent being read gets the largest bubble and its words appear in time with the audio, waiting messages show a smaller `…` bubble per agent, and without speech output the same rows run at 180 words a minute, at least 1.5 s each. The composer sends on all seven channels: post and call to one agent, newsletter, broadcast, pan-pan, security and mayday to all. "Record" records with MediaRecorder; the hub transcribes the recording with whisper.cpp off the request thread (at most 120 s of audio, a 120 s timeout, four at a time), keeps it for replay in `~/.local/state/kvb-orchestrator/voice` (the newest 50) and puts the transcript into the field to edit; the message goes out as text, with the recording's host path and sha256 only when "Attach recording" is ticked. The hub transcribes at most six recordings a minute and 600 s of audio an hour. Every operator message is passkey-signed, and the hub verifies the signature against the pinned keys, each once, before it relays; `operator_message(id, text, to)` answers `match` only for the signed text and recipient; for a denial the signature covers the recipient the inbox resolved at signing, and the answer's text is only the signed reason, never the agent's own words the radio row quotes. "Cancel mayday", Evening, Sunset, Sunrise and a settings save that adds a stream URL take the passkey the same way.
|
Stream → Radio (`#stream/radio`) is the hub's radio interface. Its station list shows one line per station, the full name in the tooltip, with its state and a play or stop button; when the browser blocks autoplay, the stream fails or the CSP refuses its origin, the row and a toast say so, and one click starts the station. New stations play daily around the clock. While the hub reads a message aloud, the speaking agent pulses there and in the Orbit and Chord views, under the caption "<Agent> speaking" with the message's first line; under `prefers-reduced-motion` the ring stays still. The speech bubble icon in the header (a hub setting, kept across reloads) puts a bubble at each speaking agent in the Agents graph, 3D, Hierarchy, Radio and Stream views, or in a caption bar at the bottom when the view does not show that agent: the agent being read gets the largest bubble and its words appear in time with the audio, waiting messages show a smaller `…` bubble per agent, and without speech output the same rows run at 180 words a minute, at least 1.5 s each. The composer sends on all seven channels: post and call to one agent, newsletter, broadcast, pan-pan, security and mayday to all. "Record" records with MediaRecorder; the hub transcribes the recording with whisper.cpp off the request thread (at most 120 s of audio, a 120 s timeout, four at a time), keeps it for replay in `~/.local/state/kvb-orchestrator/voice` (the newest 50) and puts the transcript into the field to edit; the message goes out as text, with the recording's host path and sha256 only when "Attach recording" is ticked. The hub transcribes at most six recordings a minute and 600 s of audio an hour. Every operator message is passkey-signed, and the hub verifies the signature against the pinned keys, each once, before it relays; `operator_message(id, text, to)` answers `match` only for the signed text and recipient; for a denial the signature covers the recipient the inbox resolved at signing, and the answer's text is only the signed reason, never the agent's own words the radio row quotes. "Cancel mayday", Evening, Sunset, Sunrise and a settings save that adds a stream URL take the passkey the same way.
|
||||||
|
|
||||||
The hub page loads nothing from the network: its icons come from Bootstrap Icons 1.13.1 (`orchestrator/vendor/bootstrap-icons`, MIT), inlined per page as the symbols it uses, and its 3D views from `3d-force-graph` 1.80.1 and `three` 0.186.1 (`orchestrator/vendor`, MIT, served by the hub under `/vendor/`); the speech bubbles use Comic Neue 400 latin from `@fontsource/comic-neue` 5.3.0 (`orchestrator/vendor/comic-neue`, SIL OFL 1.1), which the page fetches and adds through the FontFace API, so the CSP needs no `font-src`. In the Artifacts Tree, "Delete" on a `merged-clean` branch without skip reason, or "Delete all merged", shows the dry-run lines and asks for the passkey signature; the hub then writes a job (repository, branch, worktree and tip per item, no command) into `~/.local/state/kvb-orchestrator/cleanup/jobs`. The `kvb-orchestrator-cleanup.path` user unit runs `client/cleanup.py` on the host, which verifies the signature against the pinned keys, runs `pkgmgr branch cleanup --json --local --branch <name>` as a dry run in the repository, then `--apply` only when that plan names exactly the signed branch as `merged-clean` at the signed tip and worktree, refuses everything else unchanged, writes each result to `cleanup/results` and rewrites the tree file. The buttons stay disabled while the tree file says `delete_ready: false`.
|
The hub page loads nothing from the network: its icons come from Bootstrap Icons 1.13.1 (`orchestrator/vendor/bootstrap-icons`, MIT), inlined per page as the symbols it uses, and its 3D views from `3d-force-graph` 1.80.1 and `three` 0.186.1 (`orchestrator/vendor`, MIT, served by the hub under `/vendor/`); the radio's Gibberlink mode encodes with `ggwave` 0.4.0 (`orchestrator/vendor/ggwave`, MIT, the npm build), which only the sandboxed encoder frame `/gibberlink` loads under its own CSP, since it needs the eval and WebAssembly the hub page never allows; the speech bubbles use Comic Neue 400 latin from `@fontsource/comic-neue` 5.3.0 (`orchestrator/vendor/comic-neue`, SIL OFL 1.1), which the page fetches and adds through the FontFace API, so the CSP needs no `font-src`. In the Artifacts Tree, "Delete" on a `merged-clean` branch without skip reason, or "Delete all merged", shows the dry-run lines and asks for the passkey signature; the hub then writes a job (repository, branch, worktree and tip per item, no command) into `~/.local/state/kvb-orchestrator/cleanup/jobs`. The `kvb-orchestrator-cleanup.path` user unit runs `client/cleanup.py` on the host, which verifies the signature against the pinned keys, runs `pkgmgr branch cleanup --json --local --branch <name>` as a dry run in the repository, then `--apply` only when that plan names exactly the signed branch as `merged-clean` at the signed tip and worktree, refuses everything else unchanged, writes each result to `cleanup/results` and rewrites the tree file. The buttons stay disabled while the tree file says `delete_ready: false`.
|
||||||
|
|
||||||
The Agents view "Hierarchy" draws the council's formal offices as a collapsible organigram: the Operator above the chair; in line under the chair one unit per dimension with its domain chairs (`<dimension>/<line>`) and one for the presidents (`work/<slug>`); beside the chair, on a side branch, the staff positions: organisers (`cluster/<slug>`) and single-segment offices such as `stack-architecture`. Each box shows the office and its holder, so an agent with several offices appears in each of them. A dashed line marks an additional superior, read live from the `kvb-org-rasci` register: an open task whose R (or worker) holds an office and that names another office holder A or C links that holder's first office to the agent's office for the task (the office or claimed work named like the task, else the agent's first office); the chair adds none, its solid line already runs there. On a narrow screen the chart scrolls inside its own frame, never the page. The chair in every graph is the holder of the `chair` office, not a fixed name. Appointing, handing over or recalling an office there asks for the passkey signature; the hub writes a job (office, signed holder, successor session, work; no command) into `~/.local/state/kvb-orchestrator/offices/jobs`, and the `kvb-orchestrator-offices.path` user unit runs `client/offices.py` on the host, which verifies the signature, refuses a council directory others can write, a link on the path or a holder that changed since the signature. For a takeover or recall it moves the office aside and removes it only while the claim there still names the signed holder; an appoint or takeover then runs a plain `council.py claim <office>` for the successor by argv. council.py itself has no flag that overrides a live holder. The same view holds the operator's agent order as a drag list with up and down buttons: `rasci.py agents order` stores it in `agent-order.json` beside the register, where it breaks ties of equal task priority and orders the chair's grants without touching any task's `--prio` pin.
|
The Agents view "Hierarchy" draws the council's formal offices as a collapsible organigram: the Operator above the chair; in line under the chair one unit per dimension with its domain chairs (`<dimension>/<line>`) and one for the presidents (`work/<slug>`); beside the chair, on a side branch, the staff positions: organisers (`cluster/<slug>`) and single-segment offices such as `stack-architecture`. Each box shows the office and its holder, so an agent with several offices appears in each of them. A dashed line marks an additional superior, read live from the `kvb-org-rasci` register: an open task whose R (or worker) holds an office and that names another office holder A or C links that holder's first office to the agent's office for the task (the office or claimed work named like the task, else the agent's first office); the chair adds none, its solid line already runs there. On a narrow screen the chart scrolls inside its own frame, never the page. The chair in every graph is the holder of the `chair` office, not a fixed name. Appointing, handing over or recalling an office there asks for the passkey signature; the hub writes a job (office, signed holder, successor session, work; no command) into `~/.local/state/kvb-orchestrator/offices/jobs`, and the `kvb-orchestrator-offices.path` user unit runs `client/offices.py` on the host, which verifies the signature, refuses a council directory others can write, a link on the path or a holder that changed since the signature. For a takeover or recall it moves the office aside and removes it only while the claim there still names the signed holder; an appoint or takeover then runs a plain `council.py claim <office>` for the successor by argv. council.py itself has no flag that overrides a live holder. The same view holds the operator's agent order as a drag list with up and down buttons: `rasci.py agents order` stores it in `agent-order.json` beside the register, where it breaks ties of equal task priority and orders the chair's grants without touching any task's `--prio` pin.
|
||||||
|
|
||||||
|
|||||||
@@ -45,6 +45,8 @@ HEARING_BUDGET = 5 * STT_SECONDS
|
|||||||
NOISE = re.compile(r"\[[^\]\n]{0,40}\]")
|
NOISE = re.compile(r"\[[^\]\n]{0,40}\]")
|
||||||
PLACEHOLDERS = frozenset({0, 0xFFFFFFFF})
|
PLACEHOLDERS = frozenset({0, 0xFFFFFFFF})
|
||||||
PITCH = (550, 850)
|
PITCH = (550, 850)
|
||||||
|
GIBBERLINK = ("AUDIBLE_NORMAL", "AUDIBLE_FAST", "AUDIBLE_FASTEST", "DT_FASTEST")
|
||||||
|
PANS = (-0.8, -0.4, 0.0, 0.4, 0.8)
|
||||||
|
|
||||||
|
|
||||||
def voice_models(folder: Path) -> list[Path]:
|
def voice_models(folder: Path) -> list[Path]:
|
||||||
@@ -134,6 +136,20 @@ def pitch_of(key: str) -> int:
|
|||||||
return low + slot(key, high - low + 1)
|
return low + slot(key, high - low + 1)
|
||||||
|
|
||||||
|
|
||||||
|
def sound_of(key: str) -> dict[str, str | float]:
|
||||||
|
"""Args:
|
||||||
|
key: the speaker's session id or directory key, as pitch_of takes it.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
protocol: the ggwave protocol of GIBBERLINK, the four of the vendored
|
||||||
|
ggwave 0.4.0 whose frames decode at every length up to 140 bytes;
|
||||||
|
pan: the stereo position of PANS. One slot picks both, so the
|
||||||
|
speakers of distinct slots get distinct pairs.
|
||||||
|
"""
|
||||||
|
picked = slot(key, len(GIBBERLINK) * len(PANS))
|
||||||
|
return {"protocol": GIBBERLINK[picked % len(GIBBERLINK)], "pan": PANS[picked // len(GIBBERLINK)]}
|
||||||
|
|
||||||
|
|
||||||
def wav_seconds(body: bytes, seconds: int) -> float:
|
def wav_seconds(body: bytes, seconds: int) -> float:
|
||||||
"""Args:
|
"""Args:
|
||||||
body: the recording.
|
body: the recording.
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ from .scores import scored
|
|||||||
|
|
||||||
BODY_LIMIT = 1 << 20
|
BODY_LIMIT = 1 << 20
|
||||||
UPLOAD_LIMIT = 50 << 20
|
UPLOAD_LIMIT = 50 << 20
|
||||||
PAGE_CSP = "sandbox allow-scripts"
|
PAGE_CSP = "sandbox allow-scripts; frame-ancestors 'none'"
|
||||||
SETTINGS_ROUTE = "/api/settings"
|
SETTINGS_ROUTE = "/api/settings"
|
||||||
TTS_ROUTE = "/api/tts"
|
TTS_ROUTE = "/api/tts"
|
||||||
WAV_TYPE = "audio/wav"
|
WAV_TYPE = "audio/wav"
|
||||||
@@ -50,6 +50,7 @@ TASKS_ROUTE = "/api/tasks"
|
|||||||
GATES_ROUTE = "/api/gates"
|
GATES_ROUTE = "/api/gates"
|
||||||
TOKEN_ROUTE = "/api/cleanup/token"
|
TOKEN_ROUTE = "/api/cleanup/token"
|
||||||
VIEW_ROUTE = "/api/view"
|
VIEW_ROUTE = "/api/view"
|
||||||
|
ENCODER_ROUTE = "/gibberlink"
|
||||||
VENDOR_ROUTE = re.compile(r"/vendor/([a-z0-9.-]{1,64})")
|
VENDOR_ROUTE = re.compile(r"/vendor/([a-z0-9.-]{1,64})")
|
||||||
SCRIPT_TYPE = "text/javascript; charset=utf-8"
|
SCRIPT_TYPE = "text/javascript; charset=utf-8"
|
||||||
FONT_TYPE = "font/woff2"
|
FONT_TYPE = "font/woff2"
|
||||||
@@ -57,6 +58,7 @@ VENDOR = {
|
|||||||
"3d-force-graph.min.js": ("3d-force-graph/3d-force-graph.min.js", SCRIPT_TYPE),
|
"3d-force-graph.min.js": ("3d-force-graph/3d-force-graph.min.js", SCRIPT_TYPE),
|
||||||
"three.module.js": ("three/three.module.js", SCRIPT_TYPE),
|
"three.module.js": ("three/three.module.js", SCRIPT_TYPE),
|
||||||
"three.core.js": ("three/three.core.js", SCRIPT_TYPE),
|
"three.core.js": ("three/three.core.js", SCRIPT_TYPE),
|
||||||
|
"ggwave.js": ("ggwave/ggwave.js", SCRIPT_TYPE),
|
||||||
"comic-neue.woff2": ("comic-neue/comic-neue-latin-400-normal.woff2", FONT_TYPE),
|
"comic-neue.woff2": ("comic-neue/comic-neue-latin-400-normal.woff2", FONT_TYPE),
|
||||||
}
|
}
|
||||||
VOICE_ROUTE = "/api/voice"
|
VOICE_ROUTE = "/api/voice"
|
||||||
@@ -107,6 +109,8 @@ class Handler(Exchange):
|
|||||||
self.send_text(HTTPStatus.FORBIDDEN, "forbidden host")
|
self.send_text(HTTPStatus.FORBIDDEN, "forbidden host")
|
||||||
elif path == "/":
|
elif path == "/":
|
||||||
self.index()
|
self.index()
|
||||||
|
elif path == ENCODER_ROUTE:
|
||||||
|
self.encoder()
|
||||||
elif firewall:
|
elif firewall:
|
||||||
self.answer(firewall, HTTPStatus.OK)
|
self.answer(firewall, HTTPStatus.OK)
|
||||||
elif diff:
|
elif diff:
|
||||||
@@ -331,6 +335,10 @@ class Handler(Exchange):
|
|||||||
headers = {"Content-Security-Policy": csp, "X-Frame-Options": "DENY"}
|
headers = {"Content-Security-Policy": csp, "X-Frame-Options": "DENY"}
|
||||||
self.send(HTTPStatus.OK, "text/html; charset=utf-8", page.encode("utf-8"), headers)
|
self.send(HTTPStatus.OK, "text/html; charset=utf-8", page.encode("utf-8"), headers)
|
||||||
|
|
||||||
|
def encoder(self) -> None:
|
||||||
|
page, csp = self.server.hub.encoder(secrets.token_urlsafe(18))
|
||||||
|
self.send(HTTPStatus.OK, "text/html; charset=utf-8", page.encode("utf-8"), {"Content-Security-Policy": csp})
|
||||||
|
|
||||||
def vendored(self, name: str, content_type: str) -> None:
|
def vendored(self, name: str, content_type: str) -> None:
|
||||||
headers = {"Content-Security-Policy": PLAIN_CSP, "Cache-Control": "private, max-age=86400"}
|
headers = {"Content-Security-Policy": PLAIN_CSP, "Cache-Control": "private, max-age=86400"}
|
||||||
self.attempt((self.server.hub.vendor / name).read_bytes, lambda data: self.send(HTTPStatus.OK, content_type, data, headers))
|
self.attempt((self.server.hub.vendor / name).read_bytes, lambda data: self.send(HTTPStatus.OK, content_type, data, headers))
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ from .council import (
|
|||||||
silence_of,
|
silence_of,
|
||||||
)
|
)
|
||||||
from .crons import queue_entries
|
from .crons import queue_entries
|
||||||
from .engines import pitch_of
|
from .engines import pitch_of, sound_of
|
||||||
from .errors import ToolError
|
from .errors import ToolError
|
||||||
from .events import KINDS, VIEWS
|
from .events import KINDS, VIEWS
|
||||||
from .fields import decode, instant, single
|
from .fields import decode, instant, single
|
||||||
@@ -47,9 +47,13 @@ RADIO_WINDOW = 86400
|
|||||||
JOBS_SHOWN = 20
|
JOBS_SHOWN = 20
|
||||||
ACTIVE = 900
|
ACTIVE = 900
|
||||||
INDEX_CSP = (
|
INDEX_CSP = (
|
||||||
"default-src 'none'; script-src 'nonce-{0}'; style-src 'nonce-{0}'; connect-src 'self'; media-src {1}; "
|
"default-src 'none'; script-src 'nonce-{0}'; style-src 'nonce-{0}'; connect-src 'self'; media-src {1}; frame-src 'self'; "
|
||||||
"base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
|
"base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
|
||||||
)
|
)
|
||||||
|
ENCODER_CSP = (
|
||||||
|
"sandbox allow-scripts; default-src 'none'; script-src 'nonce-{0}' 'unsafe-eval' 'wasm-unsafe-eval'; connect-src 'none'; "
|
||||||
|
"base-uri 'none'; form-action 'none'; frame-ancestors 'self'"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def badges(inbox: list[dict], claims: list[dict], jobs: list[dict], now: float) -> dict[str, int]:
|
def badges(inbox: list[dict], claims: list[dict], jobs: list[dict], now: float) -> dict[str, int]:
|
||||||
@@ -111,7 +115,7 @@ class View:
|
|||||||
called = [directory.at(key, row["ts"]) or name for key, name in zip(targets, row["to"], strict=True)]
|
called = [directory.at(key, row["ts"]) or name for key, name in zip(targets, row["to"], strict=True)]
|
||||||
speaker = directory.at(source, row["ts"]) or row["from"]
|
speaker = directory.at(source, row["ts"]) or row["from"]
|
||||||
word, rest = phrase_parts(row["class"], speaker, called, row["text"])
|
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}
|
spoken = {"speech": joined((word, rest)), "word": word, "rest": rest, "voice": self.speech.voice_of(source), "pitch": pitch_of(source), **sound_of(source), "speaker": speaker, "called": called}
|
||||||
read = read_of(inlined, row["ts"])
|
read = read_of(inlined, row["ts"])
|
||||||
radio.append({**row, "source": source, "targets": targets, "now": directory.now(source), **spoken, **read})
|
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)]
|
grant_rows = [{**grant, "target": directory.key(grant["to"], grant["ts"])} for grant in grants(history, (begin, end), claims, tasks)]
|
||||||
@@ -235,3 +239,15 @@ class View:
|
|||||||
state = self.state(now - RADIO_WINDOW, now, now, 0)
|
state = self.state(now - RADIO_WINDOW, now, now, 0)
|
||||||
page = self.templates.get_template("index.html.j2").render(nonce=nonce, state=state, view=self.view_store.get(), icons=self.icons, emoji_bases=sorted(signing.EMOJI_BASES))
|
page = self.templates.get_template("index.html.j2").render(nonce=nonce, state=state, view=self.view_store.get(), icons=self.icons, emoji_bases=sorted(signing.EMOJI_BASES))
|
||||||
return page, INDEX_CSP.format(nonce, " ".join(["'self'", *state["media"]]))
|
return page, INDEX_CSP.format(nonce, " ".join(["'self'", *state["media"]]))
|
||||||
|
|
||||||
|
def encoder(self, nonce: str) -> tuple[str, str]:
|
||||||
|
"""Args:
|
||||||
|
nonce: the response's script nonce.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The Gibberlink encoder page and its own CSP: the vendored ggwave
|
||||||
|
needs eval and WebAssembly, which the hub page never allows, so
|
||||||
|
the server sandboxes it into an opaque origin however it loads,
|
||||||
|
with no connection at all.
|
||||||
|
"""
|
||||||
|
return self.templates.get_template("gibberlink.html.j2").render(nonce=nonce), ENCODER_CSP.format(nonce)
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Gibberlink encoder</title>
|
||||||
|
<script nonce="{{ nonce }}" src="/vendor/ggwave.js"></script>
|
||||||
|
<script nonce="{{ nonce }}">
|
||||||
|
{% include "gibberlink.js" %}
|
||||||
|
{# ggwave fetches its embedded data: wasm first and decodes the bytes itself when that fails; rejecting at once keeps connect-src 'none' from logging a violation #}
|
||||||
|
window.fetch = () => Promise.reject(new TypeError("the Gibberlink encoder has no network"));
|
||||||
|
Gibberlink.serve(window, ggwave_factory({print: () => undefined, printErr: () => undefined}));
|
||||||
|
</script>
|
||||||
|
</head>
|
||||||
|
<body></body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
const Gibberlink = (() => {
|
||||||
|
"use strict";
|
||||||
|
const VOLUME = 50;
|
||||||
|
const PREFIX = "GGWAVE_PROTOCOL_";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {object} ggwave the loaded ggwave module.
|
||||||
|
* @param {object} request protocol, a ggwave protocol name without its prefix, and frames, the frame texts.
|
||||||
|
* @returns {object} rate and samples: the samples of each frame at ggwave's own output rate; the vendored build's frames at 44.1 kHz do not decode, so the page resamples instead.
|
||||||
|
*/
|
||||||
|
function encode(ggwave, request) {
|
||||||
|
const {protocol, frames} = request;
|
||||||
|
const key = `${PREFIX}${protocol}`;
|
||||||
|
if (typeof protocol !== "string" || !Object.hasOwn(ggwave.ProtocolId, key) || !Array.isArray(frames) || !frames.every((frame) => typeof frame === "string")) {
|
||||||
|
throw new Error("refused: the request needs a known protocol and text frames");
|
||||||
|
}
|
||||||
|
const parameters = ggwave.getDefaultParameters();
|
||||||
|
const instance = ggwave.init(parameters);
|
||||||
|
try {
|
||||||
|
return {rate: parameters.sampleRateOut, samples: frames.map((frame) => {
|
||||||
|
const wave = ggwave.encode(instance, frame, ggwave.ProtocolId[key], VOLUME);
|
||||||
|
return new Float32Array(wave.buffer.slice(wave.byteOffset, wave.byteOffset + wave.length));
|
||||||
|
})};
|
||||||
|
} finally {
|
||||||
|
ggwave.free(instance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Window} scope the encoder frame's window; it answers only its parent.
|
||||||
|
* @param {Promise<object>} ready the ggwave module once loaded.
|
||||||
|
*/
|
||||||
|
function serve(scope, ready) {
|
||||||
|
scope.addEventListener("message", (event) => {
|
||||||
|
if (event.source !== scope.parent || !event.data || typeof event.data.id !== "number") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const {id} = event.data;
|
||||||
|
ready.then((ggwave) => encode(ggwave, event.data)).then(
|
||||||
|
({rate, samples}) => scope.parent.postMessage({id, rate, samples}, "*", samples.map((part) => part.buffer)),
|
||||||
|
(error) => scope.parent.postMessage({id, error: String((error && error.message) || error)}, "*"),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {VOLUME, encode, serve};
|
||||||
|
})();
|
||||||
|
if (typeof module === "object" && module.exports) {
|
||||||
|
module.exports = Gibberlink;
|
||||||
|
}
|
||||||
@@ -631,6 +631,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
|||||||
|
|
||||||
{% include "page-morse.js" %}
|
{% include "page-morse.js" %}
|
||||||
|
|
||||||
|
{% include "page-gibberlink.js" %}
|
||||||
|
|
||||||
{% include "page-mic.js" %}
|
{% include "page-mic.js" %}
|
||||||
|
|
||||||
{% include "page-bubbles.js" %}
|
{% include "page-bubbles.js" %}
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
const GIBBER = {gap: 0.3, timeout: 15000, route: "/gibberlink"};
|
||||||
|
const gibber = {frame: null, ready: null, pending: new Map(), next: 0};
|
||||||
|
|
||||||
|
function gibberFrame() {
|
||||||
|
if (!gibber.frame) {
|
||||||
|
const frame = h("iframe", {class: "gibberlink-encoder", src: GIBBER.route, sandbox: "allow-scripts", title: "Gibberlink encoder", "aria-hidden": "true", tabindex: "-1", hidden: true});
|
||||||
|
gibber.ready = new Promise((resolve) => frame.addEventListener("load", resolve, {once: true}));
|
||||||
|
window.addEventListener("message", gibberAnswer);
|
||||||
|
document.body.append(frame);
|
||||||
|
gibber.frame = frame;
|
||||||
|
}
|
||||||
|
return gibber;
|
||||||
|
}
|
||||||
|
|
||||||
|
function gibberAnswer(event) {
|
||||||
|
const waiting = gibber.frame && event.source === gibber.frame.contentWindow && event.data ? gibber.pending.get(event.data.id) : null;
|
||||||
|
if (!waiting) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
gibber.pending.delete(event.data.id);
|
||||||
|
window.clearTimeout(waiting.timer);
|
||||||
|
const {rate, samples, error} = event.data;
|
||||||
|
if (error) {
|
||||||
|
waiting.reject(new Error(String(error)));
|
||||||
|
} else if (Number.isFinite(rate) && rate > 0 && Array.isArray(samples) && samples.every((part) => part instanceof Float32Array)) {
|
||||||
|
waiting.resolve({rate, samples});
|
||||||
|
} else {
|
||||||
|
waiting.reject(new Error("the Gibberlink encoder answered no samples"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {object} step a Gibberlink step with frames and protocol.
|
||||||
|
* @returns {Promise<object>} rate and samples: the samples of each frame from the sandboxed encoder frame, at its rate.
|
||||||
|
*/
|
||||||
|
function gibberEncode(step) {
|
||||||
|
const {frame, ready, pending} = gibberFrame();
|
||||||
|
gibber.next += 1;
|
||||||
|
const id = gibber.next;
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const timer = window.setTimeout(() => {
|
||||||
|
pending.delete(id);
|
||||||
|
reject(new Error("the Gibberlink encoder did not answer"));
|
||||||
|
}, GIBBER.timeout);
|
||||||
|
pending.set(id, {resolve, reject, timer});
|
||||||
|
ready.then(() => frame.contentWindow.postMessage({id, protocol: step.protocol, frames: step.frames}, "*"));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {AudioContext} sound the page's audio context.
|
||||||
|
* @param {object} item the row that sounds.
|
||||||
|
* @param {object} step its Gibberlink step: frames, protocol and pan.
|
||||||
|
* @returns {Promise<boolean>} whether the whole row sounded uncut: the frames one after another with a short gap, at the row's tone volume times the squelch, in the sender's stereo position.
|
||||||
|
*/
|
||||||
|
async function keyGibberlink(sound, item, step) {
|
||||||
|
const level = loudness(item.tone);
|
||||||
|
if (level <= 0 || !step.frames.length) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const {rate, samples: parts} = await gibberEncode(step);
|
||||||
|
if (speech.item !== item) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!allows(rendered(item, item.at), "gibberlink")) {
|
||||||
|
item.cut = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const gap = Math.round(rate * GIBBER.gap);
|
||||||
|
const buffer = sound.createBuffer(1, parts.reduce((sum, part) => sum + part.length + gap, 0), rate);
|
||||||
|
const data = buffer.getChannelData(0);
|
||||||
|
parts.reduce((at, part) => {
|
||||||
|
data.set(part, at);
|
||||||
|
return at + part.length + gap;
|
||||||
|
}, 0);
|
||||||
|
const source = sound.createBufferSource();
|
||||||
|
const gain = sound.createGain();
|
||||||
|
const pan = sound.createStereoPanner();
|
||||||
|
gain.gain.value = level;
|
||||||
|
pan.pan.value = step.pan;
|
||||||
|
source.buffer = buffer;
|
||||||
|
source.connect(gain).connect(pan).connect(sound.destination);
|
||||||
|
voicePace(item, Infinity, buffer.duration);
|
||||||
|
const ended = sounded(item, source, buffer.duration);
|
||||||
|
source.start();
|
||||||
|
return ended.then(() => speech.item === item && !item.cut);
|
||||||
|
}
|
||||||
@@ -1,10 +1,16 @@
|
|||||||
const STATION_TONES = {playing: "ok", loading: "info", reload: "info", blocked: "warn", error: "bad", due: "teal", stopped: "neutral", idle: "neutral", off: "neutral"};
|
const STATION_TONES = {playing: "ok", loading: "info", reload: "info", blocked: "warn", error: "bad", due: "teal", stopped: "neutral", idle: "neutral", off: "neutral"};
|
||||||
const NOTE_ID = /^[0-9a-f]{16}$/;
|
const NOTE_ID = /^[0-9a-f]{16}$/;
|
||||||
const MODE_LABELS = {
|
const MODE_LABELS = {
|
||||||
auto: ["bi-volume-up", "Auto", "Auto: speech while the host CPU lies below the threshold, otherwise the noise burst"],
|
auto: ["bi-volume-up", "Auto", "Auto: speech while the host CPU lies below the threshold, otherwise the fallback picked under Read aloud"],
|
||||||
quiet: ["bi-soundwave", "Quiet", "Quiet: the noise burst only, never speech; MAYDAY, PAN-PAN and Sécurité still sound their procedure word"],
|
quiet: ["bi-soundwave", "Quiet", "Quiet: the fallback picked under Read aloud, 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"],
|
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"],
|
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"],
|
||||||
|
gibberlink: ["bi-robot", "Gibberlink", "Gibberlink: every message sent whole as ggwave data sound a machine can decode, in its sender's own protocol and stereo position; MAYDAY, PAN-PAN and Sécurité still sound their procedure word"],
|
||||||
|
};
|
||||||
|
const FALLBACK_LABELS = {
|
||||||
|
gibberlink: ["Gibberlink", "Where speech cannot play, send the rest as ggwave data sound"],
|
||||||
|
morse: ["Morse", "Where speech cannot play, key the whole message in Morse"],
|
||||||
|
burst: ["Hiss", "Where speech cannot play, play the short noise burst"],
|
||||||
};
|
};
|
||||||
const radioParts = {bars: [], devices: [], logs: [], speaks: []};
|
const radioParts = {bars: [], devices: [], logs: [], speaks: []};
|
||||||
const liveParts = (kind) => radioParts[kind].filter((part) => part.root.isConnected);
|
const liveParts = (kind) => radioParts[kind].filter((part) => part.root.isConnected);
|
||||||
@@ -89,7 +95,7 @@
|
|||||||
mode.textContent = MODE_LABELS[radioSet.mode][1];
|
mode.textContent = MODE_LABELS[radioSet.mode][1];
|
||||||
cpu.textContent = gate.cpu === null ? "CPU ?" : `CPU ${Math.round(gate.cpu)} %`;
|
cpu.textContent = gate.cpu === null ? "CPU ?" : `CPU ${Math.round(gate.cpu)} %`;
|
||||||
cpu.dataset.open = String(gate.open);
|
cpu.dataset.open = String(gate.open);
|
||||||
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"}`;
|
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 fallback"}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,10 +299,15 @@
|
|||||||
keepRadio({muted: radioSet.muted.includes(key) ? radioSet.muted.filter((name) => name !== key) : [...radioSet.muted, key]});
|
keepRadio({muted: radioSet.muted.includes(key) ? radioSet.muted.filter((name) => name !== key) : [...radioSet.muted, key]});
|
||||||
redrawFilters();
|
redrawFilters();
|
||||||
}, false));
|
}, false));
|
||||||
|
const fallbacks = RadioSet.FALLBACKS.map((id) => chip(FALLBACK_LABELS[id][0], radioSet.fallback === id, FALLBACK_LABELS[id][1], () => {
|
||||||
|
keepRadio({fallback: id});
|
||||||
|
redrawFilters();
|
||||||
|
}, false));
|
||||||
return h("div", {class: "radio-read", "aria-label": "Read aloud"},
|
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("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 fallback and the procedure words stand in.`),
|
||||||
h("div", {class: "chips", role: "group", "aria-label": "Classes"}, classes),
|
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,
|
||||||
|
h("div", {class: "chips radio-fallback", role: "group", "aria-label": "Fallback", title: "Fallback: what plays in Auto above the threshold and in Quiet, kept in this browser"}, h("span", {class: "chips-label"}, "Fallback"), fallbacks),
|
||||||
morseSpeed());
|
morseSpeed());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,11 +27,11 @@
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {object|undefined} step the step the radio set plans now at the index that plays.
|
* @param {object|undefined} step the step the radio set plans now at the index that plays.
|
||||||
* @param {string} kind word, speech or burst: what plays or is about to play there.
|
* @param {string} kind word, speech, or a fallback kind (gibberlink, morse, burst): what plays or is about to play there.
|
||||||
* @returns {boolean} whether that sound may play: the planned kind, or the burst standing in for a planned speech line.
|
* @returns {boolean} whether that sound may play: the planned kind, or a fallback standing in for a planned speech line.
|
||||||
*/
|
*/
|
||||||
function allows(step, kind) {
|
function allows(step, kind) {
|
||||||
return Boolean(step) && (step.kind === kind || (kind === "burst" && step.kind === "speech"));
|
return Boolean(step) && (step.kind === kind || (RadioSet.FALLBACKS.includes(kind) && step.kind === "speech"));
|
||||||
}
|
}
|
||||||
|
|
||||||
function speechFailed(lines) {
|
function speechFailed(lines) {
|
||||||
@@ -54,7 +54,7 @@
|
|||||||
function preempt() {
|
function preempt() {
|
||||||
const {item, source} = speech;
|
const {item, source} = speech;
|
||||||
const [first] = speech.pending;
|
const [first] = speech.pending;
|
||||||
if (item && source && item.playing === "morse" && first && Voice.rank(first) < Voice.rank(item)) {
|
if (item && source && RadioSet.KEYED.includes(item.playing) && first && Voice.rank(first) < Voice.rank(item)) {
|
||||||
speech.item = null;
|
speech.item = null;
|
||||||
speech.pending = Voice.enqueue(speech.pending, item, SPEECH_QUEUE);
|
speech.pending = Voice.enqueue(speech.pending, item, SPEECH_QUEUE);
|
||||||
source.stop();
|
source.stop();
|
||||||
@@ -224,8 +224,8 @@
|
|||||||
await burst(audio, item);
|
await burst(audio, item);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (step.kind === "morse") {
|
if (RadioSet.KEYED.includes(step.kind)) {
|
||||||
voiced = (await keyMorse(audio, item, step)) || voiced;
|
voiced = (await keyed(audio, item, step)) || voiced;
|
||||||
done -= Number(item.cut);
|
done -= Number(item.cut);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -244,11 +244,16 @@
|
|||||||
speechFailed([failed]);
|
speechFailed([failed]);
|
||||||
}
|
}
|
||||||
if (failed && step.kind === "speech" && speech.item === item && allows(stepOf(item, done), "burst")) {
|
if (failed && step.kind === "speech" && speech.item === item && allows(stepOf(item, done), "burst")) {
|
||||||
item.playing = "burst";
|
const stand = item.row ? RadioSet.standIn(item.row, radioSet) : {kind: "burst"};
|
||||||
await burst(audio, item);
|
item.playing = stand.kind;
|
||||||
|
await (stand.kind === "burst" ? burst(audio, item) : keyed(audio, item, stand));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function keyed(audio, item, step) {
|
||||||
|
return step.kind === "morse" ? keyMorse(audio, item, step) : keyGibberlink(audio, item, step);
|
||||||
|
}
|
||||||
|
|
||||||
async function pump() {
|
async function pump() {
|
||||||
if (speech.busy || !speech.pending.length) {
|
if (speech.busy || !speech.pending.length) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
const RadioSet = (() => {
|
const RadioSet = (() => {
|
||||||
"use strict";
|
"use strict";
|
||||||
const KEY = "kvb-orchestrator.radio";
|
const KEY = "kvb-orchestrator.radio";
|
||||||
const MODES = ["auto", "quiet", "silence", "morse"];
|
const MODES = ["auto", "quiet", "silence", "morse", "gibberlink"];
|
||||||
|
const FALLBACKS = ["gibberlink", "morse", "burst"];
|
||||||
|
const KEYED = ["morse", "gibberlink"];
|
||||||
|
const FRAME = {bytes: 140, prefix: 8, key: 64};
|
||||||
const TONES = ["mayday", "review", "direct", "radio"];
|
const TONES = ["mayday", "review", "direct", "radio"];
|
||||||
const CLASSES = ["post", "call", "newsletter", "broadcast", "mayday", "pan-pan", "security"];
|
const CLASSES = ["post", "call", "newsletter", "broadcast", "mayday", "pan-pan", "security"];
|
||||||
const TO_ALL = new Set(["newsletter", "broadcast", "mayday", "pan-pan", "security"]);
|
const TO_ALL = new Set(["newsletter", "broadcast", "mayday", "pan-pan", "security"]);
|
||||||
@@ -24,6 +27,7 @@ const RadioSet = (() => {
|
|||||||
};
|
};
|
||||||
const DEFAULTS = {
|
const DEFAULTS = {
|
||||||
mode: "auto",
|
mode: "auto",
|
||||||
|
fallback: "gibberlink",
|
||||||
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}},
|
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}},
|
||||||
squelch: 1,
|
squelch: 1,
|
||||||
classes: ["mayday", "pan-pan", "security"],
|
classes: ["mayday", "pan-pan", "security"],
|
||||||
@@ -61,6 +65,7 @@ const RadioSet = (() => {
|
|||||||
const muted = Array.isArray(raw.muted) ? raw.muted.filter((key) => typeof key === "string" && key && key.length <= TEXT_LIMIT) : [];
|
const muted = Array.isArray(raw.muted) ? raw.muted.filter((key) => typeof key === "string" && key && key.length <= TEXT_LIMIT) : [];
|
||||||
return {
|
return {
|
||||||
mode: MODES.includes(raw.mode) ? raw.mode : DEFAULTS.mode,
|
mode: MODES.includes(raw.mode) ? raw.mode : DEFAULTS.mode,
|
||||||
|
fallback: FALLBACKS.includes(raw.fallback) ? raw.fallback : DEFAULTS.fallback,
|
||||||
sounds: Object.fromEntries(TONES.map((name) => [name, tone(sounds[name], DEFAULTS.sounds[name])])),
|
sounds: Object.fromEntries(TONES.map((name) => [name, tone(sounds[name], DEFAULTS.sounds[name])])),
|
||||||
squelch: level(raw.squelch, DEFAULTS.squelch),
|
squelch: level(raw.squelch, DEFAULTS.squelch),
|
||||||
classes: CLASSES.filter((name) => name === "mayday" || classes.includes(name)),
|
classes: CLASSES.filter((name) => name === "mayday" || classes.includes(name)),
|
||||||
@@ -82,11 +87,74 @@ const RadioSet = (() => {
|
|||||||
return {kind: "morse", sign: called ? row.called.join(" ") : sign, joined, text: `DE ${row.speaker} ${row.text.replace(MARKS, " ")}`, pitch: row.pitch};
|
return {kind: "morse", sign: called ? row.called.join(" ") : sign, joined, text: `DE ${row.speaker} ${row.text.replace(MARKS, " ")}`, pitch: row.pitch};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const utf8 = (char) => {
|
||||||
|
const point = char.codePointAt(0);
|
||||||
|
return point < 0x80 ? 1 : point < 0x800 ? 2 : point < 0x10000 ? 3 : 4;
|
||||||
|
};
|
||||||
|
|
||||||
|
function fitting(chars, at, room) {
|
||||||
|
let end = at;
|
||||||
|
for (let left = room; end < chars.length && utf8(chars[end]) <= left; end += 1) {
|
||||||
|
left -= utf8(chars[end]);
|
||||||
|
}
|
||||||
|
return end;
|
||||||
|
}
|
||||||
|
|
||||||
|
function split(key, chars, count) {
|
||||||
|
const own = Array.from(key);
|
||||||
|
const full = own.slice(0, fitting(own, 0, FRAME.key)).join("");
|
||||||
|
const prefix = own.slice(0, FRAME.prefix).join("");
|
||||||
|
const out = [];
|
||||||
|
let at = 0;
|
||||||
|
do {
|
||||||
|
const head = `${out.length ? prefix : full} ${out.length + 1}/${count} `;
|
||||||
|
const end = fitting(chars, at, FRAME.bytes - Array.from(head).reduce((sum, char) => sum + utf8(char), 0));
|
||||||
|
out.push(head + chars.slice(at, end).join(""));
|
||||||
|
at = end;
|
||||||
|
} while (at < chars.length);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {object} row a radio row of the state with word, rest, voice and the Morse fields.
|
* @param {string} key the sender's session key, the row's source; its first 64 bytes head frame 1.
|
||||||
|
* @param {string} text the message without the hub's mark.
|
||||||
|
* @returns {Array<string>} the frames of at most 140 UTF-8 bytes, each split between characters: frame 1 the key, `1/m` and text, every later frame the key's first 8 characters, `n/m` and text.
|
||||||
|
*/
|
||||||
|
function frames(key, text) {
|
||||||
|
const chars = Array.from(text);
|
||||||
|
for (let count = 1; ;) {
|
||||||
|
const out = split(key, chars, count);
|
||||||
|
if (out.length === count) {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
count = out.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {object} row a radio row with source, text, protocol and pan.
|
||||||
|
* @returns {object} the whole row as kind "gibberlink": its frames, the sender's ggwave protocol and its stereo position.
|
||||||
|
*/
|
||||||
|
function gibberlink(row) {
|
||||||
|
return {kind: "gibberlink", frames: frames(row.source, row.text.replace(MARKS, "").trim()), protocol: row.protocol, pan: row.pan};
|
||||||
|
}
|
||||||
|
|
||||||
|
const STAND_INS = {gibberlink, morse, burst: () => ({kind: "burst"})};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {object} row a radio row of the state.
|
||||||
|
* @param {object} set the radio set.
|
||||||
|
* @returns {object} the step its fallback pick plays where speech cannot: Gibberlink frames, Morse keying or the burst.
|
||||||
|
*/
|
||||||
|
function standIn(row, set) {
|
||||||
|
return STAND_INS[set.fallback](row);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {object} row a radio row of the state with word, rest, voice, the Morse and the Gibberlink fields.
|
||||||
* @param {object} set the radio set.
|
* @param {object} set the radio set.
|
||||||
* @param {Object<string, boolean>} live tts and open: whether the hub speaks at all and whether its CPU gate is open.
|
* @param {Object<string, boolean>} 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: 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.
|
* @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 in Gibberlink the frames of the whole row, in Auto below the threshold the spoken rest, else the fallback pick, nothing more in Silence.
|
||||||
*/
|
*/
|
||||||
function plan(row, set, live) {
|
function plan(row, set, live) {
|
||||||
if (!picked(row, set)) {
|
if (!picked(row, set)) {
|
||||||
@@ -99,8 +167,11 @@ const RadioSet = (() => {
|
|||||||
if (set.mode === "silence") {
|
if (set.mode === "silence") {
|
||||||
return word;
|
return word;
|
||||||
}
|
}
|
||||||
|
if (set.mode === "gibberlink") {
|
||||||
|
return [...word, gibberlink(row)];
|
||||||
|
}
|
||||||
const spoken = set.mode === "auto" && live.tts && live.open && row.voice && row.rest;
|
const spoken = set.mode === "auto" && live.tts && live.open && row.voice && row.rest;
|
||||||
return [...word, spoken ? {kind: "speech", text: row.rest} : {kind: "burst"}];
|
return [...word, spoken ? {kind: "speech", text: row.rest} : standIn(row, set)];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -201,7 +272,7 @@ const RadioSet = (() => {
|
|||||||
return {...entry, chips: Object.fromEntries(CHIPS.map((name) => [name, ""])), q: ""};
|
return {...entry, chips: Object.fromEntries(CHIPS.map((name) => [name, ""])), q: ""};
|
||||||
}
|
}
|
||||||
|
|
||||||
return {KEY, MODES, TONES, CLASSES, TABS, CHIPS, DEFAULTS, GATE, PROSIGNS, valid, picked, plan, burst, gateLabel, toAll, ledgerOf, logRows, counts, choices, cleared};
|
return {KEY, MODES, FALLBACKS, KEYED, FRAME, TONES, CLASSES, TABS, CHIPS, DEFAULTS, GATE, PROSIGNS, valid, picked, frames, standIn, plan, burst, gateLabel, toAll, ledgerOf, logRows, counts, choices, cleared};
|
||||||
})();
|
})();
|
||||||
if (typeof module === "object" && module.exports) {
|
if (typeof module === "object" && module.exports) {
|
||||||
module.exports = RadioSet;
|
module.exports = RadioSet;
|
||||||
|
|||||||
@@ -112,6 +112,7 @@ body.fit .spot-host { flex: none; }
|
|||||||
.knob-test { grid-column: 5; }
|
.knob-test { grid-column: 5; }
|
||||||
.radio-read { display: grid; gap: var(--sp-2); }
|
.radio-read { display: grid; gap: var(--sp-2); }
|
||||||
.radio-read .chips { margin-bottom: 0; }
|
.radio-read .chips { margin-bottom: 0; }
|
||||||
|
.radio-fallback .chips-label { color: var(--muted); font-size: var(--fs-sm); }
|
||||||
.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 { 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-speed .knob { flex: 1 1 8rem; width: auto; }
|
||||||
.morse-rate { font-family: var(--mono); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
.morse-rate { font-family: var(--mono); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||||
|
|||||||
Vendored
+21
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2020 Georgi Gerganov
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
Vendored
+21
@@ -0,0 +1,21 @@
|
|||||||
|
|
||||||
|
var ggwave_factory = (() => {
|
||||||
|
var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;
|
||||||
|
if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename;
|
||||||
|
return (
|
||||||
|
function(ggwave_factory) {
|
||||||
|
ggwave_factory = ggwave_factory || {};
|
||||||
|
|
||||||
|
var Module=typeof ggwave_factory!=="undefined"?ggwave_factory:{};var objAssign=Object.assign;var readyPromiseResolve,readyPromiseReject;Module["ready"]=new Promise(function(resolve,reject){readyPromiseResolve=resolve;readyPromiseReject=reject});var moduleOverrides=objAssign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var ENVIRONMENT_IS_WEB=typeof window==="object";var ENVIRONMENT_IS_WORKER=typeof importScripts==="function";var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var read_,readAsync,readBinary,setWindowTitle;function logExceptionOnExit(e){if(e instanceof ExitStatus)return;let toLog=e;err("exiting due to exception: "+toLog)}var fs;var nodePath;var requireNodeFS;if(ENVIRONMENT_IS_NODE){if(ENVIRONMENT_IS_WORKER){scriptDirectory=require("path").dirname(scriptDirectory)+"/"}else{scriptDirectory=__dirname+"/"}requireNodeFS=(()=>{if(!nodePath){fs=require("fs");nodePath=require("path")}});read_=function shell_read(filename,binary){var ret=tryParseAsDataURI(filename);if(ret){return binary?ret:ret.toString()}requireNodeFS();filename=nodePath["normalize"](filename);return fs.readFileSync(filename,binary?null:"utf8")};readBinary=(filename=>{var ret=read_(filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}return ret});readAsync=((filename,onload,onerror)=>{var ret=tryParseAsDataURI(filename);if(ret){onload(ret)}requireNodeFS();filename=nodePath["normalize"](filename);fs.readFile(filename,function(err,data){if(err)onerror(err);else onload(data.buffer)})});if(process["argv"].length>1){thisProgram=process["argv"][1].replace(/\\/g,"/")}arguments_=process["argv"].slice(2);process["on"]("uncaughtException",function(ex){if(!(ex instanceof ExitStatus)){throw ex}});process["on"]("unhandledRejection",function(reason){throw reason});quit_=((status,toThrow)=>{if(keepRuntimeAlive()){process["exitCode"]=status;throw toThrow}logExceptionOnExit(toThrow);process["exit"](status)});Module["inspect"]=function(){return"[Emscripten Module object]"}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!=="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptDir){scriptDirectory=_scriptDir}if(scriptDirectory.indexOf("blob:")!==0){scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}else{scriptDirectory=""}{read_=(url=>{try{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText}catch(err){var data=tryParseAsDataURI(url);if(data){return intArrayToString(data)}throw err}});if(ENVIRONMENT_IS_WORKER){readBinary=(url=>{try{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}catch(err){var data=tryParseAsDataURI(url);if(data){return data}throw err}})}readAsync=((url,onload,onerror)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=(()=>{if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response);return}var data=tryParseAsDataURI(url);if(data){onload(data.buffer);return}onerror()});xhr.onerror=onerror;xhr.send(null)})}setWindowTitle=(title=>document.title=title)}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.warn.bind(console);objAssign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var tempRet0=0;var setTempRet0=value=>{tempRet0=value};var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var noExitRuntime=Module["noExitRuntime"]||true;if(typeof WebAssembly!=="object"){abort("no native wasm support detected")}var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(text)}}var UTF8Decoder=typeof TextDecoder!=="undefined"?new TextDecoder("utf8"):undefined;function UTF8ArrayToString(heap,idx,maxBytesToRead){var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heap[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heap.subarray&&UTF8Decoder){return UTF8Decoder.decode(heap.subarray(idx,endPtr))}else{var str="";while(idx<endPtr){var u0=heap[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heap[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heap[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heap[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}}return str}function UTF8ToString(ptr,maxBytesToRead){return ptrLine truncated
|
||||||
|
|
||||||
|
|
||||||
|
return ggwave_factory.ready
|
||||||
|
}
|
||||||
|
);
|
||||||
|
})();
|
||||||
|
if (typeof exports === 'object' && typeof module === 'object')
|
||||||
|
module.exports = ggwave_factory;
|
||||||
|
else if (typeof define === 'function' && define['amd'])
|
||||||
|
define([], function() { return ggwave_factory; });
|
||||||
|
else if (typeof exports === 'object')
|
||||||
|
exports["ggwave_factory"] = ggwave_factory;
|
||||||
@@ -142,6 +142,8 @@ FACE = """(async () => {@HELPERS@@RADIO@
|
|||||||
gear.click();
|
gear.click();
|
||||||
await sleep(200);
|
await sleep(200);
|
||||||
const groups =Object.fromEntries(all("#radio-gear .chips", spot).map((group) => [group.getAttribute("aria-label"), all(".chip", group).map((chipNode) => [text(chipNode), chipNode.getAttribute("aria-pressed"), chipNode.disabled])]));
|
const groups =Object.fromEntries(all("#radio-gear .chips", spot).map((group) => [group.getAttribute("aria-label"), all(".chip", group).map((chipNode) => [text(chipNode), chipNode.getAttribute("aria-pressed"), chipNode.disabled])]));
|
||||||
|
all('#radio-gear .chips[aria-label="Fallback"] .chip', spot).find((chipNode) => text(chipNode) === "Hiss").click();
|
||||||
|
await sleep(150);
|
||||||
const stationsHead = text(spot.querySelector(".radio-station .group-title"));
|
const stationsHead = text(spot.querySelector(".radio-station .group-title"));
|
||||||
const ptt = spot.querySelector('form.composer button[type="submit"]');
|
const ptt = spot.querySelector('form.composer button[type="submit"]');
|
||||||
const pageFits = fits();
|
const pageFits = fits();
|
||||||
|
|||||||
@@ -0,0 +1,239 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
HERE = Path(__file__).resolve().parent
|
||||||
|
sys.path[:0] = [str(HERE.parent), str(HERE)]
|
||||||
|
|
||||||
|
import hub_e2e_kit as base
|
||||||
|
from hub_case import HubCase
|
||||||
|
from hub_support import HUB, iso
|
||||||
|
from kvb_orchestrator import engines
|
||||||
|
from radio_set_kit import CUES, OUT, SPY, WORD, probe
|
||||||
|
|
||||||
|
GGWAVE = HUB / "vendor" / "ggwave" / "ggwave.js"
|
||||||
|
SPOKEN = "Disk at ninety percent"
|
||||||
|
GIBBER_SPY = """() => {
|
||||||
|
(@SPY@)();
|
||||||
|
const captured = window.e2eGibber = [];
|
||||||
|
const pans = window.e2ePans = [];
|
||||||
|
const encoded = (part) => {
|
||||||
|
const raw = new Uint8Array(part.buffer, part.byteOffset, part.byteLength);
|
||||||
|
let binary = "";
|
||||||
|
for (let at = 0; at < raw.length; at += 0x8000) {
|
||||||
|
binary += String.fromCharCode(...raw.subarray(at, at + 0x8000));
|
||||||
|
}
|
||||||
|
return btoa(binary);
|
||||||
|
};
|
||||||
|
window.addEventListener("message", (event) => {
|
||||||
|
if (event.data && Array.isArray(event.data.samples)) {
|
||||||
|
captured.push({rate: event.data.rate, frames: event.data.samples.map(encoded)});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const panner = AudioContext.prototype.createStereoPanner;
|
||||||
|
AudioContext.prototype.createStereoPanner = function panned() {
|
||||||
|
const node = panner.call(this);
|
||||||
|
pans.push(node);
|
||||||
|
return node;
|
||||||
|
};
|
||||||
|
}""".replace("@SPY@", SPY)
|
||||||
|
GIBBER_KIT = """
|
||||||
|
const gear = () => all(".spot-head button", spot).find((button) => name(button) === "Read aloud");
|
||||||
|
const fallbacks = () => all('#radio-gear .chips[aria-label="Fallback"] .chip', spot);
|
||||||
|
const kept = () => JSON.parse(localStorage.getItem("kvb-orchestrator.radio") || "{}").fallback || null;
|
||||||
|
const opened = async (open) => {
|
||||||
|
if ((gear().getAttribute("aria-expanded") === "true") !== open) {
|
||||||
|
gear().click();
|
||||||
|
await sleep(200);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const sent = async (count) => {
|
||||||
|
await cue("alarm");
|
||||||
|
refreshNow();
|
||||||
|
return Boolean(await until(() => window.e2eGibber.length > count && lamp().dataset.lit === "true", 40000));
|
||||||
|
};
|
||||||
|
const stopped = async () => {
|
||||||
|
const stop = all("button", spot.querySelector(".radio-caption")).find((button) => name(button) === "Stop speaking");
|
||||||
|
if (stop) {
|
||||||
|
stop.click();
|
||||||
|
}
|
||||||
|
return Boolean(await until(() => lamp().dataset.lit === "false", 3000));
|
||||||
|
};
|
||||||
|
"""
|
||||||
|
GIBBER = """(async () => {@HELPERS@@RADIO@@KIT@
|
||||||
|
press("gibberlink");
|
||||||
|
await sleep(200);
|
||||||
|
const button = spot.querySelector('.radio-modes button[data-mode="gibberlink"]');
|
||||||
|
const mode = [pressed(), field("mode"), button.title, Boolean(button.querySelector("svg.bi"))];
|
||||||
|
await opened(true);
|
||||||
|
const before = fallbacks().map((chip) => [text(chip), chip.getAttribute("aria-pressed")]);
|
||||||
|
fallbacks().find((chip) => text(chip) === "Morse").click();
|
||||||
|
await sleep(150);
|
||||||
|
const morse = [fallbacks().map((chip) => chip.getAttribute("aria-pressed")), kept()];
|
||||||
|
fallbacks().find((chip) => text(chip) === "Gibberlink").click();
|
||||||
|
await sleep(150);
|
||||||
|
const back = [fallbacks().map((chip) => chip.getAttribute("aria-pressed")), kept()];
|
||||||
|
const label = text(spot.querySelector("#radio-gear .radio-fallback .chips-label"));
|
||||||
|
const gearFits = fits();
|
||||||
|
await opened(false);
|
||||||
|
const at = {captured: window.e2eGibber.length, pans: window.e2ePans.length};
|
||||||
|
const playing = await sent(at.captured);
|
||||||
|
await sleep(300);
|
||||||
|
return {
|
||||||
|
mode, before, morse, back, label, gearFits, playing, captured: window.e2eGibber.slice(at.captured), pans: window.e2ePans.slice(at.pans).map((node) => node.pan.value),
|
||||||
|
lamp: [text(lamp()), lamp().dataset.lit], caption: text(spot.querySelector(".radio-caption strong")), fits: fits(), frames: document.querySelectorAll("iframe.gibberlink-encoder").length,
|
||||||
|
};
|
||||||
|
})()"""
|
||||||
|
STOP = """(async () => {@HELPERS@@RADIO@@KIT@
|
||||||
|
const lit = lamp().dataset.lit;
|
||||||
|
return {lit, quiet: await stopped(), hidden: spot.querySelector(".radio-caption").hidden};
|
||||||
|
})()"""
|
||||||
|
QUIET = """(async () => {@HELPERS@@RADIO@@KIT@
|
||||||
|
press("quiet");
|
||||||
|
await sleep(200);
|
||||||
|
const at = {captured: window.e2eGibber.length, tts: audio().tts.length};
|
||||||
|
const played = await sent(at.captured);
|
||||||
|
const quiet = await stopped();
|
||||||
|
const tts = audio().tts.slice(at.tts).map((entry) => entry.body.text);
|
||||||
|
await opened(true);
|
||||||
|
return {played, quiet, tts, captured: window.e2eGibber.slice(at.captured), fits: fits(), violations: window.e2eViolations};
|
||||||
|
})()"""
|
||||||
|
DECODE = """
|
||||||
|
const fs = require("fs");
|
||||||
|
const factory = require(process.argv[1]);
|
||||||
|
const captures = JSON.parse(fs.readFileSync(process.argv[2], "utf8"));
|
||||||
|
factory({print: () => undefined, printErr: () => undefined}).then((ggwave) => {
|
||||||
|
console.log(JSON.stringify(captures.map(({rate, frames}) => {
|
||||||
|
const parameters = ggwave.getDefaultParameters();
|
||||||
|
parameters.sampleRateInp = rate;
|
||||||
|
const listener = ggwave.init(parameters);
|
||||||
|
const heard = [];
|
||||||
|
const gap = new Float32Array(Math.round(rate * 0.3));
|
||||||
|
for (const frame of frames) {
|
||||||
|
const raw = Buffer.from(frame, "base64");
|
||||||
|
const parts = [new Float32Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.length)), gap];
|
||||||
|
for (const samples of parts) {
|
||||||
|
for (let at = 0; at < samples.length; at += 1024) {
|
||||||
|
const got = ggwave.decode(listener, new Int8Array(samples.slice(at, at + 1024).buffer));
|
||||||
|
if (got && got.length) {
|
||||||
|
heard.push(Buffer.from(got.buffer, got.byteOffset, got.length).toString("utf8"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ggwave.free(listener);
|
||||||
|
return heard;
|
||||||
|
})));
|
||||||
|
});
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def kit(template: str) -> str:
|
||||||
|
return probe(template).replace("@KIT@", GIBBER_KIT)
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||||
|
class TestGibberlink(HubCase):
|
||||||
|
drive = base.OrchestratorE2ECase.drive
|
||||||
|
beside = base.OrchestratorE2ECase.beside
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
OUT.mkdir(parents=True, exist_ok=True)
|
||||||
|
now = time.time()
|
||||||
|
self.claim("s1", "Skills session")
|
||||||
|
self.write_council({"work/s2/claim.json": {"office": "work/s2", "session": "s2", "runtime": "claude", "name": "Stage", "since": iso(now - 7200), "beat": now - 60, "work": "x"}, "news.jsonl": ""})
|
||||||
|
hub = self.httpd.hub
|
||||||
|
hub.settings.put({**hub.settings.get(), "theme": "light"}, hub.settings.get())
|
||||||
|
self.host_cpu(10.0, 0)
|
||||||
|
self.beside(lambda: self.host_cpu(10.0, 0))
|
||||||
|
self.sent = 0
|
||||||
|
heard = hub.voice_notes.get
|
||||||
|
|
||||||
|
def get(note_id: str) -> dict:
|
||||||
|
if note_id != CUES["alarm"]:
|
||||||
|
return heard(note_id)
|
||||||
|
self.sent += 1
|
||||||
|
row = {"ts": time.time(), "from": "Stage", "to": [], "text": f"{SPOKEN} {self.sent}", "class": "security", "v": 2}
|
||||||
|
with (self.council / "news.jsonl").open("a", encoding="utf-8") as handle:
|
||||||
|
handle.write(self.jsonl([row]))
|
||||||
|
return {"id": note_id, "status": "done", "text": "", "error": "", "seconds": None, "created_ts": None}
|
||||||
|
|
||||||
|
patch = mock.patch.object(hub.voice_notes, "get", get)
|
||||||
|
patch.start()
|
||||||
|
self.addCleanup(patch.stop)
|
||||||
|
self.base = f"http://localhost:{self.port}/"
|
||||||
|
|
||||||
|
def steps(self, browser: str) -> list[dict]:
|
||||||
|
steps = []
|
||||||
|
for width, height in base.WIDTHS:
|
||||||
|
shot = str(OUT / f"{browser}-{width}-radio-gibberlink")
|
||||||
|
steps += [
|
||||||
|
{"width": width, "height": height, "url": f"{self.base}?{width}-gibberlink#stream", "wait": 1200, "probe": kit(GIBBER), "shot": f"{shot}-playing.png", "gesture": True},
|
||||||
|
{"width": width, "height": height, "url": None, "wait": 0, "probe": kit(STOP), "shot": None, "gesture": True},
|
||||||
|
{"width": width, "height": height, "url": None, "wait": 0, "probe": kit(QUIET), "shot": f"{shot}-fallback.png", "gesture": True},
|
||||||
|
]
|
||||||
|
return steps
|
||||||
|
|
||||||
|
def decoded(self, captures: list[dict]) -> list[list[str]]:
|
||||||
|
with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as handle:
|
||||||
|
json.dump(captures, handle)
|
||||||
|
self.addCleanup(os.unlink, handle.name)
|
||||||
|
done = subprocess.run(["node", "-e", DECODE, str(GGWAVE), handle.name], capture_output=True, text=True, timeout=600, check=True)
|
||||||
|
return json.loads(done.stdout)
|
||||||
|
|
||||||
|
def check(self, data: dict, browser: str) -> None:
|
||||||
|
results = iter(data["results"])
|
||||||
|
sound = engines.sound_of("s2")
|
||||||
|
for index, (width, _) in enumerate(base.WIDTHS):
|
||||||
|
played, stop, quiet = next(results), next(results), next(results)
|
||||||
|
with self.subTest(browser=browser, width=width, part="mode and fallback"):
|
||||||
|
self.assertNotIn("error", played, played)
|
||||||
|
self.assertEqual(played["mode"][:2], [["gibberlink"], "Gibberlink"], played["mode"])
|
||||||
|
self.assertIn("MAYDAY", played["mode"][2])
|
||||||
|
self.assertTrue(played["mode"][3])
|
||||||
|
self.assertEqual(played["before"], [["Gibberlink", "true"], ["Morse", "false"], ["Hiss", "false"]])
|
||||||
|
self.assertEqual((played["morse"], played["back"], played["label"]), ([["false", "true", "false"], "morse"], [["true", "false", "false"], "gibberlink"], "Fallback"))
|
||||||
|
self.assertEqual((played["gearFits"], played["fits"]), ({"page": True, "panel": True}, {"page": True, "panel": True}))
|
||||||
|
with self.subTest(browser=browser, width=width, part="frames"):
|
||||||
|
self.assertTrue(played["playing"], {key: value for key, value in played.items() if key != "captured"})
|
||||||
|
self.assertEqual(([capture["rate"] for capture in played["captured"]], played["frames"]), ([48000], 1))
|
||||||
|
self.assertEqual(len(played["pans"]), 1)
|
||||||
|
self.assertAlmostEqual(played["pans"][0], sound["pan"], places=5)
|
||||||
|
self.assertEqual(played["lamp"], ["RX", "true"])
|
||||||
|
self.assertEqual(played["caption"], "Stage speaking")
|
||||||
|
self.assertEqual(self.decoded(played["captured"]), [[f"s2 1/1 {SPOKEN} {2 * index + 1}"]])
|
||||||
|
with self.subTest(browser=browser, width=width, part="stop"):
|
||||||
|
self.assertEqual(stop, {"lit": "true", "quiet": True, "hidden": True})
|
||||||
|
with self.subTest(browser=browser, width=width, part="fallback in quiet"):
|
||||||
|
self.assertNotIn("error", quiet, quiet)
|
||||||
|
self.assertEqual((quiet["played"], quiet["quiet"], quiet["tts"]), (True, True, [WORD]))
|
||||||
|
self.assertEqual(self.decoded(quiet["captured"]), [[f"s2 1/1 {SPOKEN} {2 * index + 2}"]])
|
||||||
|
self.assertEqual(quiet["fits"], {"page": True, "panel": True})
|
||||||
|
self.assertEqual([seen for seen in quiet["violations"] if not seen.endswith("/favicon.ico")], [], "the hub page itself sees no CSP violation")
|
||||||
|
|
||||||
|
def test_chromium_sends_every_row_as_decodable_ggwave_frames_from_the_sandboxed_encoder_at_three_widths(self):
|
||||||
|
data = self.drive(self.steps("chromium"), None, init=GIBBER_SPY)
|
||||||
|
(OUT / "chromium-radio-gibberlink.json").write_text(json.dumps(data), encoding="utf-8")
|
||||||
|
self.assertEqual(data["errors"], [])
|
||||||
|
self.check(data, "chromium")
|
||||||
|
|
||||||
|
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
|
||||||
|
def test_firefox_sends_every_row_as_decodable_ggwave_frames_from_the_sandboxed_encoder_at_three_widths(self):
|
||||||
|
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=GIBBER_SPY)
|
||||||
|
(OUT / "firefox-radio-gibberlink.json").write_text(json.dumps(data), encoding="utf-8")
|
||||||
|
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
|
||||||
|
self.check(data, "firefox")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -136,7 +136,9 @@ class TestRadioSet(HubCase):
|
|||||||
self.assertEqual(face["display"]["mode"], "Auto")
|
self.assertEqual(face["display"]["mode"], "Auto")
|
||||||
self.assertEqual((face["display"]["cpu"], face["display"]["lamp"]), ("CPU 10 %", ["RX", "false"]), face)
|
self.assertEqual((face["display"]["cpu"], face["display"]["lamp"]), ("CPU 10 %", ["RX", "false"]), face)
|
||||||
self.assertTrue(face["display"]["cls"], face)
|
self.assertTrue(face["display"]["cls"], face)
|
||||||
self.assertEqual([mode_[:2] for mode_ in face["modes"]], [["Auto", "true"], ["Quiet", "false"], ["Silence", "false"], ["Morse", "false"]])
|
self.assertEqual([mode_[:2] for mode_ in face["modes"]], [["Auto", "true"], ["Quiet", "false"], ["Silence", "false"], ["Morse", "false"], ["Gibberlink", "false"]])
|
||||||
|
hiss = "false" if index == 0 else "true"
|
||||||
|
self.assertEqual(face["groups"]["Fallback"], [["Gibberlink", "true" if index == 0 else "false", False], ["Morse", "false", False], ["Hiss", hiss, False]])
|
||||||
self.assertTrue(all(mode_[2] and mode_[3] for mode_ in face["modes"]), face["modes"])
|
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([knob[0] for knob in face["knobs"]], ["MAYDAY / PAN-PAN", "Reviews, asks, decisions", "Post and calls to you", "All radio", "Squelch", "Threshold"])
|
||||||
shown = "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]])
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ VENDORED = {
|
|||||||
"3d-force-graph/3d-force-graph.min.js": ("13088340aad408156064fd120c3bc3a47c93a3cc45b8f132d6284b20e2223be9", "Copyright (c) 2017 Vasco Asturiano"),
|
"3d-force-graph/3d-force-graph.min.js": ("13088340aad408156064fd120c3bc3a47c93a3cc45b8f132d6284b20e2223be9", "Copyright (c) 2017 Vasco Asturiano"),
|
||||||
"three/three.module.js": ("9052042d676cb0fdc1ddfefe193053f34b7ac0513a616fdac4535d49987812ea", "Copyright © 2010-2026 three.js authors"),
|
"three/three.module.js": ("9052042d676cb0fdc1ddfefe193053f34b7ac0513a616fdac4535d49987812ea", "Copyright © 2010-2026 three.js authors"),
|
||||||
"three/three.core.js": ("9edde002b066a9a05676a6127f67735b62baf399bdea529f2f7e31657da769e6", "Copyright © 2010-2026 three.js authors"),
|
"three/three.core.js": ("9edde002b066a9a05676a6127f67735b62baf399bdea529f2f7e31657da769e6", "Copyright © 2010-2026 three.js authors"),
|
||||||
|
"ggwave/ggwave.js": ("f3792b5c185345a35a935ca68a5064b97f979d13fbba0062ff16f6b3b31a6113", "Copyright (c) 2020 Georgi Gerganov"),
|
||||||
}
|
}
|
||||||
VERSIONS = {"3d-force-graph/3d-force-graph.min.js": "Version 1.80.1", "three/three.core.js": "REVISION = '186'"}
|
VERSIONS = {"3d-force-graph/3d-force-graph.min.js": "Version 1.80.1", "three/three.core.js": "REVISION = '186'"}
|
||||||
|
|
||||||
|
|||||||
@@ -144,7 +144,7 @@ async function failed(bubbles, item, cancel) {
|
|||||||
};
|
};
|
||||||
vm.runInNewContext(`${code}\\nsay(item);`, {
|
vm.runInNewContext(`${code}\\nsay(item);`, {
|
||||||
Bubbles, speech, fetch, item, Date, settings: {bubbles}, SPEECH_QUEUE: 9, SPEECH_QUIET: 0, radioSet: {},
|
Bubbles, speech, fetch, item, Date, settings: {bubbles}, SPEECH_QUEUE: 9, SPEECH_QUIET: 0, radioSet: {},
|
||||||
Voice: {enqueue: (pending, next) => [...pending, next], loudness: () => 0}, RadioSet: {burst: (gain) => ({gain})},
|
Voice: {enqueue: (pending, next) => [...pending, next], loudness: () => 0}, RadioSet: {KEYED: ["morse", "gibberlink"], FALLBACKS: ["gibberlink", "morse", "burst"], burst: (gain) => ({gain})},
|
||||||
toast: (title, lines) => shown.push(`${title}: ${lines.join(" ")}`),
|
toast: (title, lines) => shown.push(`${title}: ${lines.join(" ")}`),
|
||||||
context: () => ({}), drawBubbles: draw, drawSpeaker: draw, wordsRead: () => 0,
|
context: () => ({}), drawBubbles: draw, drawSpeaker: draw, wordsRead: () => 0,
|
||||||
performance: {now: () => 1000}, window: {setTimeout: () => 7, clearTimeout: () => {}},
|
performance: {now: () => 1000}, window: {setTimeout: () => 7, clearTimeout: () => {}},
|
||||||
@@ -195,7 +195,7 @@ async function run(rule, items) {
|
|||||||
};
|
};
|
||||||
const sandbox = {
|
const sandbox = {
|
||||||
Bubbles, speech, Date, settings: {bubbles: true}, radioSet: {}, SPEECH_QUEUE: 9, SPEECH_QUIET: 0, SOUND_SLACK: 2,
|
Bubbles, speech, Date, settings: {bubbles: true}, radioSet: {}, SPEECH_QUEUE: 9, SPEECH_QUIET: 0, SOUND_SLACK: 2,
|
||||||
Voice: {enqueue: (pending, next) => [...pending, next], loudness: () => 1}, RadioSet: {burst: (gain) => ({gain, seconds: 0.6, frequency: 1800, q: 0.9})},
|
Voice: {enqueue: (pending, next) => [...pending, next], loudness: () => 1}, RadioSet: {KEYED: ["morse", "gibberlink"], FALLBACKS: ["gibberlink", "morse", "burst"], burst: (gain) => ({gain, seconds: 0.6, frequency: 1800, q: 0.9})},
|
||||||
toast: () => null, context: () => audio, drawBubbles: () => null, wordsRead: () => 0, saidOf: (item) => item.words || Bubbles.words(item.line), performance: {now: () => 1000},
|
toast: () => null, context: () => audio, drawBubbles: () => null, wordsRead: () => 0, saidOf: (item) => item.words || Bubbles.words(item.line), performance: {now: () => 1000},
|
||||||
duck: () => {
|
duck: () => {
|
||||||
if (rule === "transmit" && !ducked) {
|
if (rule === "transmit" && !ducked) {
|
||||||
@@ -343,7 +343,7 @@ async function transmitted(steps, cut, row = ROW, broken = "") {
|
|||||||
fetch: async (url, options) => (JSON.parse(options.body).text === "fails"
|
fetch: async (url, options) => (JSON.parse(options.body).text === "fails"
|
||||||
? {ok: false, status: 500, headers: {get: () => "text/plain"}, text: async () => "tts down"}
|
? {ok: false, status: 500, headers: {get: () => "text/plain"}, text: async () => "tts down"}
|
||||||
: {ok: true, status: 200, headers: {get: () => "audio/wav"}, arrayBuffer: async () => ({})}),
|
: {ok: true, status: 200, headers: {get: () => "audio/wav"}, arrayBuffer: async () => ({})}),
|
||||||
Voice: {enqueue: (pending, next) => [...pending, next], loudness: () => 1}, RadioSet: {burst: (gain) => ({gain, seconds: 0.6, frequency: 1800, q: 0.9})},
|
Voice: {enqueue: (pending, next) => [...pending, next], loudness: () => 1}, RadioSet: {KEYED: ["morse", "gibberlink"], FALLBACKS: ["gibberlink", "morse", "burst"], burst: (gain) => ({gain, seconds: 0.6, frequency: 1800, q: 0.9})},
|
||||||
};
|
};
|
||||||
vm.runInNewContext(`${code}
|
vm.runInNewContext(`${code}
|
||||||
function drawSpeaker() {
|
function drawSpeaker() {
|
||||||
|
|||||||
@@ -0,0 +1,419 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
from hub_case import HubCase
|
||||||
|
from hub_support import HUB
|
||||||
|
from kvb_orchestrator import council, engines, exchange, settings
|
||||||
|
from kvb_orchestrator.view import ENCODER_CSP
|
||||||
|
|
||||||
|
TEMPLATES = HUB / "templates"
|
||||||
|
RADIOSET = TEMPLATES / "radioset.js"
|
||||||
|
GIBBERLINK = TEMPLATES / "gibberlink.js"
|
||||||
|
MORSE = TEMPLATES / "morse.js"
|
||||||
|
VOICE = TEMPLATES / "voice.js"
|
||||||
|
PAGE_SPEECH = TEMPLATES / "page-speech.js"
|
||||||
|
PAGE_MORSE = TEMPLATES / "page-morse.js"
|
||||||
|
PAGE_GIBBERLINK = TEMPLATES / "page-gibberlink.js"
|
||||||
|
GGWAVE = HUB / "vendor" / "ggwave" / "ggwave.js"
|
||||||
|
KEY = "4f0c2a1e-1111-2222-3333-444455556666"
|
||||||
|
MARK = "[kvb-orchestrator msg 0123456789abcdef]"
|
||||||
|
WIDE = "ä€😀"
|
||||||
|
ALARMS = ("mayday", "pan-pan", "security")
|
||||||
|
SOUND = {"protocol": "AUDIBLE_FAST", "pan": -0.4}
|
||||||
|
FRAMES_PROBE = """
|
||||||
|
const R = require(process.argv[1]);
|
||||||
|
const input = JSON.parse(process.argv[2]);
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
split: input.texts.map(([key, text]) => R.frames(key, text)),
|
||||||
|
plans: input.plans.map(([row, set, live]) => R.plan(row, set, live)),
|
||||||
|
kept: input.sets.map((set) => R.valid(set).fallback),
|
||||||
|
constants: {modes: R.MODES, fallbacks: R.FALLBACKS, frame: R.FRAME, fallback: R.DEFAULTS.fallback, key: R.KEY},
|
||||||
|
}));
|
||||||
|
"""
|
||||||
|
PLAYING_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.slice(4, 7).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, pan, cls, text) => ({class: cls, source, from: source, to: [], called: [], speaker: "E", pitch: 600, protocol: "AUDIBLE_FAST", pan, voice: "v", word: "", rest: "x", text, ts: 1000});
|
||||||
|
function radio(plays, change) {
|
||||||
|
const run = {buffers: [], gains: [], pans: [], oscillators: [], encoded: []};
|
||||||
|
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 === undefined ? "now" : 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 made = (list) => () => {
|
||||||
|
const node = new Source();
|
||||||
|
list.push(node);
|
||||||
|
return node;
|
||||||
|
};
|
||||||
|
const param = () => ({value: 0, setValueAtTime: stub, linearRampToValueAtTime: stub, exponentialRampToValueAtTime: stub});
|
||||||
|
const audio = {
|
||||||
|
currentTime: 0, sampleRate: 8000, destination: {}, createBufferSource: made(run.buffers), createOscillator: made(run.oscillators),
|
||||||
|
createGain: () => {
|
||||||
|
const gain = param();
|
||||||
|
run.gains.push(gain);
|
||||||
|
return {gain, connect: (node) => node};
|
||||||
|
},
|
||||||
|
createStereoPanner: () => {
|
||||||
|
const pan = param();
|
||||||
|
run.pans.push(pan);
|
||||||
|
return {pan, connect: (node) => node};
|
||||||
|
},
|
||||||
|
createBuffer: (channels, frames, rate) => ({length: frames, duration: frames / rate, getChannelData: () => new Float32Array(frames)}),
|
||||||
|
};
|
||||||
|
const sandbox = {
|
||||||
|
RadioSet, Morse, Voice, radioSet: RadioSet.valid({mode: "gibberlink", classes: RadioSet.CLASSES, ...change}),
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
vm.runInNewContext(code, sandbox);
|
||||||
|
sandbox.gibberEncode = async (step) => {
|
||||||
|
run.encoded.push([step.pan, step.frames.length]);
|
||||||
|
return {rate: 48000, samples: step.frames.map((frame) => new Float32Array(frame.length * 10))};
|
||||||
|
};
|
||||||
|
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 long = "E ".repeat(200);
|
||||||
|
(async () => {
|
||||||
|
const whole = radio(true, {});
|
||||||
|
whole.say(row("s1", -0.4, "post", long));
|
||||||
|
await settle();
|
||||||
|
const quiet = radio(true, {squelch: 0.5});
|
||||||
|
quiet.say(row("s1", 0.4, "post", "E"));
|
||||||
|
await settle();
|
||||||
|
const mute = radio(true, {squelch: 0});
|
||||||
|
mute.say(row("s1", 0.4, "post", "E"));
|
||||||
|
await settle();
|
||||||
|
const stop = radio(false, {});
|
||||||
|
stop.say(row("s1", -0.4, "post", long));
|
||||||
|
await settle();
|
||||||
|
const playing = [stop.buffers.length, stop.sandbox.speech.source === stop.buffers[0]];
|
||||||
|
stop.sandbox.cancelSpeech();
|
||||||
|
await settle();
|
||||||
|
const urgent = radio(false, {});
|
||||||
|
urgent.say(row("s1", -0.8, "post", long));
|
||||||
|
await settle();
|
||||||
|
urgent.say(row("s2", 0.8, "mayday", "E"));
|
||||||
|
await settle();
|
||||||
|
const during = {buffers: urgent.buffers.map((node, index) => [urgent.pans[index].value, node.stops.includes("now")]), pending: urgent.sandbox.speech.pending.map((item) => item.cls)};
|
||||||
|
urgent.buffers[1].ended();
|
||||||
|
await settle();
|
||||||
|
const switched = radio(false, {});
|
||||||
|
switched.say(row("s1", -0.4, "post", long));
|
||||||
|
await settle();
|
||||||
|
switched.sandbox.keepRadio({mode: "morse"});
|
||||||
|
await settle();
|
||||||
|
console.log(JSON.stringify({
|
||||||
|
whole: {encoded: whole.encoded, length: whole.buffers.map((node) => node.buffer.length), pan: whole.pans.map((pan) => pan.value), gain: whole.gains.map((gain) => gain.value), idle: whole.idle()},
|
||||||
|
quiet: quiet.gains.map((gain) => gain.value),
|
||||||
|
mute: [mute.encoded.length, mute.buffers.length, mute.idle()],
|
||||||
|
stop: {playing, stops: stop.buffers[0].stops, idle: stop.idle()},
|
||||||
|
urgent: {during, encoded: urgent.encoded, after: urgent.buffers.map((node, index) => [urgent.pans[index].value, node.started])},
|
||||||
|
switched: {stops: switched.buffers[0].stops, oscillators: switched.oscillators.length},
|
||||||
|
}));
|
||||||
|
})();
|
||||||
|
"""
|
||||||
|
ANSWER_PROBE = """
|
||||||
|
const fs = require("fs");
|
||||||
|
const vm = require("vm");
|
||||||
|
const posted = [];
|
||||||
|
const listeners = [];
|
||||||
|
const frame = {contentWindow: {postMessage: (message) => posted.push(message)}, addEventListener: (type, loaded) => loaded()};
|
||||||
|
const sandbox = {
|
||||||
|
h: () => frame, document: {body: {append: () => undefined}},
|
||||||
|
window: {addEventListener: (type, heard) => listeners.push(heard), setTimeout: () => 0, clearTimeout: () => undefined},
|
||||||
|
};
|
||||||
|
vm.runInNewContext(fs.readFileSync(process.argv[1], "utf8"), sandbox);
|
||||||
|
const Floats = vm.runInContext("Float32Array", sandbox);
|
||||||
|
const settle = () => new Promise((resolve) => setImmediate(resolve));
|
||||||
|
const outcome = (promise) => promise.then((value) => ({rate: value.rate, parts: value.samples.length}), (error) => ({error: error.message}));
|
||||||
|
(async () => {
|
||||||
|
const good = outcome(sandbox.gibberEncode({protocol: "AUDIBLE_FAST", frames: ["a", "b"]}));
|
||||||
|
const bad = outcome(sandbox.gibberEncode({protocol: "AUDIBLE_FAST", frames: ["c"]}));
|
||||||
|
const failed = outcome(sandbox.gibberEncode({protocol: "MT_FAST", frames: ["d"]}));
|
||||||
|
await settle();
|
||||||
|
const answer = (source, data) => listeners.forEach((heard) => heard({source, data}));
|
||||||
|
answer({}, {id: 1, rate: 1, samples: []});
|
||||||
|
answer(frame.contentWindow, {id: 1, rate: 48000, samples: [new Floats(2), new Floats(3)]});
|
||||||
|
answer(frame.contentWindow, {id: 2, rate: "fast", samples: [[0.1]]});
|
||||||
|
answer(frame.contentWindow, {id: 3, error: "refused"});
|
||||||
|
console.log(JSON.stringify({posted, listeners: listeners.length, answers: await Promise.all([good, bad, failed])}));
|
||||||
|
})();
|
||||||
|
"""
|
||||||
|
DECODE_PROBE = """
|
||||||
|
const factory = require(process.argv[1]);
|
||||||
|
const Gibberlink = require(process.argv[2]);
|
||||||
|
const R = require(process.argv[3]);
|
||||||
|
const input = JSON.parse(process.argv[4]);
|
||||||
|
factory({print: () => undefined, printErr: () => undefined}).then((ggwave) => {
|
||||||
|
const frames = R.frames(input.key, input.text);
|
||||||
|
const heard = (parts, rate) => {
|
||||||
|
const gap = Math.round(rate * 0.3);
|
||||||
|
const joined = new Float32Array(parts.reduce((sum, part) => sum + part.length + gap, 0));
|
||||||
|
parts.reduce((at, part) => {
|
||||||
|
joined.set(part, at);
|
||||||
|
return at + part.length + gap;
|
||||||
|
}, 0);
|
||||||
|
const parameters = ggwave.getDefaultParameters();
|
||||||
|
parameters.sampleRateInp = rate;
|
||||||
|
const listener = ggwave.init(parameters);
|
||||||
|
const texts = [];
|
||||||
|
for (let at = 0; at < joined.length; at += 1024) {
|
||||||
|
const got = ggwave.decode(listener, new Int8Array(joined.slice(at, at + 1024).buffer));
|
||||||
|
if (got && got.length) {
|
||||||
|
texts.push(new TextDecoder().decode(new Uint8Array(got.buffer, got.byteOffset, got.length)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ggwave.free(listener);
|
||||||
|
return texts;
|
||||||
|
};
|
||||||
|
const decoded = {};
|
||||||
|
const rates = [];
|
||||||
|
for (const protocol of input.protocols) {
|
||||||
|
const {rate, samples} = Gibberlink.encode(ggwave, {protocol, frames});
|
||||||
|
rates.push(rate);
|
||||||
|
decoded[protocol] = heard(samples, rate);
|
||||||
|
}
|
||||||
|
const refused = input.wrong.map((request) => {
|
||||||
|
try {
|
||||||
|
Gibberlink.encode(ggwave, request);
|
||||||
|
return false;
|
||||||
|
} catch (error) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
console.log(JSON.stringify({frames, decoded, rates, refused, ids: Object.keys(ggwave.ProtocolId)}));
|
||||||
|
});
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def node(script: str, *args: str) -> dict:
|
||||||
|
return json.loads(subprocess.run(["node", "-e", script, *args], check=True, capture_output=True, text=True, timeout=600).stdout)
|
||||||
|
|
||||||
|
|
||||||
|
def row(cls: str, text: str) -> dict:
|
||||||
|
return {"class": cls, "source": KEY, "voice": "v1", "word": "W" if cls in ALARMS else "", "rest": "R", "text": text, "speaker": "Docs", "called": ["Docs"], "pitch": 600, **SOUND}
|
||||||
|
|
||||||
|
|
||||||
|
def header(index: int, count: int) -> str:
|
||||||
|
return f"{KEY if index == 1 else KEY[:8]} {index}/{count} "
|
||||||
|
|
||||||
|
|
||||||
|
def payloads(frames: list[str]) -> list[str]:
|
||||||
|
return [frame[len(header(index, len(frames))) :] for index, frame in enumerate(frames, start=1)]
|
||||||
|
|
||||||
|
|
||||||
|
class TestFrames(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
cls.long = "a" * 300
|
||||||
|
cls.edges = ["b" * offset + WIDE * 40 for offset in range(8)]
|
||||||
|
texts = [[KEY, cls.long], [KEY, ""], *[[KEY, text] for text in cls.edges]]
|
||||||
|
live = {"tts": True, "open": True}
|
||||||
|
cls.cases = [(mode, fallback, gate, name) for mode in ("gibberlink", "quiet", "auto", "silence") for fallback in ("gibberlink", "morse", "burst") for gate in (True, False) for name in council.CLASSES]
|
||||||
|
plans = [[row(name, f"hello {MARK}"), {"mode": mode, "fallback": fallback, "classes": list(council.CLASSES), "muted": []}, {**live, "open": gate}] for mode, fallback, gate, name in cls.cases]
|
||||||
|
plans.append([row("post", "hello"), {"mode": "gibberlink", "fallback": "burst", "classes": list(council.CLASSES), "muted": []}, {"tts": False, "open": False}])
|
||||||
|
sets = [{}, {"fallback": "morse"}, {"fallback": "burst"}, {"fallback": "hiss"}, {"fallback": 1}, {"mode": "gibberlink"}]
|
||||||
|
cls.data = node(FRAMES_PROBE, str(RADIOSET), json.dumps({"texts": texts, "plans": plans, "sets": sets}))
|
||||||
|
|
||||||
|
def test_a_300_byte_message_splits_into_frames_of_at_most_140_bytes_with_the_key_header_and_joins_back(self):
|
||||||
|
frames = self.data["split"][0]
|
||||||
|
self.assertGreaterEqual(len(frames), 3)
|
||||||
|
for index, frame in enumerate(frames, start=1):
|
||||||
|
with self.subTest(frame=index):
|
||||||
|
self.assertLessEqual(len(frame.encode("utf-8")), 140)
|
||||||
|
self.assertTrue(frame.startswith(header(index, len(frames))), frame)
|
||||||
|
self.assertEqual("".join(payloads(frames)), self.long)
|
||||||
|
self.assertEqual(self.data["split"][1], [f"{KEY} 1/1 "], "an empty text still sends its sender")
|
||||||
|
|
||||||
|
def test_umlauts_euro_and_emoji_at_every_frame_edge_split_between_characters(self):
|
||||||
|
for offset, frames in enumerate(self.data["split"][2:]):
|
||||||
|
with self.subTest(offset=offset):
|
||||||
|
sizes = [len(frame.encode("utf-8")) for frame in frames]
|
||||||
|
self.assertTrue(all(size <= 140 for size in sizes), sizes)
|
||||||
|
self.assertGreater(max(sizes), 136, "the frames fill the budget up to the last whole character")
|
||||||
|
self.assertEqual("".join(payloads(frames)), self.edges[offset])
|
||||||
|
|
||||||
|
def test_gibberlink_mode_gives_the_alarm_classes_their_word_then_the_whole_message_and_every_other_class_the_frames_only(self):
|
||||||
|
gibberlink = {"kind": "gibberlink", "frames": [f"{KEY} 1/1 hello"], **SOUND}
|
||||||
|
for case, plan in zip(self.cases, self.data["plans"], strict=False):
|
||||||
|
mode, _, _, name = case
|
||||||
|
if mode != "gibberlink":
|
||||||
|
continue
|
||||||
|
with self.subTest(case=case):
|
||||||
|
self.assertEqual(plan, [{"kind": "word", "text": "W"}, gibberlink] if name in ALARMS else [gibberlink])
|
||||||
|
self.assertEqual(self.data["plans"][-1], [gibberlink], "without the speech engine no procedure word is rendered")
|
||||||
|
|
||||||
|
def test_quiet_and_auto_with_the_gate_closed_play_the_fallback_pick_after_the_word(self):
|
||||||
|
standins = {"gibberlink": {"kind": "gibberlink", "frames": [f"{KEY} 1/1 hello"], **SOUND}, "burst": {"kind": "burst"}}
|
||||||
|
for case, plan in zip(self.cases, self.data["plans"], strict=False):
|
||||||
|
mode, fallback, gate, name = case
|
||||||
|
word = [{"kind": "word", "text": "W"}] if name in ALARMS else []
|
||||||
|
with self.subTest(case=case):
|
||||||
|
if mode == "silence":
|
||||||
|
self.assertEqual(plan, word)
|
||||||
|
elif mode == "auto" and gate:
|
||||||
|
self.assertEqual(plan, [*word, {"kind": "speech", "text": "R"}])
|
||||||
|
elif mode != "gibberlink" and fallback == "morse":
|
||||||
|
self.assertEqual((plan[:-1], plan[-1]["kind"], plan[-1]["text"]), (word, "morse", "DE Docs hello "))
|
||||||
|
elif mode != "gibberlink":
|
||||||
|
self.assertEqual(plan, [*word, standins[fallback]])
|
||||||
|
|
||||||
|
def test_the_fallback_pick_is_kept_per_browser_beside_the_mode_and_never_in_the_hub_settings(self):
|
||||||
|
self.assertEqual(self.data["kept"], ["gibberlink", "morse", "burst", "gibberlink", "gibberlink", "gibberlink"])
|
||||||
|
constants = self.data["constants"]
|
||||||
|
self.assertEqual((constants["modes"], constants["fallbacks"], constants["fallback"]), (["auto", "quiet", "silence", "morse", "gibberlink"], ["gibberlink", "morse", "burst"], "gibberlink"))
|
||||||
|
self.assertEqual((constants["frame"]["bytes"], constants["frame"]["prefix"], constants["key"]), (140, 8, "kvb-orchestrator.radio"))
|
||||||
|
self.assertNotIn("fallback", settings.SETTINGS)
|
||||||
|
self.assertNotIn("fallback", json.dumps(settings.SETTINGS))
|
||||||
|
|
||||||
|
|
||||||
|
class TestSpeakerSound(unittest.TestCase):
|
||||||
|
def test_every_speaker_gets_one_stable_protocol_and_stereo_position_from_its_slot(self):
|
||||||
|
keys = [f"s{number}" for number in range(200)]
|
||||||
|
sounds = [engines.sound_of(key) for key in keys]
|
||||||
|
self.assertEqual(sounds, [engines.sound_of(key) for key in keys])
|
||||||
|
self.assertTrue(all(sound["protocol"] in engines.GIBBERLINK and sound["pan"] in engines.PANS for sound in sounds))
|
||||||
|
self.assertEqual(len({(sound["protocol"], sound["pan"]) for sound in sounds}), len(engines.GIBBERLINK) * len(engines.PANS))
|
||||||
|
with mock.patch.object(engines, "slot", lambda key, count: count - 1):
|
||||||
|
self.assertEqual(engines.sound_of("s1"), {"protocol": engines.GIBBERLINK[-1], "pan": engines.PANS[-1]})
|
||||||
|
self.assertEqual(engines.sound_of("s1")["protocol"], engines.GIBBERLINK[engines.slot("s1", 20) % 4])
|
||||||
|
|
||||||
|
def test_speakers_in_distinct_slots_get_distinct_protocols_from_the_vendored_source(self):
|
||||||
|
picks = {}
|
||||||
|
for number in range(200):
|
||||||
|
picks.setdefault(engines.slot(f"s{number}", 20) % len(engines.GIBBERLINK), f"s{number}")
|
||||||
|
self.assertEqual(len({engines.sound_of(key)["protocol"] for key in picks.values()}), len(engines.GIBBERLINK))
|
||||||
|
self.assertEqual(engines.GIBBERLINK, ("AUDIBLE_NORMAL", "AUDIBLE_FAST", "AUDIBLE_FASTEST", "DT_FASTEST"))
|
||||||
|
|
||||||
|
|
||||||
|
class TestPlaying(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
cls.data = node(PLAYING_PROBE, str(RADIOSET), str(MORSE), str(VOICE), str(PAGE_SPEECH), str(PAGE_MORSE), str(PAGE_GIBBERLINK))
|
||||||
|
|
||||||
|
def test_the_frames_play_once_in_the_sender_position_at_the_tone_volume_times_the_squelch(self):
|
||||||
|
whole = self.data["whole"]
|
||||||
|
self.assertEqual(whole["encoded"], [[-0.4, 3]])
|
||||||
|
self.assertEqual((len(whole["length"]), whole["pan"], whole["gain"], whole["idle"]), (1, [-0.4], [0.5], True))
|
||||||
|
self.assertGreater(whole["length"][0], 399 * 10 + 3 * 48000 * 0.3 - 1, "every frame with a 0.3 second gap at the encoder's 48 kHz")
|
||||||
|
self.assertEqual(self.data["quiet"], [0.25])
|
||||||
|
self.assertEqual(self.data["mute"], [0, 0, True], "squelch 0 encodes and plays nothing")
|
||||||
|
|
||||||
|
def test_stop_ends_the_frames_at_once(self):
|
||||||
|
stop = self.data["stop"]
|
||||||
|
self.assertEqual((stop["playing"], stop["stops"], stop["idle"]), ([1, True], ["now"], True))
|
||||||
|
|
||||||
|
def test_a_mayday_cuts_a_post_whose_frames_play_and_the_post_sends_again_whole_after_it(self):
|
||||||
|
urgent = self.data["urgent"]
|
||||||
|
self.assertEqual(urgent["during"], {"buffers": [[-0.8, True], [0.8, False]], "pending": ["post"]})
|
||||||
|
self.assertEqual(urgent["encoded"], [[-0.8, 3], [0.8, 1], [-0.8, 3]])
|
||||||
|
self.assertEqual(urgent["after"][2], [-0.8, "now"])
|
||||||
|
|
||||||
|
def test_a_mode_change_cuts_the_frames_and_replans_the_row(self):
|
||||||
|
self.assertEqual(self.data["switched"], {"stops": ["now"], "oscillators": 1})
|
||||||
|
|
||||||
|
|
||||||
|
class TestEncoderAnswers(unittest.TestCase):
|
||||||
|
def test_the_page_takes_samples_only_from_its_own_encoder_frame_and_refuses_anything_else(self):
|
||||||
|
data = node(ANSWER_PROBE, str(PAGE_GIBBERLINK))
|
||||||
|
self.assertEqual(data["listeners"], 1, "one encoder frame, one listener, however often the radio encodes")
|
||||||
|
self.assertEqual(data["posted"], [{"id": 1, "protocol": "AUDIBLE_FAST", "frames": ["a", "b"]}, {"id": 2, "protocol": "AUDIBLE_FAST", "frames": ["c"]}, {"id": 3, "protocol": "MT_FAST", "frames": ["d"]}])
|
||||||
|
self.assertEqual(data["answers"], [{"rate": 48000, "parts": 2}, {"error": "the Gibberlink encoder answered no samples"}, {"error": "refused"}])
|
||||||
|
|
||||||
|
|
||||||
|
class TestEncoder(unittest.TestCase):
|
||||||
|
def test_every_protocol_decodes_back_to_the_frame_texts_and_wrong_requests_are_refused(self):
|
||||||
|
text = f"disk full on {WIDE} " + "rotate the keys " * 15
|
||||||
|
wrong = [{"protocol": "MT_FAST", "frames": ["x"]}, {"protocol": "values", "frames": ["x"]}, {"protocol": "AUDIBLE_FAST", "frames": [1]}, {"protocol": "AUDIBLE_FAST", "frames": "x"}, {"frames": ["x"]}]
|
||||||
|
data = node(DECODE_PROBE, str(GGWAVE), str(GIBBERLINK), str(RADIOSET), json.dumps({"key": KEY, "text": text, "protocols": engines.GIBBERLINK, "wrong": wrong}))
|
||||||
|
self.assertGreaterEqual(len(data["frames"]), 3)
|
||||||
|
self.assertEqual(list(data["decoded"]), list(engines.GIBBERLINK))
|
||||||
|
for name, heard in data["decoded"].items():
|
||||||
|
with self.subTest(protocol=name):
|
||||||
|
self.assertEqual(heard, data["frames"])
|
||||||
|
self.assertEqual((set(data["rates"]), data["refused"]), ({48000}, [True] * len(wrong)))
|
||||||
|
for name in engines.GIBBERLINK:
|
||||||
|
with self.subTest(protocol=name):
|
||||||
|
self.assertIn(f"GGWAVE_PROTOCOL_{name}", data["ids"])
|
||||||
|
|
||||||
|
|
||||||
|
class TestEncoderHttp(HubCase):
|
||||||
|
def test_the_encoder_page_carries_its_own_csp_and_the_hub_page_never_allows_eval(self):
|
||||||
|
status, headers, body = self.get("/gibberlink")
|
||||||
|
page = body.decode("utf-8")
|
||||||
|
nonces = set(re.findall(r'<script nonce="([^"]+)"', page))
|
||||||
|
self.assertEqual((status, headers["content-type"], len(nonces)), (200, "text/html; charset=utf-8", 1), page)
|
||||||
|
csp = headers["content-security-policy"]
|
||||||
|
self.assertEqual(csp, ENCODER_CSP.format(nonces.pop()))
|
||||||
|
self.assertIn("'unsafe-eval' 'wasm-unsafe-eval'", csp)
|
||||||
|
self.assertTrue(csp.startswith("sandbox allow-scripts;"), "the server keeps the encoder in an opaque origin even at top level")
|
||||||
|
self.assertIn("connect-src 'none'", csp)
|
||||||
|
self.assertIn('src="/vendor/ggwave.js"', page)
|
||||||
|
self.assertIn("Gibberlink.serve(window, ggwave_factory(", page)
|
||||||
|
self.assertLess(page.index("window.fetch = () => Promise.reject("), page.index("Gibberlink.serve("), "the frame asks for nothing before ggwave loads its wasm")
|
||||||
|
self.assertNotEqual(self.get("/gibberlink")[1]["content-security-policy"], csp, "every load gets a fresh nonce")
|
||||||
|
index = self.get("/")[1]["content-security-policy"]
|
||||||
|
self.assertNotIn("unsafe-eval", index)
|
||||||
|
self.assertIn("frame-src 'self'", index)
|
||||||
|
|
||||||
|
def test_the_vendor_route_serves_ggwave_under_the_plain_csp(self):
|
||||||
|
status, headers, body = self.get("/vendor/ggwave.js")
|
||||||
|
self.assertEqual((status, headers["content-type"], headers["content-security-policy"]), (200, "text/javascript; charset=utf-8", exchange.PLAIN_CSP))
|
||||||
|
self.assertEqual(body, GGWAVE.read_bytes())
|
||||||
|
|
||||||
|
def test_every_radio_row_carries_the_sender_protocol_and_stereo_position(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["protocol"], row["pan"]) for row in self.snapshot()["radio"]]
|
||||||
|
self.assertEqual(rows, [(key, *engines.sound_of(key).values()) for key in ("s1", "s2")])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -137,7 +137,7 @@ const ons = (run) => run.gains[0].filter(([kind, value]) => kind === "ramp" && v
|
|||||||
const switched = radio(false);
|
const switched = radio(false);
|
||||||
switched.say(row("s1", 640, "security", "E"));
|
switched.say(row("s1", 640, "security", "E"));
|
||||||
await settle();
|
await settle();
|
||||||
switched.sandbox.keepRadio({mode: "quiet"});
|
switched.sandbox.keepRadio({mode: "quiet", fallback: "burst"});
|
||||||
await settle();
|
await settle();
|
||||||
const urgent = radio(false);
|
const urgent = radio(false);
|
||||||
urgent.say(row("s1", 600, "post", "E ".repeat(200)));
|
urgent.say(row("s1", 600, "post", "E ".repeat(200)));
|
||||||
@@ -231,7 +231,7 @@ class TestMorseCode(unittest.TestCase):
|
|||||||
|
|
||||||
def test_morse_is_a_fourth_mode_and_the_threshold_labels_read_never_and_always_at_the_ends(self):
|
def test_morse_is_a_fourth_mode_and_the_threshold_labels_read_never_and_always_at_the_ends(self):
|
||||||
constants = self.data["constants"]
|
constants = self.data["constants"]
|
||||||
self.assertEqual((constants["modes"], constants["kept"]), (["auto", "quiet", "silence", "morse"], "morse"))
|
self.assertEqual((constants["modes"][:4], 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(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"])
|
self.assertEqual(self.data["gates"], ["never", "speak while CPU < 10 %", "speak while CPU < 50 %", "speak while CPU < 90 %", "always"])
|
||||||
|
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ class TestHubPage(HubCase):
|
|||||||
review_id = self.request("feat: csp", "")
|
review_id = self.request("feat: csp", "")
|
||||||
status, headers, _ = self.get(f"/reviews/{review_id}/page")
|
status, headers, _ = self.get(f"/reviews/{review_id}/page")
|
||||||
self.assertEqual(status, 200)
|
self.assertEqual(status, 200)
|
||||||
self.assertEqual(headers["content-security-policy"], "sandbox allow-scripts")
|
self.assertEqual(headers["content-security-policy"], "sandbox allow-scripts; frame-ancestors 'none'")
|
||||||
self.assertEqual(headers["x-content-type-options"], "nosniff")
|
self.assertEqual(headers["x-content-type-options"], "nosniff")
|
||||||
status, headers, body = self.get("/")
|
status, headers, body = self.get("/")
|
||||||
csp = headers["content-security-policy"]
|
csp = headers["content-security-policy"]
|
||||||
|
|||||||
@@ -119,7 +119,7 @@ const row = {class: "security", source: "s1", voice: "v1", word: "W", rest: "R",
|
|||||||
async function queued(flip) {
|
async function queued(flip) {
|
||||||
const heard = [];
|
const heard = [];
|
||||||
const sandbox = {
|
const sandbox = {
|
||||||
RadioSet, radioSet: RadioSet.valid({mode: "auto"}), state: {speech: {tts: true, gate: {open: true}}},
|
RadioSet, radioSet: RadioSet.valid({mode: "auto", fallback: "burst"}), state: {speech: {tts: true, gate: {open: true}}},
|
||||||
speech: {pending: [], busy: false, current: null, source: null, item: null, timer: 0}, settings: {bubbles: false}, SPEECH_QUEUE: 9,
|
speech: {pending: [], busy: false, current: null, source: null, item: null, timer: 0}, settings: {bubbles: false}, SPEECH_QUEUE: 9,
|
||||||
Voice: {enqueue: (pending, next) => [...pending, next]}, drawBubbles: stub, drawSpeaker: stub,
|
Voice: {enqueue: (pending, next) => [...pending, next]}, drawBubbles: stub, drawSpeaker: stub,
|
||||||
};
|
};
|
||||||
@@ -128,7 +128,7 @@ async function queued(flip) {
|
|||||||
sandbox.spoken = async (audio, item, step) => {
|
sandbox.spoken = async (audio, item, step) => {
|
||||||
heard.push(step.text);
|
heard.push(step.text);
|
||||||
if (heard.length === 1 && flip) {
|
if (heard.length === 1 && flip) {
|
||||||
sandbox.radioSet = RadioSet.valid({mode: flip});
|
sandbox.radioSet = RadioSet.valid({mode: flip, fallback: "burst"});
|
||||||
}
|
}
|
||||||
return "";
|
return "";
|
||||||
};
|
};
|
||||||
@@ -248,7 +248,7 @@ function radio({running = true, hold = "", long = "", fail = 0, scale = 1000, bu
|
|||||||
decodeAudioData: async (data) => ({duration: data.text === long ? 60 : 1, text: data.text}),
|
decodeAudioData: async (data) => ({duration: data.text === long ? 60 : 1, text: data.text}),
|
||||||
};
|
};
|
||||||
const sandbox = {
|
const sandbox = {
|
||||||
RadioSet, Voice, radioSet: RadioSet.valid(null), state: {now: 1000, messages: [], speech: {tts: true, gate: {open: true}}},
|
RadioSet, Voice, radioSet: RadioSet.valid({fallback: "burst"}), state: {now: 1000, messages: [], speech: {tts: true, gate: {open: true}}},
|
||||||
speech: {pending: [], busy: false, warned: 0, current: null, source: null, loading: null, timer: 0, item: null},
|
speech: {pending: [], busy: false, warned: 0, current: null, source: null, loading: null, timer: 0, item: null},
|
||||||
settings: {bubbles, music: {on: false, volume: 0.4}}, SPEECH_QUEUE: 20, SPEECH_QUIET: 60000, SOUND_SLACK: 2, HUMAN: "Operator", Bubbles: {reading: () => 0.001},
|
settings: {bubbles, music: {on: false, volume: 0.4}}, SPEECH_QUEUE: 20, SPEECH_QUIET: 60000, SOUND_SLACK: 2, HUMAN: "Operator", Bubbles: {reading: () => 0.001},
|
||||||
keep: stub, drawRadioSet: stub, drawBubbles: stub, drawSpeaker: stub, duck: stub, clearBubbles: stub, wordsRead: () => 0, saidOf: (item) => item.words, toast: (title) => run.log.push(["toast", title]),
|
keep: stub, drawRadioSet: stub, drawBubbles: stub, drawSpeaker: stub, duck: stub, clearBubbles: stub, wordsRead: () => 0, saidOf: (item) => item.words, toast: (title) => run.log.push(["toast", title]),
|
||||||
@@ -437,7 +437,7 @@ def run(calls: dict[str, list[list]]) -> dict:
|
|||||||
class TestRadioSetModule(unittest.TestCase):
|
class TestRadioSetModule(unittest.TestCase):
|
||||||
@classmethod
|
@classmethod
|
||||||
def setUpClass(cls):
|
def setUpClass(cls):
|
||||||
defaults = {"mode": "auto", "classes": ["mayday", "pan-pan", "security"], "muted": ["s9"], "sounds": {}, "squelch": 1, "log": {}}
|
defaults = {"mode": "auto", "fallback": "burst", "classes": ["mayday", "pan-pan", "security"], "muted": ["s9"], "sounds": {}, "squelch": 1, "log": {}}
|
||||||
modes = ("auto", "quiet", "silence")
|
modes = ("auto", "quiet", "silence")
|
||||||
lives = ({"tts": True, "open": True}, {"tts": True, "open": False}, {"tts": False, "open": True})
|
lives = ({"tts": True, "open": True}, {"tts": True, "open": False}, {"tts": False, "open": True})
|
||||||
plans = [["plan", ROWS[name], {**defaults, "mode": mode}, live] for mode in modes for live in lives for name in ROWS]
|
plans = [["plan", ROWS[name], {**defaults, "mode": mode}, live] for mode in modes for live in lives for name in ROWS]
|
||||||
@@ -596,7 +596,7 @@ class TestTransmit(unittest.TestCase):
|
|||||||
self.assertEqual(self.data["stalled"], {"before": [False, True], "after": [True, None], "waits": [2500], "stops": 1})
|
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):
|
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", {"mode": "morse"}, "context"])
|
self.assertEqual(self.data["pressed"], [{"mode": "auto"}, "context", {"mode": "quiet"}, "context", {"mode": "silence"}, "context", {"mode": "morse"}, "context", {"mode": "gibberlink"}, "context"])
|
||||||
|
|
||||||
|
|
||||||
class TestSpeechModes(unittest.TestCase):
|
class TestSpeechModes(unittest.TestCase):
|
||||||
|
|||||||
Reference in new issue
Block a user