feat(hub): grant split menu, radio redesign and answerable decision rows
The Grant bar becomes one split control: Select, or Grant N with a menu for Deny, Grant all green, the picked list, Clear and Direct mode; picked items turn pale green. The radio drops its filter flyout and gains three-state bells per row, a test per row including Speak, Auto or Morse on a second click, mute on the sender avatar and the agent profile, Cancel MAYDAY beside Send only while one is active, a Send menu with a test message and hold-to-record push-to-talk. Decision rows read as questions with their options; the signed answer is Decision <id> plus Answer: <answer>, and the card names its recipient. Security: the passkey-signed answer carries no agent-written text, the inbox lists answerable rows only when their id fullmatches the TASK rule of the installed rasci.py (skill_scripts.task_pattern), and rasci.py, operator.py and hotfix.py check task slugs with fullmatch, so a trailing newline no longer passes. Accepted MEDUSA findings after kvb-think-criticize: page-inbox.js:116 EXA006 (by design after the fix), page-inbox.js:125 EXA010, operator.py:173, 618 and 633 RP001, FT-TRIGGER-005 and RLHF-POISON-002, operator.py:639 MEX-SCAN-346, operator.py:968 MM-SCAN-058, operator.py:974 ACP-SCAN-028 (false positives). 🎯 Fix: 85 % 💥 Break: 10 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 77 🚦 Gate: ⛔ fix 85 % < 90, break 10 % > 5 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ff9bbc19c2
commit
d695bb2b58
42 files changed
+1158
-340
No files matched your search
@@ -57,7 +57,7 @@ IGNORABLE = frozenset(code for start, end in DEFAULT_IGNORABLE for code in range
|
||||
EMOJI_TABLE = Path(__file__).with_name("emoji-variation.json")
|
||||
HEX_CODE = re.compile(r"[0-9A-F]{4,6}")
|
||||
PRESENTATION = (chr(0xFE0E), chr(0xFE0F))
|
||||
FREE_TEXT = ("command", "text", "reason", "question", "description")
|
||||
FREE_TEXT = ("command", "text", "reason", "question", "description", "preview")
|
||||
BREAKS = "\t\n"
|
||||
DEPTH_LIMIT = 64
|
||||
WARNINGS = (
|
||||
|
||||
@@ -7,6 +7,8 @@ from .diffs import sealed_file, store_diff, store_sealed, valid_diff, valid_seal
|
||||
from .errors import Conflict, Missing, ToolError
|
||||
from .fields import (
|
||||
COMMAND_LIMIT,
|
||||
DESCRIPTION_LIMIT,
|
||||
OPTION_LIMIT,
|
||||
PATH_LIMIT,
|
||||
WAIT_CAP,
|
||||
bounded,
|
||||
@@ -21,8 +23,7 @@ from .fields import (
|
||||
from .signed import ask_signed
|
||||
|
||||
ASK_LIFETIME = 3600
|
||||
DESCRIPTION_LIMIT = 1000
|
||||
OPTION_LIMIT = 12
|
||||
PREVIEW_LIMIT = 4000
|
||||
ASK_TEXTS = {"command": COMMAND_LIMIT, "cwd": PATH_LIMIT, "session": 200, "agent": 200}
|
||||
ANSWERS = {"allow": "allowed", "deny": "denied"}
|
||||
|
||||
@@ -52,13 +53,22 @@ def decision_row(decision: dict) -> dict:
|
||||
|
||||
|
||||
def option_of(option: object) -> dict:
|
||||
"""Args:
|
||||
option: {"label", "description"} and an optional "preview", a
|
||||
multi-line mockup, snippet or table shown beside the options.
|
||||
|
||||
Returns:
|
||||
The option with its texts stripped; "preview" only when it was given
|
||||
and is not empty.
|
||||
"""
|
||||
if not isinstance(option, dict):
|
||||
raise ToolError("every option must be an object with label and description")
|
||||
expect(option, ("label", "description"))
|
||||
expect(option, ("label", "description", *(("preview",) if "preview" in option else ())))
|
||||
label = field(option, "label").strip()
|
||||
description = bounded(option, "description", DESCRIPTION_LIMIT).strip()
|
||||
visible({"description": description})
|
||||
return {"label": label, "description": description}
|
||||
preview = bounded(option, "preview", PREVIEW_LIMIT).rstrip() if "preview" in option else ""
|
||||
visible({"description": description, "preview": preview})
|
||||
return {"label": label, "description": description, **({"preview": preview} if preview.strip() else {})}
|
||||
|
||||
|
||||
class Asking:
|
||||
|
||||
@@ -12,6 +12,8 @@ TEXT_LIMIT = 20_000
|
||||
COMMAND_LIMIT = 4000
|
||||
PATH_LIMIT = limits.PATH_LIMIT
|
||||
NAME_LIMIT = 120
|
||||
DESCRIPTION_LIMIT = 1000
|
||||
OPTION_LIMIT = 12
|
||||
COUNT = re.compile(r"[0-9]{1,12}")
|
||||
PATH = re.compile(rf"/[^\x00-\x1f\x7f]{{0,{PATH_LIMIT - 1}}}")
|
||||
LINE = r"(?=[^\x00-\x1f\x7f]*\S)[^\x00-\x1f\x7f]{{1,{0}}}"
|
||||
|
||||
@@ -12,6 +12,7 @@ from .names import Directory
|
||||
from .records import digest, iso_epoch
|
||||
from .register import adder, operator_rows, runnable
|
||||
from .signed import signing
|
||||
from .skill_scripts import task_pattern
|
||||
|
||||
SNOOZE_LIMIT = 8 * 86400
|
||||
|
||||
@@ -19,7 +20,7 @@ SNOOZE_LIMIT = 8 * 86400
|
||||
class Inbox:
|
||||
def inbox(self, now: float, tasks: dict[str, dict], directory: Directory) -> list[dict]:
|
||||
claims = read_claims(self.council)
|
||||
base = {"agent": "", "to": "", "detail": "", "green": False, "gate": "", "score": "", "warnings": [], "options": [], "recommended": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False}
|
||||
base = {"agent": "", "to": "", "detail": "", "green": False, "gate": "", "score": "", "warnings": [], "options": [], "recommended": "", "check": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False}
|
||||
items = []
|
||||
for review in self.reviews.pending():
|
||||
created = iso_epoch(review["created"]) or now
|
||||
@@ -37,10 +38,11 @@ class Inbox:
|
||||
items.append({**base, "kind": "decision", "id": decision["id"], "ts": decision["created_ts"], **fields})
|
||||
held = self.open_jobs()
|
||||
consoles = self.consoles()
|
||||
rows = operator_rows(tasks)
|
||||
pattern = task_pattern(self.scripts.skills)
|
||||
rows = [row for row in operator_rows(tasks) if pattern is not None and pattern.fullmatch(row["task"])]
|
||||
for row in rows:
|
||||
busy = row["task"] in held
|
||||
fields = {"title": row["command"], "detail": row["why"], "agent": adder(tasks[row["task"]]), "to": requester_of(claims, adder(tasks[row["task"]]))[0], "command": row["command"], "directory": row["directory"], "sha256": digest(row["command"])}
|
||||
fields = {"title": row["command"], "detail": row["why"], "agent": adder(tasks[row["task"]]), "to": requester_of(claims, adder(tasks[row["task"]]))[0], "command": row["command"], "directory": row["directory"], "sha256": digest(row["command"]), "check": row["check"], "options": row["options"], "recommended": row["recommended"]}
|
||||
state = {"runnable": runnable(row) and not busy, "deniable": not busy, "job": console_of(consoles.get(row["task"]))}
|
||||
items.append({**base, "kind": "operator", "id": row["task"], "ts": self.watch.first(row["task"], now), **fields, **state})
|
||||
listed = {row["task"] for row in rows}
|
||||
|
||||
@@ -4,10 +4,9 @@ import json
|
||||
from http import HTTPStatus
|
||||
|
||||
from . import NAME
|
||||
from .asking import OPTION_LIMIT
|
||||
from .choosing import CHOICE_REQUEST
|
||||
from .errors import RpcError, ToolError
|
||||
from .fields import WAIT_CAP
|
||||
from .fields import OPTION_LIMIT, WAIT_CAP
|
||||
from .requesting import AGENT_CAP
|
||||
from .reviewing import GATES
|
||||
from .rules import RULE_KINDS
|
||||
@@ -34,7 +33,11 @@ class Mcp:
|
||||
wait = {"type": "number", "minimum": 0, "description": f"Seconds to wait, capped at {WAIT_CAP}."}
|
||||
option = {
|
||||
"type": "object",
|
||||
"properties": {"label": text_property("Button text, one line."), "description": text_property("What choosing it means; may be empty.")},
|
||||
"properties": {
|
||||
"label": text_property("Button text, one line."),
|
||||
"description": text_property("What choosing it means; may be empty."),
|
||||
"preview": text_property("Optional multi-line mockup, snippet, diff or table shown in monospace beside the options while this option is focused; only for options that need a visual comparison."),
|
||||
},
|
||||
"required": ["label", "description"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
@@ -3,9 +3,11 @@ from __future__ import annotations
|
||||
from pathlib import Path
|
||||
|
||||
from .council import HUMAN, agent, ordered
|
||||
from .fields import ORDER_NAME
|
||||
from .fields import DESCRIPTION_LIMIT, OPTION_LIMIT, ORDER_NAME
|
||||
from .records import read_json, shown
|
||||
|
||||
LABEL_LIMIT = 80
|
||||
|
||||
REGISTER = "rasci.json"
|
||||
AGENT_ORDER = "agent-order.json"
|
||||
OPERATOR = "operator/"
|
||||
@@ -53,19 +55,46 @@ def is_open(task: str, row: dict, operator: bool) -> bool:
|
||||
return task.startswith(OPERATOR) == operator and status_of(row) not in ENDED
|
||||
|
||||
|
||||
def row_options(row: dict) -> list[dict]:
|
||||
"""Args:
|
||||
row: an operator row of the register, which agents write.
|
||||
|
||||
Returns:
|
||||
A decision row's options as {"label", "description"}, at most
|
||||
OPTION_LIMIT, each label one non-empty line of at most LABEL_LIMIT
|
||||
characters and unique; [] for any other row or malformed options.
|
||||
"""
|
||||
raw = row.get("options")
|
||||
if row.get("check") != "decision" or not isinstance(raw, list):
|
||||
return []
|
||||
options = []
|
||||
for option in raw[:OPTION_LIMIT]:
|
||||
label = option.get("label") if isinstance(option, dict) else None
|
||||
description = option.get("description", "") if isinstance(option, dict) else None
|
||||
if isinstance(label, str) and isinstance(description, str) and label.strip() and label.isprintable() and len(label) <= LABEL_LIMIT:
|
||||
options.append({"label": label.strip(), "description": " ".join(description.split())[:DESCRIPTION_LIMIT]})
|
||||
labels = [option["label"] for option in options]
|
||||
return options if len(set(labels)) == len(labels) else []
|
||||
|
||||
|
||||
def operator_rows(tasks: dict[str, dict]) -> list[dict]:
|
||||
return [
|
||||
{
|
||||
rows = []
|
||||
for task, row in sorted(tasks.items()):
|
||||
if not is_open(task, row, True):
|
||||
continue
|
||||
options = row_options(row)
|
||||
recommended = row.get("recommended")
|
||||
rows.append({
|
||||
"task": task,
|
||||
"command": shown(row.get("title")),
|
||||
"directory": shown(row.get("workdir")),
|
||||
"why": shown(row.get("description")),
|
||||
"check": shown(row.get("check")),
|
||||
"status": status_of(row),
|
||||
}
|
||||
for task, row in sorted(tasks.items())
|
||||
if is_open(task, row, True)
|
||||
]
|
||||
"options": options,
|
||||
"recommended": recommended if recommended in [option["label"] for option in options] else "",
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def runnable(row: dict) -> bool:
|
||||
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import importlib.util
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
@@ -50,6 +51,19 @@ def script_module(script: Path) -> ModuleType | None:
|
||||
return loaded(script, changed)
|
||||
|
||||
|
||||
def task_pattern(skills: Path) -> re.Pattern[str] | None:
|
||||
"""Args:
|
||||
skills: the installed skills directory, the hub's --skills mount.
|
||||
|
||||
Returns:
|
||||
TASK of the installed kvb-org-rasci rasci.py, the one rule for
|
||||
register task ids; None when the script is missing, does not load or
|
||||
holds no compiled pattern.
|
||||
"""
|
||||
found = getattr(script_module(skills / RASCI), "TASK", None)
|
||||
return found if isinstance(found, re.Pattern) else None
|
||||
|
||||
|
||||
@functools.cache
|
||||
def loaded(script: Path, changed: int) -> ModuleType | None:
|
||||
spec = importlib.util.spec_from_file_location(f"kvb_orchestrator_{script.stem}_{changed}", script)
|
||||
|
||||
@@ -60,9 +60,18 @@ h1 { margin: 0; font-size: var(--fs-lg); font-weight: 680; letter-spacing: -.01e
|
||||
.badge.alarm { background: var(--alarm); color: #fff; }
|
||||
.tools { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 6px; }
|
||||
.grant-bar, .grant-tray { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 6px; }
|
||||
.grant-tray[hidden] { display: none; }
|
||||
.grant-bar .segmented button { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.grant-count { color: var(--muted); font-size: var(--fs-sm); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.grant-split { display: inline-flex; align-items: stretch; }
|
||||
.grant-split > .btn { display: inline-flex; align-items: center; gap: 6px; border-top-right-radius: 0; border-bottom-right-radius: 0; }
|
||||
.grant-menu > summary.grant-count { height: 100%; margin-left: -1px; padding: 0 7px; border-top-left-radius: 0; border-bottom-left-radius: 0; }
|
||||
.grant-menu-box { gap: 2px; min-width: 15rem; padding: 6px; }
|
||||
.menu-item { display: flex; align-items: center; gap: 8px; width: 100%; padding: 7px 10px; border: 0; border-radius: 8px; background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; }
|
||||
.menu-item:hover:not(:disabled), .menu-item:focus-visible { background: var(--sunken); }
|
||||
.menu-item:disabled { opacity: .45; cursor: not-allowed; }
|
||||
.menu-item.danger { color: var(--bad); }
|
||||
.grant-picked { display: grid; gap: 2px; max-height: 40vh; margin: 4px 0; padding: 4px 0; overflow: auto; border-block: 1px solid var(--line); list-style: none; }
|
||||
.grant-picked-title { min-width: 0; max-width: 24rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.btn.picked:disabled { border-color: color-mix(in srgb, var(--ok) 40%, transparent); background: color-mix(in srgb, var(--ok) 18%, var(--panel)); color: var(--ok); opacity: 1; cursor: default; }
|
||||
:is(.item, .entry):has(button.picked) { background: color-mix(in srgb, var(--ok) 7%, var(--panel)); }
|
||||
.banner { display: flex; align-items: center; gap: var(--sp-3); padding: var(--sp-2) var(--sp-5); background: var(--alarm); color: #fff; font-weight: 650; }
|
||||
.banner[hidden] { display: none; }
|
||||
.banner .text { flex: 1; min-width: 0; margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
@@ -355,8 +364,15 @@ textarea + .mic-auto { display: flex; margin: 4px 0 0 auto; }
|
||||
.option:hover { background: var(--accent-soft); border-color: var(--accent); }
|
||||
.option.recommended { border-color: var(--ok); box-shadow: inset 3px 0 0 var(--ok); }
|
||||
.option span { color: var(--muted); font-size: var(--fs-sm); }
|
||||
.option:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||
.option.other { display: flex; gap: 6px; align-items: center; cursor: default; }
|
||||
.option.other:hover { background: var(--panel); border-color: var(--line-strong); }
|
||||
.option.other .field { flex: 1; min-width: 0; }
|
||||
.choice { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); gap: 10px; align-items: start; }
|
||||
.choice-preview { margin: 8px 0 0; padding: 10px 12px; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--panel); line-height: 1.45; white-space: pre; overflow: auto; max-height: 360px; }
|
||||
.text.question { font-weight: 600; }
|
||||
@media (max-width: 720px) { .choice { grid-template-columns: 1fr; } }
|
||||
.inbox-head { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
|
||||
.inbox-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 12px; }
|
||||
.inbox-list { display: grid; gap: 8px; margin: 0; padding: 0; list-style: none; }
|
||||
.item { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: var(--sp-2) var(--sp-3); padding: var(--sp-3); border: 1px solid var(--line); border-radius: 12px; background: var(--glass-card); }
|
||||
.item.cursor { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||
|
||||
@@ -113,7 +113,7 @@
|
||||
const life = h("span", {class: "muted"});
|
||||
const night = h("span", {});
|
||||
const claimed = nightAgents().some(([sid]) => sid === key);
|
||||
const nightRow = h("div", {class: "actions agent-night", role: "group", "aria-label": "Day/Night"}, night, h("span", {class: "spacer"}),
|
||||
const nightRow = h("div", {class: "actions agent-night", role: "group", "aria-label": "Day/Night"}, night, h("span", {class: "spacer"}), radioMute(key, name),
|
||||
claimed ? ACTIONS.slice(1).map(([id]) => actionButton(id, "btn small", null, () => [key])) : null);
|
||||
const former = (people()[key] || {names: []}).names.filter((entry) => entry !== name);
|
||||
openPopup(name, [
|
||||
@@ -134,6 +134,22 @@
|
||||
text.focus();
|
||||
}
|
||||
|
||||
function radioMute(key, name) {
|
||||
const button = h("button", {type: "button", class: "btn small agent-mute", "aria-label": `Mute ${name}`});
|
||||
const show = () => {
|
||||
const muted = radioSet.muted.includes(key);
|
||||
button.title = muted ? `Muted: the radio reads ${name} aloud again on a press` : `Mute ${name}: the radio stops reading this agent aloud`;
|
||||
button.setAttribute("aria-pressed", String(muted));
|
||||
button.replaceChildren(icon(muted ? "bi-volume-mute" : "bi-volume-up"), muted ? "Muted" : "Radio on");
|
||||
};
|
||||
button.addEventListener("click", () => {
|
||||
keepRadio(RadioSet.muting(radioSet, key));
|
||||
show();
|
||||
});
|
||||
show();
|
||||
return button;
|
||||
}
|
||||
|
||||
function agentNames() {
|
||||
const names = new Set([...state.graph.nodes.filter((node) => node.kind === "session" || node.kind === "chair").map((node) => nameOf(node.id)), ...state.agent_order]);
|
||||
return [...names].sort((a, b) => a.localeCompare(b));
|
||||
|
||||
@@ -98,7 +98,6 @@
|
||||
}
|
||||
|
||||
function drawSpot() {
|
||||
drawBars();
|
||||
drawSpeak();
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
mayday: "MAYDAY: all agents pause writing steps until you cancel it.",
|
||||
};
|
||||
const VOICE_POLL = 700;
|
||||
const HOLD_MS = 350;
|
||||
const composer = {live: null};
|
||||
|
||||
function confirmMayday() {
|
||||
@@ -71,6 +72,8 @@
|
||||
}
|
||||
|
||||
async function keepRecording(blob, parts) {
|
||||
const held = parts.ptt === "released";
|
||||
parts.ptt = "";
|
||||
parts.record.disabled = true;
|
||||
try {
|
||||
const sound = context();
|
||||
@@ -94,6 +97,9 @@
|
||||
parts.text.dispatchEvent(new Event("input", {bubbles: true}));
|
||||
parts.text.focus();
|
||||
parts.status.textContent = note.text ? "Check the text, then send." : "Nothing understood: write the text yourself.";
|
||||
if (held && note.text) {
|
||||
parts.text.form.requestSubmit();
|
||||
}
|
||||
} catch (error) {
|
||||
parts.status.textContent = "";
|
||||
toast("Recording failed", [String(error.message || error)], false);
|
||||
@@ -150,6 +156,9 @@
|
||||
composer.live = parts;
|
||||
recorder.start();
|
||||
recordLabel(parts, true);
|
||||
if (parts.ptt === "released") {
|
||||
stopRecording(parts);
|
||||
}
|
||||
parts.timer = window.setInterval(() => {
|
||||
const seconds = Math.floor((Date.now() - parts.started) / 1000);
|
||||
parts.status.textContent = `Recording ${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")} of at most ${state.speech.seconds} s`;
|
||||
@@ -167,17 +176,31 @@
|
||||
const replay = h("div", {class: "voice-note", hidden: true});
|
||||
const hint = h("span", {class: "muted composer-hint"});
|
||||
const status = h("span", {class: "muted composer-status", "aria-live": "polite"});
|
||||
const record = h("button", {type: "button", class: "btn small", "aria-pressed": "false", title: "Record: one click starts, another stops; the hub transcribes, you check the text before sending"});
|
||||
const record = h("button", {type: "button", class: "btn small", "aria-pressed": "false", title: "Record: one click starts, another stops, you check the text before sending; hold it to talk, release to send"});
|
||||
const submit = h("button", {type: "submit", class: "btn primary ptt", title: "PTT: push to transmit the message; your passkey signs it"}, icon("bi-broadcast-pin"), "PTT");
|
||||
const attach = h("input", {type: "checkbox", title: "Attach recording: the agents get the path of the sound file; otherwise only the checked text goes out"});
|
||||
const parts = {record, status, text, replay, attach, voice: "", recorder: null, timer: 0, started: 0};
|
||||
const parts = {record, status, text, replay, attach, voice: "", recorder: null, timer: 0, started: 0, ptt: "", hold: 0, swallow: false};
|
||||
recordLabel(parts, false);
|
||||
const gap = micGap();
|
||||
if (gap) {
|
||||
record.disabled = true;
|
||||
record.title = `Record: ${gap}`;
|
||||
}
|
||||
record.addEventListener("click", () => (parts.recorder ? stopRecording(parts) : startRecording(parts)));
|
||||
holdToTalk(parts);
|
||||
record.addEventListener("click", () => {
|
||||
if (parts.swallow) {
|
||||
parts.swallow = false;
|
||||
return;
|
||||
}
|
||||
parts.ptt = "";
|
||||
if (parts.recorder) {
|
||||
stopRecording(parts);
|
||||
} else {
|
||||
startRecording(parts);
|
||||
}
|
||||
});
|
||||
const [, cancel, , cancelHint] = actionOf("clear-mayday");
|
||||
const clear = h("button", {type: "button", class: "btn small danger radio-cancel", hidden: !state.silence, ...named(cancel, cancelHint), on: {click: () => confirmAct("clear-mayday", [])}}, icon("bi-life-preserver"), cancel);
|
||||
const sync = () => {
|
||||
const direct = TO_ONE.some(([id]) => id === channel.value);
|
||||
toField.hidden = !direct;
|
||||
@@ -187,7 +210,7 @@
|
||||
channel.addEventListener("change", sync);
|
||||
sync();
|
||||
const form = h("form", {class: "composer"}, h("div", {class: "composer-grid"}, h("label", {}, "Channel", channel), toField), text, replay,
|
||||
h("div", {class: "actions"}, record, micButton(text, false), status, hint, submit));
|
||||
h("div", {class: "actions"}, record, micButton(text, false), status, hint, clear, h("div", {class: "ptt-split", role: "group", "aria-label": "Send"}, submit, testMenu(text, channel))));
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const direct = TO_ONE.some(([id]) => id === channel.value);
|
||||
@@ -207,5 +230,45 @@
|
||||
submit.disabled = false;
|
||||
});
|
||||
attachVoice(parts, "");
|
||||
return {form, recipient, text, channel};
|
||||
return {form, recipient, text, channel, clear};
|
||||
}
|
||||
|
||||
function holdToTalk(parts) {
|
||||
const {record} = parts;
|
||||
record.addEventListener("pointerdown", (event) => {
|
||||
if (event.button !== 0 || record.disabled || parts.recorder) {
|
||||
return;
|
||||
}
|
||||
parts.hold = window.setTimeout(() => {
|
||||
parts.ptt = "holding";
|
||||
startRecording(parts);
|
||||
}, HOLD_MS);
|
||||
});
|
||||
const release = () => {
|
||||
window.clearTimeout(parts.hold);
|
||||
if (parts.ptt === "holding") {
|
||||
Object.assign(parts, {ptt: "released", swallow: true});
|
||||
stopRecording(parts);
|
||||
}
|
||||
};
|
||||
for (const kind of ["pointerup", "pointercancel", "pointerleave"]) {
|
||||
record.addEventListener(kind, release);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Element} text the message field.
|
||||
* @param {Element} channel the class select.
|
||||
* @returns {Element} the ▾ of PTT: a menu whose item reads the message, or a sample line, aloud here only, so nothing leaves the browser.
|
||||
*/
|
||||
function testMenu(text, channel) {
|
||||
const item = h("button", {type: "button", class: "menu-item", ...named("Test message", "Test message: hear it here as the radio reads it aloud; nothing is sent, nothing is signed"), on: {click: (event) => {
|
||||
event.currentTarget.closest("details").open = false;
|
||||
if (!state.speech.tts) {
|
||||
toast("No test message", [`The hub speaks no line: ${state.speech.tts_off}.`], false);
|
||||
return;
|
||||
}
|
||||
say({steps: [{kind: "speech", text: text.value.trim() || state.speech.sample}], voice: state.speech.operator, tone: "direct", cls: channel.value, who: HUMAN, sent: true, line: "test message"});
|
||||
}}}, icon("bi-play-fill"), "Test message");
|
||||
return h("details", {class: "menu ptt-menu"}, h("summary", {class: "btn primary ptt-more", ...named("More send options", "More: send a test message only you hear")}, caret()), h("div", {class: "menu-box end"}, item));
|
||||
}
|
||||
@@ -47,7 +47,6 @@
|
||||
dead: ["Dead", "bi-x-octagon-fill", "bad"],
|
||||
};
|
||||
const SOUND_KINDS = [["mayday", "MAYDAY / PAN-PAN"], ["review", "Reviews, asks, decisions"], ["direct", "Post and calls to you"], ["radio", "All radio"]];
|
||||
const SPEECH_CLASSES = [["post", "Post"], ["call", "Call"], ["newsletter", "Newsletter"], ["broadcast", "Broadcast"], ["mayday", "MAYDAY"], ["pan-pan", "PAN-PAN"], ["security", "Sécurité"]];
|
||||
const SPEECH_QUEUE = 20;
|
||||
const SPEECH_QUIET = 60000;
|
||||
const SPEECH_FRESH = 300;
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
const GRANT_SELECT = "select";
|
||||
const GRANT_MODES = [
|
||||
["direct", "Direct", "bi-lightning-charge", "Direct: every grant button grants at once"],
|
||||
[GRANT_SELECT, "Select", "bi-check2-square", "Select: every grant button adds its item to the selection; the tray grants the selection under one passkey signature"],
|
||||
];
|
||||
const GRANT_MODES = {
|
||||
direct: ["Direct", "bi-lightning-charge", "Direct mode", "Direct: every grant button grants at once"],
|
||||
[GRANT_SELECT]: ["Select", "bi-check2-square", "Select mode", "Select: every grant button adds its item to the selection; Grant grants the selection under one passkey signature"],
|
||||
};
|
||||
const PICKED_HINT = "In the selection: take it out with ✕ in the Grant menu";
|
||||
const DIRECT_WHY = {rule: "a rule is accepted one at a time", review: "a red gate is never granted in a selection"};
|
||||
const grantView = {modes: [], tray: null, sig: ""};
|
||||
const grantView = {tray: null, sig: "", open: false};
|
||||
|
||||
const grantMode = () => (typeof ViewStore === "object" && ViewStore ? ViewStore.get("approval.mode") : "direct");
|
||||
const collecting = (item) => grantMode() === GRANT_SELECT && selectable(item);
|
||||
@@ -27,53 +28,83 @@
|
||||
/**
|
||||
* @param button - the grant button of item.
|
||||
* @param item - a waiting inbox item.
|
||||
* @returns button; in Select it shows whether item is in the selection, or why its grant still acts at once.
|
||||
* @returns button; a picked item's button turns pale green and disabled, and in Select it says why a grant still acts at once.
|
||||
*/
|
||||
function grantPress(button, item) {
|
||||
if (grantMode() !== GRANT_SELECT) {
|
||||
return button;
|
||||
}
|
||||
const select = grantMode() === GRANT_SELECT;
|
||||
if (!selectable(item)) {
|
||||
button.setAttribute("title", `${button.getAttribute("title")}: acts at once, ${DIRECT_WHY[item.kind]}`);
|
||||
if (select) {
|
||||
button.setAttribute("title", `${button.getAttribute("title")}: acts at once, ${DIRECT_WHY[item.kind]}`);
|
||||
}
|
||||
return button;
|
||||
}
|
||||
const picked = ui.selected.has(keyOf(item));
|
||||
button.setAttribute("aria-pressed", String(picked));
|
||||
button.setAttribute("title", picked ? "In the selection: press to take it out" : "Select: press to add it to the selection; the tray grants it");
|
||||
if (picked) {
|
||||
button.disabled = true;
|
||||
button.setAttribute("class", `${button.getAttribute("class")} picked`);
|
||||
button.setAttribute("title", PICKED_HINT);
|
||||
}
|
||||
if (select) {
|
||||
button.setAttribute("aria-pressed", String(picked));
|
||||
if (!picked) {
|
||||
button.setAttribute("title", "Select: press to add it to the selection; Grant grants it");
|
||||
}
|
||||
}
|
||||
return button;
|
||||
}
|
||||
|
||||
function modeItem(mode) {
|
||||
const [, name, text, hint] = GRANT_MODES[mode];
|
||||
return h("button", {type: "button", id: `grant-${mode}`, class: "menu-item", "data-mode": mode, ...named(GRANT_MODES[mode][0], hint), on: {click: () => {
|
||||
grantView.open = false;
|
||||
ViewStore.set("approval.mode", mode);
|
||||
}}}, icon(name), text);
|
||||
}
|
||||
|
||||
function pickedItem(item) {
|
||||
return h("li", {}, h("button", {type: "button", class: "menu-item", ...named(`Remove ${item.title}`, "Remove: take it out of the selection"), on: {click: () => collect(item)}},
|
||||
icon("bi-x-lg"), h("span", {class: "grant-picked-title"}, revealed(item.title))));
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Node} the one selection control: Select, or Grant N once something is picked or Select mode is on, with a menu of the rest.
|
||||
*/
|
||||
function grantSplit(mode, actions) {
|
||||
const selecting = mode === GRANT_SELECT || actions.chosen.length > 0;
|
||||
const [label, name, , hint] = GRANT_MODES[GRANT_SELECT];
|
||||
const main = selecting ? actions.grant : h("button", {type: "button", id: "grant-select", class: "btn small", "data-mode": GRANT_SELECT, ...named(label, hint), on: {click: () => ViewStore.set("approval.mode", GRANT_SELECT)}},
|
||||
icon(name), h("span", {class: "grant-label"}, label));
|
||||
const clear = h("button", {type: "button", class: "menu-item", ...named("Clear", "Clear: empty the selection"), disabled: !actions.chosen.length, on: {click: () => {
|
||||
ui.selected.clear();
|
||||
regrant();
|
||||
}}}, icon("bi-x-lg"), "Clear selection");
|
||||
const menu = h("details", {class: "menu grant-menu", open: grantView.open, on: {toggle: (event) => {
|
||||
grantView.open = event.currentTarget.open;
|
||||
}}}, h("summary", {class: "grant-count", ...named(`${actions.chosen.length} selected`, "More: deny, grant all green, the picked items, clear, mode")}, caret()),
|
||||
h("div", {class: "menu-box end grant-menu-box"}, actions.deny, actions.green,
|
||||
actions.chosen.length ? h("ul", {class: "grant-picked", "aria-label": "Picked"}, actions.chosen.map(pickedItem)) : null,
|
||||
clear, selecting ? modeItem(mode === GRANT_SELECT ? "direct" : GRANT_SELECT) : null));
|
||||
return h("div", {class: "grant-split", role: "group", "aria-label": "Selection"}, main, menu);
|
||||
}
|
||||
|
||||
function drawGrant() {
|
||||
if (!grantView.tray) {
|
||||
return;
|
||||
}
|
||||
const mode = grantMode();
|
||||
const chosen = state.inbox.filter((item) => ui.selected.has(keyOf(item)));
|
||||
const sig = JSON.stringify([mode, chosen.map(keyOf), state.inbox.map((item) => [keyOf(item), isGreen(item), item.held]), ui.busy]);
|
||||
const actions = selectionActions(state.inbox);
|
||||
const sig = JSON.stringify([mode, actions.chosen.map(keyOf), state.inbox.map((item) => [keyOf(item), isGreen(item), item.held]), ui.busy]);
|
||||
if (sig === grantView.sig) {
|
||||
return;
|
||||
}
|
||||
grantView.sig = sig;
|
||||
for (const button of grantView.modes) {
|
||||
button.setAttribute("aria-pressed", String(button.dataset.mode === mode));
|
||||
}
|
||||
grantView.tray.hidden = mode !== GRANT_SELECT;
|
||||
grantView.tray.replaceChildren(...(mode === GRANT_SELECT ? [
|
||||
h("span", {class: "grant-count", "aria-live": "polite"}, `${chosen.length} selected`),
|
||||
...selectionButtons(state.inbox),
|
||||
h("button", {type: "button", class: "btn small ghost", ...named("Clear", "Clear: empty the selection"), disabled: !chosen.length, on: {click: () => {
|
||||
ui.selected.clear();
|
||||
regrant();
|
||||
}}}, icon("bi-x-lg"), "Clear"),
|
||||
] : []));
|
||||
grantView.tray.replaceChildren(grantSplit(mode, actions));
|
||||
}
|
||||
|
||||
function grantBoot() {
|
||||
const bar = document.getElementById("grant-bar");
|
||||
grantView.modes = GRANT_MODES.map(([mode, label, name, hint]) => h("button", {type: "button", id: `grant-${mode}`, "data-mode": mode, ...named(label, hint), on: {click: () => ViewStore.set("approval.mode", mode)}},
|
||||
icon(name), h("span", {class: "grant-label"}, label)));
|
||||
grantView.tray = h("div", {class: "grant-tray", role: "group", "aria-label": "Selection"});
|
||||
bar.replaceChildren(h("div", {class: "segmented", role: "group", "aria-label": "Grant mode"}, grantView.modes), grantView.tray);
|
||||
grantView.tray = h("div", {class: "grant-tray"});
|
||||
bar.replaceChildren(grantView.tray);
|
||||
ViewStore.on("approval", regrant);
|
||||
drawGrant();
|
||||
}
|
||||
@@ -105,6 +105,59 @@
|
||||
}
|
||||
|
||||
const chooseOne = (item, label) => submit([entryOf(item, "approve", label)], `Choice: ${label}`);
|
||||
const asked = (item) => item.kind === "operator" && item.check === "decision";
|
||||
const answers = new Map();
|
||||
|
||||
async function answerRow(item, answer) {
|
||||
if (!item.agent) {
|
||||
toast("Answer: no agent to send it to", ["The row names no adding agent; answer in its session."], false);
|
||||
return;
|
||||
}
|
||||
if (await radioSend({to: item.agent, text: `Decision ${item.id}\nAnswer: ${answer}`, cls: "post", upload: "", voice: ""})) {
|
||||
answers.set(keyOf(item), answer);
|
||||
drawInbox();
|
||||
}
|
||||
}
|
||||
|
||||
function otherAnswer(item) {
|
||||
const input = h("input", {class: "field", type: "text", placeholder: "Other answer …", "aria-label": `Other answer to ${item.id}`, disabled: answers.has(keyOf(item))});
|
||||
const form = h("form", {class: "option other"}, input,
|
||||
h("button", {type: "submit", class: "btn small", disabled: answers.has(keyOf(item)), ...named("Send", revealed(`Send: your passkey signs this answer, a post to ${item.agent}`))}, icon("bi-send"), "Send"));
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
if (input.value.trim()) {
|
||||
answerRow(item, input.value.trim());
|
||||
}
|
||||
});
|
||||
return form;
|
||||
}
|
||||
|
||||
function choicePanel(item, pick, other) {
|
||||
const done = answers.has(keyOf(item));
|
||||
const pane = item.options.some((option) => option.preview) ? h("pre", {class: "choice-preview", "aria-label": "Preview"}) : null;
|
||||
const show = (option) => {
|
||||
if (pane) {
|
||||
pane.textContent = revealedLines(option.preview || "");
|
||||
}
|
||||
};
|
||||
const buttons = item.options.map((option) => h("button", {
|
||||
type: "button", class: `option${option.label === item.recommended ? " recommended" : ""}`, title: revealed(`${option.label}: your passkey signs this answer, a post to ${item.agent}`), disabled: item.held || done,
|
||||
on: {click: () => pick(option.label), focus: () => show(option), mouseenter: () => show(option)},
|
||||
}, h("strong", {}, revealed(option.label)), option.description ? h("span", {}, revealed(option.description)) : null));
|
||||
show(item.options.find((option) => option.label === item.recommended) || item.options[0] || {});
|
||||
const list = h("div", {class: "options"}, buttons, other || null);
|
||||
return pane ? h("div", {class: "choice"}, list, pane) : list;
|
||||
}
|
||||
|
||||
const choiceOf = (item, after) => item.kind === "decision"
|
||||
? choicePanel(item, (label) => { after(); chooseOne(item, label); })
|
||||
: asked(item) ? [answerTo(item), choicePanel(item, (label) => { after(); answerRow(item, label); }, otherAnswer(item))] : null;
|
||||
|
||||
/**
|
||||
* @param {Object} item a decision row of the register.
|
||||
* @returns {HTMLElement} who receives the answer: the row's first agent with role A, which any agent can set, so the operator sees it before signing.
|
||||
*/
|
||||
const answerTo = (item) => h("p", {class: "muted answer-to"}, item.agent ? ["Your answer goes to ", h("strong", {}, revealed(item.agent)), " as a passkey-signed post, with the row id and your answer only."] : "No agent holds role A on this row: answer in its session.");
|
||||
|
||||
const deniable = (item) => item.deniable || item.kind === "review";
|
||||
const denialOf = (item, reason) => ({...entryOf(item, "reject", ""), channel: "post", reason, to: item.to});
|
||||
@@ -136,16 +189,20 @@
|
||||
(reason || confirm).focus();
|
||||
}
|
||||
|
||||
function selectionButtons(items) {
|
||||
/**
|
||||
* @returns {object} the picked items as chosen, and the grant, deny and grant-all-green controls of the Grant menu.
|
||||
*/
|
||||
function selectionActions(items) {
|
||||
const green = items.filter(isGreen);
|
||||
const chosen = items.filter((item) => ui.selected.has(keyOf(item)));
|
||||
const denials = chosen.filter(deniable);
|
||||
const grantable = chosen.filter(selectable);
|
||||
return [
|
||||
h("button", {type: "button", class: "btn small soft", ...named(`Grant selection (${grantable.length})`), disabled: !grantable.length || ui.busy, on: {click: () => bulk(chosen, "Grant selection", false)}}, icon("bi-check2-square"), String(grantable.length)),
|
||||
h("button", {type: "button", class: "btn small danger", ...named(`Deny selection (${denials.length})`, `Deny selection (${denials.length}): each requester gets its denial and an optional reason by post, one passkey signature, 3 s to undo`), disabled: !denials.length || ui.busy, on: {click: () => bulk(chosen, "Deny selection", true)}}, icon("bi-x-square"), String(denials.length)),
|
||||
h("button", {type: "button", class: "btn small primary", ...named(`Grant all green (${green.length})`), disabled: !green.length || ui.busy, on: {click: () => bulk(green, "Grant all green", false)}}, icon("bi-check2-all"), String(green.length)),
|
||||
];
|
||||
return {
|
||||
chosen,
|
||||
grant: h("button", {type: "button", class: "btn small primary", ...named(`Grant selection (${grantable.length})`), disabled: !grantable.length || ui.busy, on: {click: () => bulk(chosen, "Grant selection", false)}}, icon("bi-check2-square"), `Grant ${grantable.length}`),
|
||||
deny: h("button", {type: "button", class: "menu-item danger", ...named(`Deny selection (${denials.length})`, `Deny selection (${denials.length}): each requester gets its denial and an optional reason by post, one passkey signature, 3 s to undo`), disabled: !denials.length || ui.busy, on: {click: () => bulk(chosen, "Deny selection", true)}}, icon("bi-x-square"), `Deny ${denials.length}`),
|
||||
green: h("button", {type: "button", class: "menu-item", ...named(`Grant all green (${green.length})`), disabled: !green.length || ui.busy, on: {click: () => bulk(green, "Grant all green", false)}}, icon("bi-check2-all"), `Grant all green ${green.length}`),
|
||||
};
|
||||
}
|
||||
|
||||
async function mark(item, until, pinned) {
|
||||
@@ -175,6 +232,7 @@
|
||||
}
|
||||
ui.cursor = Math.max(visibleInbox().findIndex((entry) => keyOf(entry) === key), 0);
|
||||
drawInbox();
|
||||
drawGrant();
|
||||
const box = inboxDom.querySelector(`.item[data-index="${ui.cursor}"] > input[type="checkbox"]`);
|
||||
if (refocus && box) {
|
||||
box.focus({preventScroll: true});
|
||||
@@ -214,14 +272,15 @@
|
||||
|
||||
function inboxItem(item, index) {
|
||||
const red = item.kind === "review" && item.gate !== "pass";
|
||||
const commanded = item.kind === "ask" || item.kind === "operator";
|
||||
const commanded = item.kind === "ask" || (item.kind === "operator" && !asked(item));
|
||||
const classes = ["item", "entry", `k-${item.kind}`, "waiting", isGreen(item) ? "green" : "", red ? "red" : "", item.held ? "held" : "", index === ui.cursor ? "cursor" : ""].filter(Boolean).join(" ");
|
||||
const box = h("input", {type: "checkbox", "aria-label": `Select ${item.title}`, checked: ui.selected.has(keyOf(item)), disabled: !pickable(item), on: {change: () => toggle(item, true)}});
|
||||
return h("li", {class: classes, "data-index": index, "data-ref": keyOf(item), "data-to": item.to || null},
|
||||
box,
|
||||
h("div", {class: "msg-meta"},
|
||||
when(item.ts),
|
||||
pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]),
|
||||
asked(item) ? pill("Decision", KIND_TONES.decision) : pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]),
|
||||
answers.has(keyOf(item)) ? pill(revealed(`answered: ${answers.get(keyOf(item))}`), "ok") : null,
|
||||
item.kind === "review" ? pill(item.gate === "pass" ? "Gate green" : "Gate red", item.gate === "pass" ? "ok" : "bad") : null,
|
||||
item.warnings.map((warning) => pill(warning, "bad")),
|
||||
item.pinned ? pill("pinned", "violet") : null,
|
||||
@@ -233,13 +292,12 @@
|
||||
item.kind === "review" ? h("div", {class: "muted"}, revealed(item.detail), item.score ? revealed(` · ${item.score}`) : "") : null,
|
||||
commanded ? h("div", {class: "command", "data-path": item.directory || "-"}, h("code", {}, revealed(item.command)), copyButton(item.command)) : null,
|
||||
commanded ? h("span", {class: "muted"}, revealed(`in ${dash(item.directory)}`)) : null,
|
||||
asked(item) ? h("p", {class: "text question"}, revealed(item.title)) : null,
|
||||
item.kind === "operator" && item.detail && item.detail !== "-" ? h("p", {class: "text reason"}, revealed(item.detail)) : null,
|
||||
diffBlocks(item),
|
||||
item.job ? consoleOf(item.job) : null,
|
||||
item.kind === "rule" ? ruleRequestBody(item) : null,
|
||||
item.kind === "decision" ? h("div", {class: "options"}, item.options.map((option) => h("button", {
|
||||
type: "button", class: `option${option.label === item.recommended ? " recommended" : ""}`, title: revealed(`${option.label}: your passkey signs this answer, a post to ${item.agent}`), disabled: item.held, on: {click: () => chooseOne(item, option.label)},
|
||||
}, h("strong", {}, revealed(option.label)), option.description ? h("span", {}, revealed(option.description)) : null))) : null,
|
||||
choiceOf(item, () => {}),
|
||||
feedbackList(keyOf(item))),
|
||||
h("div", {class: "item-actions line-actions"},
|
||||
actionsFor(item),
|
||||
@@ -269,7 +327,7 @@
|
||||
}
|
||||
}
|
||||
const mode = grantMode();
|
||||
const sig = JSON.stringify([mode, items.map(withoutOutput), [...ui.selected], ui.cursor, ui.snoozed, ui.busy, Math.floor(nowSeconds() / 60), diffView.version, state.messages.map((message) => message.id)]);
|
||||
const sig = JSON.stringify([mode, items.map(withoutOutput), [...ui.selected], [...answers], ui.cursor, ui.snoozed, ui.busy, Math.floor(nowSeconds() / 60), diffView.version, state.messages.map((message) => message.id)]);
|
||||
if (sig === inboxSig) {
|
||||
repaintConsoles(items);
|
||||
return;
|
||||
@@ -283,7 +341,6 @@
|
||||
Panels.keepFocus(inboxSlot, () => inboxDom.replaceChildren(
|
||||
h("div", {class: "inbox-head"}, h("h2", {class: "group-title"}, "Waits on Operator", counter(waitingCount())), h("span", {class: "spacer"}),
|
||||
hidden ? h("label", {class: "check"}, snoozed, `${hidden} snoozed`) : null, inboxSlot),
|
||||
mode === GRANT_SELECT ? null : h("div", {class: "inbox-actions"}, selectionButtons(items)),
|
||||
onLocalhost() ? "" : h("p", {class: "muted"}, "The passkey signs grants only under ", localLink()),
|
||||
items.length ? h("ol", {class: "inbox-list"}, items.map(inboxItem)) : emptyState("All done", "Nothing is waiting for you right now.")));
|
||||
settleConsoles(items);
|
||||
@@ -304,15 +361,11 @@
|
||||
const body = [
|
||||
h("div", {class: "who"}, pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]), item.agent ? face(item.agent, false) : null, item.agent ? person(item.agent) : null, when(item.ts)),
|
||||
h("p", {class: "text"}, revealed(item.title)),
|
||||
item.command ? h("div", {class: "command"}, h("code", {}, revealed(item.command)), copyButton(item.command)) : null,
|
||||
item.command && !asked(item) ? h("div", {class: "command"}, h("code", {}, revealed(item.command)), copyButton(item.command)) : null,
|
||||
asked(item) && item.detail && item.detail !== "-" ? h("p", {class: "text reason"}, revealed(item.detail)) : null,
|
||||
item.kind === "rule" ? ruleRequestBody(item) : null,
|
||||
meta([["Directory", item.directory], ["Warnings", item.warnings.join(", ")], ["Id", item.id]]),
|
||||
item.kind === "decision" ? h("div", {class: "options"}, item.options.map((option) => h("button", {
|
||||
type: "button", class: `option${option.label === item.recommended ? " recommended" : ""}`, disabled: item.held, on: {click: () => {
|
||||
closeSheet();
|
||||
chooseOne(item, option.label);
|
||||
}},
|
||||
}, h("strong", {}, revealed(option.label)), option.description ? h("span", {}, revealed(option.description)) : null))) : null,
|
||||
choiceOf(item, closeSheet),
|
||||
h("div", {class: "actions"}, h("span", {class: "spacer"}), actionsFor(item).map((node) => {
|
||||
node.addEventListener("click", closeSheet);
|
||||
return node;
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
if (wpm !== settings.morse.wpm && await saveSettings({...settings, space: savedSpace(), morse: {wpm}})) {
|
||||
toast("Morse speed saved", [`The radio keys Morse at ${Morse.rate(wpm)}.`], true);
|
||||
}
|
||||
redrawFilters();
|
||||
redrawModeMenus();
|
||||
}
|
||||
|
||||
function morseSpeed() {
|
||||
|
||||
@@ -48,6 +48,7 @@
|
||||
const [name, label] = sent ? ["bi-arrow-up-right", "Sent"] : ["bi-arrow-down-left", "Received"];
|
||||
const first = firstLine(row.text);
|
||||
const line = h("li", {class: "radio-row", "data-key": row.key, "data-dir": sent ? "sent" : "received", "data-class": row.class, "data-ts": row.ts, on: {click: (event) => openRadioRow(event.currentTarget.row, event.currentTarget)}},
|
||||
row.source && !sent && row.from !== HUMAN ? muteFace(row.source, row.from) : null,
|
||||
h("button", {type: "button", class: "radio-pick", "aria-haspopup": "dialog", title: first},
|
||||
when(row.ts),
|
||||
h("span", {class: "radio-dir", role: "img", ...named(label)}, icon(name)),
|
||||
@@ -73,10 +74,26 @@
|
||||
for (const node of [...kept.children].filter((child) => child !== pick)) {
|
||||
node.remove();
|
||||
}
|
||||
kept.append(...[...fresh.children].filter((child) => child !== twin));
|
||||
const parts = [...fresh.children];
|
||||
const at = parts.indexOf(twin);
|
||||
pick.before(...parts.slice(0, at));
|
||||
pick.after(...parts.slice(at + 1));
|
||||
return kept;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} key the sender's session key.
|
||||
* @param {string} name the sender's name.
|
||||
* @returns {Element} the sender's avatar as a button that mutes or unmutes the sender on the radio, without opening the row.
|
||||
*/
|
||||
function muteFace(key, name) {
|
||||
const muted = radioSet.muted.includes(key);
|
||||
return h("button", {type: "button", class: "radio-mute", "aria-pressed": String(muted), ...named(`Mute ${name}`, muted ? `Muted: a press lets the radio read ${name} aloud again` : `Mute ${name}: the radio stops reading this agent aloud`), on: {click: (event) => {
|
||||
event.stopPropagation();
|
||||
keepRadio(RadioSet.muting(radioSet, key));
|
||||
}}}, face(key, false));
|
||||
}
|
||||
|
||||
function patchList(list, lines) {
|
||||
const before = [...list.children];
|
||||
const focused = before.find((node) => node.contains(document.activeElement)) || null;
|
||||
@@ -188,7 +205,7 @@
|
||||
|
||||
function drawLog() {
|
||||
const entry = radioSet.log;
|
||||
const sig = JSON.stringify([state.radio.length, state.radio.length ? state.radio[state.radio.length - 1].ts : 0, state.messages.length, Receipts.signature(state.radio), Receipts.signature(state.messages), entry, Math.floor(Date.now() / 60000)]);
|
||||
const sig = JSON.stringify([state.radio.length, state.radio.length ? state.radio[state.radio.length - 1].ts : 0, state.messages.length, Receipts.signature(state.radio), Receipts.signature(state.messages), entry, radioSet.muted, Math.floor(Date.now() / 60000)]);
|
||||
for (const dom of liveParts("logs")) {
|
||||
if (sig !== dom.sig) {
|
||||
dom.sig = sig;
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
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 MODE_LABELS = {
|
||||
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 fallback picked under Read aloud, never speech; MAYDAY, PAN-PAN and Sécurité still sound their procedure word"],
|
||||
auto: ["bi-volume-up", "Auto", "Auto: speech while the host CPU lies below the threshold, otherwise the fallback; press Auto again to pick the fallback"],
|
||||
quiet: ["bi-soundwave", "Quiet", "Quiet: the fallback, never speech; press Quiet again to pick it; 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; press Morse again to set the 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 MODE_MENUS = {auto: () => fallbackPick(), quiet: () => fallbackPick(), morse: () => morseSpeed()};
|
||||
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 BELLS = {off: ["bi-bell-slash", "off"], tone: ["bi-bell", "tone only"], speak: ["bi-megaphone", "tone and read aloud"]};
|
||||
const radioParts = {devices: [], logs: [], speaks: []};
|
||||
const liveParts = (kind) => radioParts[kind].filter((part) => part.root.isConnected);
|
||||
|
||||
function voiceReplay(note) {
|
||||
@@ -131,14 +133,23 @@
|
||||
return {input, value, name, row: h("div", {class: "knob-row", title: hint}, name, input, value)};
|
||||
}
|
||||
|
||||
function radioCheck(tone, line) {
|
||||
say({steps: [{kind: "speech", text: state.speech.sample}], voice: state.speech.operator, tone, cls: "newsletter", who: HUMAN, sent: true, line});
|
||||
}
|
||||
|
||||
function testTone(id, label) {
|
||||
play(id, loudness(id));
|
||||
if (state.speech.tts && RadioSet.bell(radioSet, id) === "speak") {
|
||||
radioCheck(id, `${label} test`);
|
||||
}
|
||||
}
|
||||
|
||||
function toneKnob(id, label) {
|
||||
const toggle = h("button", {type: "button", class: "btn small ghost icon-only knob-toggle", "aria-pressed": "false", ...named(`${label} tone`), on: {click: () => {
|
||||
keepRadio({sounds: {...radioSet.sounds, [id]: {...radioSet.sounds[id], on: !radioSet.sounds[id].on}}});
|
||||
}}});
|
||||
const toggle = h("button", {type: "button", class: "btn small ghost icon-only knob-toggle", "aria-pressed": "false", ...named(`${label} tone`), on: {click: () => keepRadio(RadioSet.ring(radioSet, id))}});
|
||||
const level = knob(label, `${label}: tone volume; speech and the burst of these rows play at it`, {min: 0, max: 1, step: 0.05}, (volume) => {
|
||||
keepRadio({sounds: {...radioSet.sounds, [id]: {...radioSet.sounds[id], volume}}});
|
||||
});
|
||||
const test = iconBtn("bi-play-fill", `Test ${label}`, "btn small ghost knob-test", () => play(id, loudness(id)), `Test: play the ${label} tone`);
|
||||
const test = iconBtn("bi-play-fill", `Test ${label}`, "btn small ghost knob-test", () => testTone(id, label), `Test: play the ${label} tone, while it reads aloud also a spoken line`);
|
||||
level.row.prepend(toggle);
|
||||
level.row.append(test);
|
||||
return {id, toggle, level};
|
||||
@@ -164,9 +175,51 @@
|
||||
squelch.row.append(iconBtn("bi-play-fill", "Test Squelch", "btn small ghost knob-test", () => say({steps: [{kind: "burst"}], voice: "", tone: "radio", cls: "post", who: HUMAN, sent: true, line: "squelch test"}), "Test: play the burst of a radio row, at the All radio volume times the squelch"));
|
||||
const threshold = knob("Threshold", "Speech threshold: the hub renders new speech only while the host CPU lies below it, always at 100 %, never at 0 %; your passkey signs each change", RadioSet.GATE, (value) => drawGate(threshold, value));
|
||||
threshold.input.addEventListener("change", (event) => setThreshold(Number(event.target.value)));
|
||||
const check = iconBtn("bi-broadcast", "Radio check", "btn small ghost radio-check", () => say({steps: [{kind: "speech", text: state.speech.sample}], voice: state.speech.operator, tone: "direct", cls: "newsletter", who: HUMAN, sent: true, line: "radio check"}), "Radio check: hear the operator's voice once");
|
||||
const check = iconBtn("bi-play-fill", "Radio check", "btn small ghost knob-test radio-check", () => radioCheck("direct", "radio check"), "Radio check: hear the operator's voice once at these settings");
|
||||
check.disabled = !state.speech.tts;
|
||||
return {tones, squelch, threshold, check, rows: [...tones.map((tone) => tone.level.row), squelch.row, threshold.row]};
|
||||
threshold.row.append(check);
|
||||
return {tones, squelch, threshold, rows: [...tones.map((tone) => tone.level.row), squelch.row, threshold.row]};
|
||||
}
|
||||
|
||||
function fallbackPick() {
|
||||
return 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"),
|
||||
RadioSet.FALLBACKS.map((id) => h("button", {type: "button", class: "chip", "aria-pressed": String(radioSet.fallback === id), ...named(FALLBACK_LABELS[id][0], FALLBACK_LABELS[id][1]), on: {click: () => keepRadio({fallback: id})}}, FALLBACK_LABELS[id][0])));
|
||||
}
|
||||
|
||||
function pressMode(part, id) {
|
||||
if (radioSet.mode === id && MODE_MENUS[id]) {
|
||||
part.menuFor = part.menuFor === id ? "" : id;
|
||||
drawModeMenu(part);
|
||||
return;
|
||||
}
|
||||
part.menuFor = "";
|
||||
keepRadio({mode: id});
|
||||
context();
|
||||
}
|
||||
|
||||
function drawModeMenu(part) {
|
||||
const {menu, modes} = part.face;
|
||||
if (part.menuFor !== radioSet.mode) {
|
||||
part.menuFor = "";
|
||||
}
|
||||
for (const button of modes.querySelectorAll("button[data-mode]")) {
|
||||
if (MODE_MENUS[button.dataset.mode]) {
|
||||
button.setAttribute("aria-expanded", String(part.menuFor === button.dataset.mode));
|
||||
}
|
||||
}
|
||||
const sig = JSON.stringify([part.menuFor, radioSet.fallback, settings.morse.wpm]);
|
||||
if (sig !== part.menuSig) {
|
||||
part.menuSig = sig;
|
||||
menu.replaceChildren(...(part.menuFor ? [MODE_MENUS[part.menuFor]()] : []));
|
||||
menu.hidden = !part.menuFor;
|
||||
}
|
||||
}
|
||||
|
||||
function redrawModeMenus() {
|
||||
for (const part of liveParts("devices")) {
|
||||
part.menuSig = "";
|
||||
drawModeMenu(part);
|
||||
}
|
||||
}
|
||||
|
||||
function faceplate(part) {
|
||||
@@ -176,49 +229,22 @@
|
||||
const caption = h("div", {class: "radio-caption", role: "status", "aria-live": "polite", hidden: true});
|
||||
const modes = h("div", {class: "segmented radio-modes", role: "group", "aria-label": "Mode"}, RadioSet.MODES.map((id) => {
|
||||
const [name, label, hint] = MODE_LABELS[id];
|
||||
return h("button", {type: "button", "data-mode": id, "aria-pressed": "false", ...named(label, hint), on: {click: () => {
|
||||
keepRadio({mode: id});
|
||||
context();
|
||||
}}}, icon(name), label);
|
||||
return h("button", {type: "button", "data-mode": id, "aria-pressed": "false", ...named(label, hint), on: {click: () => pressMode(part, id)}},
|
||||
icon(name), label, MODE_MENUS[id] ? h("span", {class: "mode-caret", "aria-hidden": "true"}, "▾") : null);
|
||||
}));
|
||||
part.face = {lamp, cls, mode, cpu, caption, modes};
|
||||
part.knobs = knobs();
|
||||
const menu = h("div", {class: "radio-mode-menu", hidden: true});
|
||||
Object.assign(part, {face: {lamp, cls, mode, cpu, caption, modes, menu}, menuFor: "", menuSig: "", knobs: knobs()});
|
||||
const display = h("div", {class: "radio-display", role: "group", "aria-label": "Display"}, lamp, cls, mode, cpu);
|
||||
return h("div", {class: "radio-face", role: "group", "aria-label": "Radio set"}, display, caption, modes, part.knobs.check,
|
||||
return h("div", {class: "radio-face", role: "group", "aria-label": "Radio set"}, display, caption, modes, menu,
|
||||
h("div", {class: "radio-knobs", role: "group", "aria-label": "Knobs"}, part.knobs.rows));
|
||||
}
|
||||
|
||||
function toggleGear(part) {
|
||||
const open = part.box.hidden;
|
||||
part.box.replaceChildren(...(open ? [radioFilters()] : []));
|
||||
part.box.hidden = !open;
|
||||
part.gear.setAttribute("aria-expanded", String(open));
|
||||
window.requestAnimationFrame(refresh3d);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {boolean} spot whether the bar heads the radio spot.
|
||||
* @returns {object} the bar part: root, gear, its box and the Cancel mayday button.
|
||||
* @returns {object} the bar part with its root.
|
||||
*/
|
||||
function radioBar(spot) {
|
||||
const part = {box: h("div", {class: "radio-gear", id: spot ? "radio-gear" : null, hidden: true})};
|
||||
part.gear = iconBtn("bi-funnel", "Read aloud", "btn small ghost spot-toggle", () => toggleGear(part), "Read aloud: the classes and agents the radio sounds for");
|
||||
part.gear.setAttribute("aria-expanded", "false");
|
||||
if (spot) {
|
||||
part.gear.setAttribute("aria-controls", "radio-gear");
|
||||
}
|
||||
const [, label, , hint] = actionOf("clear-mayday");
|
||||
part.clear = iconBtn("bi-life-preserver", label, "btn small danger", () => confirmAct("clear-mayday", []), hint);
|
||||
part.clear.disabled = !state.silence;
|
||||
part.root = h("div", {class: "spot-bar", "data-star-slot": ""}, h("div", {class: "spot-head"}, spot ? h("h3", {class: "group-title"}, "Radio") : null, h("span", {class: "spacer"}), part.gear, part.clear), part.box);
|
||||
radioParts.bars.push(part);
|
||||
return part;
|
||||
}
|
||||
|
||||
function drawBars() {
|
||||
for (const part of liveParts("bars")) {
|
||||
part.clear.disabled = !state.silence;
|
||||
}
|
||||
return {root: h("div", {class: "spot-bar", "data-star-slot": ""}, h("div", {class: "spot-head"}, spot ? h("h3", {class: "group-title"}, "Radio") : null, h("span", {class: "spacer"})))};
|
||||
}
|
||||
|
||||
function cardHead(title, ...tools) {
|
||||
@@ -270,8 +296,8 @@
|
||||
}
|
||||
|
||||
function speakCard() {
|
||||
const {form, recipient, text, channel} = composerForm();
|
||||
const part = {recipient, text, channel, names: ""};
|
||||
const {form, recipient, text, channel, clear} = composerForm();
|
||||
const part = {recipient, text, channel, clear, names: ""};
|
||||
part.root = h("section", {class: "radio-card radio-speak", "data-panel": "radio-speak", "aria-label": "Speak"}, cardHead("Speak"), form);
|
||||
radioParts.speaks.push(part);
|
||||
return part;
|
||||
@@ -281,6 +307,7 @@
|
||||
const names = agentNames();
|
||||
const sig = JSON.stringify(names);
|
||||
for (const part of liveParts("speaks")) {
|
||||
part.clear.hidden = !state.silence;
|
||||
if (sig !== part.names) {
|
||||
part.names = sig;
|
||||
const chosen = part.recipient.value;
|
||||
@@ -289,47 +316,20 @@
|
||||
}
|
||||
}
|
||||
|
||||
function radioFilters() {
|
||||
const chip = (label, pressed, hint, run, locked) => h("button", {type: "button", class: "chip", "aria-pressed": String(pressed), disabled: locked, ...named(label, hint), on: {click: run}}, label);
|
||||
const classes = SPEECH_CLASSES.map(([id, label]) => chip(label, radioSet.classes.includes(id), id === "mayday" ? "MAYDAY always sounds" : `Read ${label} aloud`, () => {
|
||||
keepRadio({classes: radioSet.classes.includes(id) ? radioSet.classes.filter((name) => name !== id) : [...radioSet.classes, id]});
|
||||
redrawFilters();
|
||||
}, id === "mayday"));
|
||||
const agents = Object.entries(people()).sort(([, a], [, b]) => a.now.localeCompare(b.now)).map(([key, entry]) => chip(entry.now, !radioSet.muted.includes(key), `Read ${entry.now} aloud`, () => {
|
||||
keepRadio({muted: radioSet.muted.includes(key) ? radioSet.muted.filter((name) => name !== key) : [...radioSet.muted, key]});
|
||||
redrawFilters();
|
||||
}, 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"},
|
||||
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),
|
||||
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());
|
||||
}
|
||||
|
||||
function redrawFilters() {
|
||||
for (const part of liveParts("bars")) {
|
||||
if (!part.box.hidden) {
|
||||
part.box.replaceChildren(radioFilters());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawRadioSet() {
|
||||
for (const part of liveParts("devices")) {
|
||||
for (const button of part.face.modes.querySelectorAll("button[data-mode]")) {
|
||||
button.setAttribute("aria-pressed", String(button.dataset.mode === radioSet.mode));
|
||||
}
|
||||
drawModeMenu(part);
|
||||
const {tones, squelch, threshold} = part.knobs;
|
||||
for (const {id, toggle, level} of tones) {
|
||||
const sound = radioSet.sounds[id];
|
||||
toggle.setAttribute("aria-pressed", String(sound.on));
|
||||
toggle.replaceChildren(icon(sound.on ? "bi-bell" : "bi-bell-slash"));
|
||||
toggle.title = `${toggle.getAttribute("aria-label")}: ${sound.on ? "on, a press mutes it" : "off, a press turns it on"}`;
|
||||
const bell = RadioSet.bell(radioSet, id);
|
||||
toggle.setAttribute("aria-pressed", String(bell !== "off"));
|
||||
toggle.dataset.bell = bell;
|
||||
toggle.replaceChildren(icon(BELLS[bell][0]));
|
||||
toggle.title = `${toggle.getAttribute("aria-label")}: ${BELLS[bell][1]}; each press moves on: ${RadioSet.SPOKEN[id].length ? "off, tone, read aloud" : "off, tone"}`;
|
||||
level.input.value = String(sound.volume);
|
||||
level.value.textContent = sound.volume.toFixed(2);
|
||||
}
|
||||
@@ -346,7 +346,6 @@
|
||||
drawRadioSet();
|
||||
drawStations();
|
||||
drawSpeak();
|
||||
drawBars();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,6 +7,7 @@ const RadioSet = (() => {
|
||||
const FRAME = {bytes: 140, prefix: 8, key: 64};
|
||||
const TONES = ["mayday", "review", "direct", "radio"];
|
||||
const CLASSES = ["post", "call", "newsletter", "broadcast", "mayday", "pan-pan", "security"];
|
||||
const SPOKEN = {mayday: ["mayday", "pan-pan", "security"], review: [], direct: ["post", "call"], radio: ["newsletter", "broadcast"]};
|
||||
const TO_ALL = new Set(["newsletter", "broadcast", "mayday", "pan-pan", "security"]);
|
||||
const TABS = ["sent", "received", "all"];
|
||||
const CHIPS = ["class", "from", "to", "agent"];
|
||||
@@ -78,6 +79,37 @@ const RadioSet = (() => {
|
||||
return row.class === "mayday" || (set.classes.includes(row.class) && !set.muted.includes(row.source));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} set the radio set.
|
||||
* @param {string} tone one of TONES.
|
||||
* @returns {string} the bell of that row: off while its tone is off, speak while every class it speaks is read aloud, else tone.
|
||||
*/
|
||||
function bell(set, tone) {
|
||||
if (!set.sounds[tone].on) {
|
||||
return "off";
|
||||
}
|
||||
return SPOKEN[tone].length && SPOKEN[tone].every((name) => set.classes.includes(name)) ? "speak" : "tone";
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} set the radio set.
|
||||
* @param {string} tone one of TONES.
|
||||
* @returns {object} the change of sounds and classes that moves the row's bell on: off to tone to speak to off, a row that speaks no class skips speak.
|
||||
*/
|
||||
function ring(set, tone) {
|
||||
const now = bell(set, tone);
|
||||
const next = now === "off" ? "tone" : now === "tone" && SPOKEN[tone].length ? "speak" : "off";
|
||||
const rest = set.classes.filter((name) => !SPOKEN[tone].includes(name));
|
||||
return {
|
||||
sounds: {...set.sounds, [tone]: {...set.sounds[tone], on: next !== "off"}},
|
||||
classes: next === "speak" ? [...rest, ...SPOKEN[tone]] : rest,
|
||||
};
|
||||
}
|
||||
|
||||
function muting(set, key) {
|
||||
return {muted: set.muted.includes(key) ? set.muted.filter((name) => name !== key) : [...set.muted, key]};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} row a radio row of the state with class, called, speaker, pitch and text.
|
||||
* @returns {object} the whole row keyed in Morse as kind "morse", sign, joined, text and pitch: the class prosign, or the called stations of a call, then DE with the sender's clear name and the full text without the hub's message mark, in the sender's pitch.
|
||||
@@ -272,7 +304,7 @@ const RadioSet = (() => {
|
||||
return {...entry, chips: Object.fromEntries(CHIPS.map((name) => [name, ""])), q: ""};
|
||||
}
|
||||
|
||||
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};
|
||||
return {KEY, MODES, FALLBACKS, KEYED, FRAME, TONES, CLASSES, SPOKEN, TABS, CHIPS, DEFAULTS, GATE, PROSIGNS, valid, picked, bell, ring, muting, frames, standIn, plan, burst, gateLabel, toAll, ledgerOf, logRows, counts, choices, cleared};
|
||||
})();
|
||||
if (typeof module === "object" && module.exports) {
|
||||
module.exports = RadioSet;
|
||||
|
||||
@@ -59,7 +59,7 @@ svg .presence-dot { fill: var(--panel); stroke: currentColor; stroke-width: 1; }
|
||||
.spot-toggle[aria-expanded="true"] { background: var(--accent-soft); color: var(--accent); }
|
||||
.radio-spot, .radio-home { container: radio / inline-size; min-width: 0; }
|
||||
.radio-spot { display: grid; gap: var(--sp-3); margin-bottom: var(--sp-4); padding: var(--sp-3); }
|
||||
.radio-spot[hidden], .radio-gear[hidden] { display: none; }
|
||||
.radio-spot[hidden], .radio-mode-menu[hidden] { display: none; }
|
||||
body.fit .spot-host { flex: none; }
|
||||
.spot-bar { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; }
|
||||
.spot-head { display: flex; flex: 1; flex-wrap: wrap; align-items: center; gap: var(--sp-2); min-width: 0; }
|
||||
@@ -67,7 +67,6 @@ body.fit .spot-host { flex: none; }
|
||||
.night-picks:empty { display: none; }
|
||||
.agent-night { align-items: center; margin: 0 0 var(--sp-2); }
|
||||
.spot-bar { position: relative; }
|
||||
.radio-gear { position: absolute; top: calc(100% + var(--sp-1)); right: 0; z-index: 12; width: min(36rem, 100%); min-width: 0; padding: var(--sp-3); border: 1px solid var(--line-strong); border-radius: var(--radius); background: var(--glass-card); box-shadow: var(--shadow-lift); -webkit-backdrop-filter: var(--blur); backdrop-filter: var(--blur); }
|
||||
.radio-grid { display: grid; grid-template-columns: clamp(22rem, 100% - 34rem - var(--sp-3), 26rem) minmax(0, 1fr); gap: var(--sp-3); min-width: 0; }
|
||||
.radio-column { display: flex; flex-direction: column; gap: var(--sp-3); min-width: 0; min-height: 0; }
|
||||
.radio-card { display: flex; flex-direction: column; gap: var(--sp-2); min-width: 0; padding: var(--sp-3); border: 1px solid var(--line); border-radius: var(--radius); background: var(--sunken); }
|
||||
@@ -81,7 +80,11 @@ body.fit .spot-host { flex: none; }
|
||||
.composer [hidden] { display: none; }
|
||||
.composer .actions { flex-wrap: wrap; align-items: center; margin-top: 0; }
|
||||
.composer-hint { flex: 1 1 14em; min-width: 0; margin: 0; font-size: var(--fs-xs); }
|
||||
.composer .ptt { margin-inline-start: auto; }
|
||||
.composer .ptt-split { display: inline-flex; margin-inline-start: auto; }
|
||||
.ptt-split > .ptt { border-start-end-radius: 0; border-end-end-radius: 0; }
|
||||
.ptt-menu > summary.ptt-more { height: 100%; padding-inline: 6px; border-inline-start: 1px solid color-mix(in srgb, currentColor 30%, transparent); border-start-start-radius: 0; border-end-start-radius: 0; list-style: none; }
|
||||
.ptt-menu > summary.ptt-more::-webkit-details-marker { display: none; }
|
||||
.radio-cancel[hidden] { display: none; }
|
||||
.composer-status { min-width: 0; overflow-wrap: anywhere; }
|
||||
.voice-note { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); }
|
||||
.voice-replay { max-width: 100%; height: 34px; }
|
||||
@@ -89,8 +92,12 @@ body.fit .spot-host { flex: none; }
|
||||
.mini .voice-replay, .bubble .voice-replay, .radio-row .voice-replay, .popup-box .voice-replay { width: 100%; }
|
||||
.radio-face { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: var(--sp-2); min-width: 0; }
|
||||
.radio-face > * { grid-column: 1 / -1; }
|
||||
.radio-face > .radio-modes { grid-column: 1; justify-self: start; }
|
||||
.radio-face > .radio-check { grid-column: 2; align-self: center; }
|
||||
.radio-face > .radio-modes { justify-self: start; }
|
||||
.mode-caret { display: none; margin-inline-start: -2px; font-size: .8em; }
|
||||
.radio-modes button[aria-pressed="true"] > .mode-caret { display: inline; }
|
||||
.radio-mode-menu { display: grid; gap: var(--sp-2); padding: var(--sp-2); border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--panel); }
|
||||
.radio-mode-menu .chips { margin-bottom: 0; }
|
||||
.knob-toggle[data-bell="speak"] { background: var(--accent-soft); color: var(--accent); }
|
||||
.radio-display { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2) var(--sp-3); min-width: 0; padding: 5px var(--sp-3); border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--panel); font-family: var(--mono); font-size: var(--fs-sm); font-variant-numeric: tabular-nums; }
|
||||
.radio-field { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.radio-field[data-field="class"] { font-weight: 700; }
|
||||
@@ -110,8 +117,6 @@ body.fit .spot-host { flex: none; }
|
||||
.knob { grid-column: 3; width: 100%; min-width: 0; margin: 0; accent-color: var(--accent); }
|
||||
.knob-value { grid-column: 4; font-family: var(--mono); font-variant-numeric: tabular-nums; text-align: right; white-space: nowrap; }
|
||||
.knob-test { grid-column: 5; }
|
||||
.radio-read { display: grid; gap: var(--sp-2); }
|
||||
.radio-read .chips { margin-bottom: 0; }
|
||||
.radio-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 .knob { flex: 1 1 8rem; width: auto; }
|
||||
@@ -143,6 +148,11 @@ body.fit .spot-host { flex: none; }
|
||||
.radio-row.picked { box-shadow: inset 3px 0 0 var(--accent); }
|
||||
.radio-pick { display: flex; flex: 1 1 auto; align-items: center; gap: var(--sp-2); min-width: 0; height: 100%; padding: 0 0 0 8px; overflow: hidden; border: 0; border-radius: var(--radius-sm); background: transparent; color: inherit; font: inherit; line-height: 20px; text-align: left; white-space: nowrap; cursor: pointer; }
|
||||
.radio-pick > * { flex: none; }
|
||||
.radio-mute { display: inline-flex; flex: none; margin-inline-start: 6px; padding: 0; border: 0; border-radius: 50%; background: none; cursor: pointer; }
|
||||
.radio-mute .avatar { width: 22px; height: 22px; }
|
||||
.radio-mute[aria-pressed="true"] .avatar { filter: grayscale(1); opacity: .45; }
|
||||
.radio-mute[aria-pressed="true"]::after { content: "🔇"; margin-inline-start: -8px; font-size: 10px; line-height: 1; align-self: flex-end; }
|
||||
.radio-row:has(> .radio-mute) > .radio-pick { padding-inline-start: 0; }
|
||||
.radio-row time { color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
.radio-dir { display: inline-flex; color: var(--muted); }
|
||||
.radio-row[data-dir="sent"] .radio-dir { color: var(--accent); }
|
||||
@@ -213,7 +223,7 @@ body.fit .spot-host { flex: none; }
|
||||
.radio-spot .radio-column { gap: 4px; }
|
||||
.radio-spot .radio-card { gap: 4px; padding: 4px var(--sp-2); }
|
||||
.radio-spot .radio-card-head { min-height: 24px; }
|
||||
.radio-spot .radio-card-head > .star, .radio-spot .knob-row .btn, .radio-spot .radio-check, .radio-spot .radio-filters .btn { padding-block: 2px; }
|
||||
.radio-spot .radio-card-head > .star, .radio-spot .knob-row .btn, .radio-spot .radio-filters .btn { padding-block: 2px; }
|
||||
.radio-spot .radio-device { display: grid; grid-template-columns: auto auto minmax(0, max-content) minmax(0, 1fr) auto auto; align-content: start; gap: 4px var(--sp-2); }
|
||||
.radio-spot .radio-device > :is(.radio-card-head, .radio-face) { display: contents; }
|
||||
.radio-spot .radio-device > .radio-card-head > .group-title { grid-area: 1 / 1; margin: 0; }
|
||||
@@ -224,10 +234,10 @@ body.fit .spot-host { flex: none; }
|
||||
.radio-spot .radio-caption .caption-line { flex: 1 0 4rem; }
|
||||
.radio-spot .radio-caption .avatar { width: 20px; height: 20px; }
|
||||
.radio-spot .radio-caption .btn { padding: 4px; }
|
||||
.radio-spot .radio-modes { grid-area: 2 / 1 / 3 / 6; justify-self: start; padding: 1px; }
|
||||
.radio-spot .radio-modes { grid-area: 2 / 1 / 3 / -1; justify-self: start; padding: 1px; }
|
||||
.radio-spot .radio-modes button { padding-block: 2px; }
|
||||
.radio-spot .radio-check { grid-area: 2 / 6; }
|
||||
.radio-spot .radio-knobs { grid-area: 3 / 1 / 4 / -1; row-gap: 0; }
|
||||
.radio-spot .radio-mode-menu { grid-column: 1 / -1; padding: 4px var(--sp-2); }
|
||||
.radio-spot .radio-knobs { grid-column: 1 / -1; row-gap: 0; }
|
||||
.radio-spot .knob-row { min-height: 24px; }
|
||||
.radio-spot .radio-device > .radio-station { grid-column: 1 / -1; padding-top: 4px; }
|
||||
.radio-spot .radio-station > summary { min-height: 24px; }
|
||||
|
||||
@@ -228,7 +228,7 @@ def resolves(where: str, ref: str) -> bool:
|
||||
|
||||
|
||||
def task_of(rasci: ModuleType, slug: str) -> str:
|
||||
if not rasci.TASK.match(slug):
|
||||
if not rasci.TASK.fullmatch(slug):
|
||||
fail(f"invalid slug {slug!r}; use lowercase letters, digits, '.', '_', '-' and '/'")
|
||||
return PREFIX + slug
|
||||
|
||||
|
||||
@@ -38,7 +38,11 @@ before reporting it: one copy-pasteable command, its absolute directory, and
|
||||
why no agent can run it. The row gets the operator as R, your session as A,
|
||||
status `queued`. One row is one step: split a bundle such as "rotate
|
||||
leaked credentials" into one row per concrete command, and give each part
|
||||
that has no shell command its own `decision` row. Pick its check from
|
||||
that has no shell command its own `decision` row: the question as
|
||||
`--command`, each answer as `--option "<label>=<what it means>"`, your pick
|
||||
as `--recommended`; the hub shows them as buttons, and the answer reaches
|
||||
the row's A as a passkey-signed post `Decision <task>` / `Answer: <answer>`
|
||||
to check with `operator_message` before acting. Pick its check from
|
||||
`checks.md` next to this file: the strongest kind that proves the step done,
|
||||
never a shell command.
|
||||
|
||||
|
||||
@@ -15,9 +15,14 @@ Environment:
|
||||
|
||||
Args:
|
||||
add <slug> --dir <abs dir> --command "<cmd>" --reason "<why>"
|
||||
--check <kind>[:<arg>] [--session <id>]: record a command, or update
|
||||
--check <kind>[:<arg>] [--option "<label>=<description>" ...]
|
||||
[--recommended <label>] [--session <id>]: record a command, or update
|
||||
the row of that slug, as queued with Operator R and the adder A, its
|
||||
session id under `sessions`.
|
||||
session id under `sessions`. --option, only with --check decision
|
||||
and at most OPTION_LIMIT times, gives the answers the Agent
|
||||
Orchestrator shows as buttons beside a free answer; the operator's
|
||||
pick arrives as a signed post to the adder. --recommended names one
|
||||
of them.
|
||||
Kinds, never a shell command:
|
||||
pushed:<repo dir> `git rev-list --count @{u}..HEAD` is 0 there;
|
||||
no upstream counts as open.
|
||||
@@ -168,6 +173,8 @@ INTERRUPTED = 130
|
||||
SUDO = re.compile(r"\bsudo\b")
|
||||
PREFIX = "operator/"
|
||||
KINDS = ("pushed", "installed", "binary", "absent", "manual", "decision")
|
||||
OPTION_LIMIT = 12
|
||||
LABEL_LIMIT = 80
|
||||
OPEN = ("queued", "blocked")
|
||||
META = re.compile(r"[\s|&;()<>$`\\\"'*?\[\]{}~!#]")
|
||||
NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]*$")
|
||||
@@ -201,7 +208,7 @@ def module(name: str, path: Path) -> ModuleType:
|
||||
|
||||
|
||||
def task_of(rasci: ModuleType, slug: str) -> str:
|
||||
if not rasci.TASK.match(slug):
|
||||
if not rasci.TASK.fullmatch(slug):
|
||||
fail(f"invalid slug {slug!r}; use lowercase letters, digits, '.', '_', '-' and '/'")
|
||||
return PREFIX + slug
|
||||
|
||||
@@ -299,6 +306,41 @@ def cell(text: object) -> str:
|
||||
return visible(" ".join(str(text).split()), "").replace("|", "\\|")
|
||||
|
||||
|
||||
def choices(raw: list[str] | None, recommended: str | None, check: str) -> list[dict]:
|
||||
"""Args:
|
||||
raw: the --option values, each "<label>=<description>" or "<label>".
|
||||
recommended: the --recommended label, or None.
|
||||
check: the row's --check kind.
|
||||
|
||||
Returns:
|
||||
[{"label", "description"}] in the given order; [] without options.
|
||||
Exits 2 when options come with another check than decision, exceed
|
||||
OPTION_LIMIT, repeat a label, hold an empty, multi-line or longer
|
||||
than LABEL_LIMIT label, or when --recommended names no option.
|
||||
"""
|
||||
if not raw:
|
||||
if recommended:
|
||||
fail("--recommended needs --option")
|
||||
return []
|
||||
if check != "decision":
|
||||
fail("--option is only for --check decision")
|
||||
if len(raw) > OPTION_LIMIT:
|
||||
fail(f"at most {OPTION_LIMIT} --option values")
|
||||
options = []
|
||||
for text in raw:
|
||||
label, _, description = text.partition("=")
|
||||
label = label.strip()
|
||||
if not label or not label.isprintable() or len(label) > LABEL_LIMIT:
|
||||
fail(f"--option {text!r} needs a label of one line and at most {LABEL_LIMIT} characters before the =")
|
||||
options.append({"label": label, "description": " ".join(description.split())})
|
||||
labels = [option["label"] for option in options]
|
||||
if len(set(labels)) != len(labels):
|
||||
fail("--option labels must be distinct")
|
||||
if recommended and recommended not in labels:
|
||||
fail(f"--recommended {recommended!r} names none of {', '.join(labels)}")
|
||||
return options
|
||||
|
||||
|
||||
def cmd_add(rasci: ModuleType, args: argparse.Namespace) -> int:
|
||||
task = task_of(rasci, args.slug)
|
||||
for error in (path_problem(args.dir, "--dir"), problem(args.check)):
|
||||
@@ -313,6 +355,7 @@ def cmd_add(rasci: ModuleType, args: argparse.Namespace) -> int:
|
||||
refused = None if args.check == "decision" else unrunnable(command, args.dir)
|
||||
if refused:
|
||||
fail(f"--command {command!r} {refused}; write the real command, or record the step with --check decision")
|
||||
options = choices(args.option, args.recommended, args.check)
|
||||
council = module("council", rasci.COUNCIL)
|
||||
sid, _ = council.caller(args.session)
|
||||
party = council.live_sessions().get(sid) or sid
|
||||
@@ -322,8 +365,10 @@ def cmd_add(rasci: ModuleType, args: argparse.Namespace) -> int:
|
||||
entry = tasks.setdefault(task, {})
|
||||
entry.setdefault("seq", seq)
|
||||
entry.update(title=command, workdir=args.dir, description=reason, check=args.check)
|
||||
entry.pop("cancelled", None)
|
||||
entry.pop("failed", None)
|
||||
for name in ("cancelled", "failed", "options", "recommended"):
|
||||
entry.pop(name, None)
|
||||
if options:
|
||||
entry.update(options=options, recommended=args.recommended or "")
|
||||
roles = {p: v.replace("A", "") for p, v in entry.get("roles", {}).items()}
|
||||
roles[rasci.OPERATOR] = rasci.letters_of(roles.get(rasci.OPERATOR, ""), "R")
|
||||
roles[party] = rasci.letters_of(roles.get(party, ""), "A")
|
||||
@@ -1011,6 +1056,8 @@ def main() -> int:
|
||||
p.add_argument("slug")
|
||||
for flag in ("--dir", "--command", "--reason", "--check"):
|
||||
p.add_argument(flag, required=True)
|
||||
p.add_argument("--option", action="append")
|
||||
p.add_argument("--recommended")
|
||||
p.add_argument("--session")
|
||||
p.set_defaults(func=cmd_add)
|
||||
p = sub.add_parser("list")
|
||||
|
||||
@@ -55,7 +55,7 @@ def fail(message: str) -> None:
|
||||
|
||||
|
||||
def check_task(task: str) -> None:
|
||||
if not TASK.match(task):
|
||||
if not TASK.fullmatch(task):
|
||||
fail(f"invalid task {task!r}; use a slug like work/<slug>")
|
||||
|
||||
|
||||
|
||||
@@ -43,7 +43,8 @@ Merge duplicates and drop items a command can settle (those go to
|
||||
- **Agent Orchestrator**: when an operator message that `operator_message`
|
||||
verified asks "send me your open decisions as choices", send each item
|
||||
through the MCP tool `decision_request` (question, options, your agent
|
||||
name, the recommended label); it shows as a choice card under "Waits on
|
||||
name, the recommended label; an option that needs a visual comparison
|
||||
carries a `preview`); it shows as a choice card under "Waits on
|
||||
Operator". `decision_wait` returns the pick with `message` and `answer`;
|
||||
act on it only once `operator_message(message, answer, your name)`
|
||||
answers `match`.
|
||||
|
||||
@@ -58,8 +58,10 @@ INBOX_PICK = """(async () => {@HELPERS@
|
||||
const focused = Boolean(holder && text(holder.querySelector(".command code")) === title && document.activeElement.checked);
|
||||
all("#main .inbox-list > li").find((li) => li.textContent.includes("pick a name")).querySelector("input").click();
|
||||
await sleep(300);
|
||||
const buttons = all("#main .inbox-actions button").map(name);
|
||||
all("#main .inbox-actions button").find((button) => name(button).startsWith("Deny selection")).click();
|
||||
const buttons = all("#grant-bar .grant-split button").map(name);
|
||||
document.querySelector("#grant-bar details.grant-menu > summary").click();
|
||||
await until(() => document.querySelector("#grant-bar details.grant-menu[open]"), 2000);
|
||||
all("#grant-bar .grant-split button").find((button) => name(button).startsWith("Deny selection")).click();
|
||||
await until(() => document.querySelector(".sheet-box .actions"), 4000);
|
||||
const listed = all(".sheet-box ul.mini > li strong").map(text);
|
||||
const reason = document.querySelector(".sheet-box .deny-reason textarea");
|
||||
|
||||
+29
-37
@@ -229,9 +229,9 @@ CLEAR_MAYDAY = """(async () => {@HELPERS@
|
||||
};
|
||||
await until(() => document.querySelector('#main [role="toolbar"]'), 8000);
|
||||
const toolbar = all('#main [role="toolbar"] button, #main [role="toolbar"] summary').map(name);@SPOT_OPEN@
|
||||
const button = await until(() => spot && all(".spot-head button", spot).find((node) => name(node) === "Cancel mayday" && !node.disabled), 8000);
|
||||
const button = await until(() => spot && all("form.composer .radio-cancel", spot).find((node) => name(node) === "Cancel mayday" && !node.hidden), 8000);
|
||||
if (!button) {
|
||||
return {error: "no enabled Cancel mayday button in the radio spot", toolbar};
|
||||
return {error: "no shown Cancel mayday button next to PTT", toolbar};
|
||||
}
|
||||
const shown = new Set(all("#toasts .toast"));
|
||||
const fresh = () => all("#toasts .toast").filter((node) => !shown.has(node)).map(text);
|
||||
@@ -266,7 +266,9 @@ SPOT_SEND = """(async () => {@HELPERS@
|
||||
toolbar: all('#main [role="toolbar"] > *').map((node) => name(node.tagName === "DETAILS" ? node.querySelector("summary") : node)),
|
||||
channels: all("option", channel).map((option) => option.value),
|
||||
record: all("button", form).filter((button) => button.hasAttribute("aria-pressed") && !button.classList.contains("mic")).map(text),
|
||||
heads: all(".spot-head button", spot).map((button) => [name(button), button.title]),
|
||||
heads: all(".spot-head button", spot).length,
|
||||
send: all(".ptt-split :is(button, summary)", form).filter((node) => !node.closest(".menu-box")).map((node) => [name(node), node.title]),
|
||||
cancel: form.querySelector(".radio-cancel").hidden,
|
||||
@FITS@,
|
||||
};
|
||||
await until(() => [...recipient.options].some((option) => option.value === "Stage"), 8000);
|
||||
@@ -310,7 +312,7 @@ RADIO_JUMP = """(async () => {@HELPERS@
|
||||
await sleep(200);
|
||||
return {
|
||||
hash: "#stream", focused, tabs, closed: [spot.hidden, toggle.getAttribute("aria-expanded")],
|
||||
header: all("header.top button").map((button) => [button.id, name(button), text(button)]), radioTab: Boolean(document.getElementById("tab-radio")),
|
||||
header: all("header.top button[id]").map((button) => [button.id, name(button), text(button)]), radioTab: Boolean(document.getElementById("tab-radio")),
|
||||
};
|
||||
})()""".replace("@HELPERS@", HELPERS)
|
||||
CANCELED = """() => {
|
||||
@@ -324,63 +326,53 @@ CANCELED = """() => {
|
||||
}"""
|
||||
JUMPED = {
|
||||
"hash": "#stream", "focused": True, "tabs": [[tab, True, True] for tab in ("#home", "#stream/inbox", "#agents/orbit", "#artifacts/tree", "#tasks/list", "#resources")], "closed": [True, "false"],
|
||||
"header": [["grant-direct", "Direct", "Direct"], ["grant-select", "Select", "Select"], ["radio-open", "Radio", ""], ["bubbles-toggle", "Speech bubbles", ""], ["palette-open", "Commands", ""], ["settings-open", "Settings", ""]], "radioTab": False,
|
||||
"header": [["grant-select", "Select", "Select"], ["radio-open", "Radio", ""], ["bubbles-toggle", "Speech bubbles", ""], ["palette-open", "Commands", ""], ["settings-open", "Settings", ""]], "radioTab": False,
|
||||
}
|
||||
GEAR_SAVE = """(async () => {@HELPERS@@CLASHES@
|
||||
BELLS = """
|
||||
const bell = (label) => spot.querySelector(`.radio-face button[aria-label="${label} tone"]`);
|
||||
const ring = async (label, want) => {
|
||||
for (let press = 0; press < 3 && bell(label).dataset.bell !== want; press += 1) {
|
||||
bell(label).click();
|
||||
await sleep(100);
|
||||
}
|
||||
};
|
||||
"""
|
||||
BELL_SAVE = """(async () => {@HELPERS@@CLASHES@@BELLS@
|
||||
const spot = document.getElementById("radio-spot");
|
||||
const face = spot.querySelector(".radio-face");
|
||||
const gear = all(".spot-head button", spot).find((button) => name(button) === "Read aloud");
|
||||
gear.click();
|
||||
const box = await until(() => spot.querySelector("#radio-gear .radio-read"), 4000);
|
||||
if (!box) {
|
||||
return {error: "no read-aloud filters behind the gear"};
|
||||
}
|
||||
const chips = () => all('#radio-gear [aria-label="Classes"] button', spot);
|
||||
const post = () => chips().find((chip) => text(chip) === "Post");
|
||||
const found = {
|
||||
expanded: gear.getAttribute("aria-expanded"),
|
||||
tones: all(".radio-knobs .knob-label", face).map(text),
|
||||
classes: chips().map((chip) => [text(chip), chip.getAttribute("aria-pressed"), chip.disabled]),
|
||||
clashes: [clashes(face), clashes(spot.querySelector("#radio-gear"))],
|
||||
bells: all(".radio-knobs .knob-toggle", face).map((button) => name(button)),
|
||||
clashes: [clashes(face)],
|
||||
@FITS@,
|
||||
};
|
||||
const squelch = face.querySelector('input[aria-label="Squelch"]');
|
||||
squelch.value = "@SQUELCH@";
|
||||
squelch.dispatchEvent(new Event("input", {bubbles: true}));
|
||||
const tone = face.querySelector('button[aria-label="All radio tone"]');
|
||||
if (tone.getAttribute("aria-pressed") !== "@TONE@") {
|
||||
tone.click();
|
||||
}
|
||||
if (post().getAttribute("aria-pressed") !== "@POST@") {
|
||||
post().click();
|
||||
}
|
||||
await ring("All radio", "@RADIO@");
|
||||
await ring("Post and calls to you", "@POST@");
|
||||
await sleep(200);
|
||||
const kept = JSON.parse(localStorage.getItem("kvb-orchestrator.radio"));
|
||||
found.kept = [kept.squelch, kept.sounds.radio.on, kept.classes.includes("post")];
|
||||
gear.click();
|
||||
await sleep(200);
|
||||
found.after = [gear.getAttribute("aria-expanded"), Boolean(spot.querySelector("#radio-gear .radio-read"))];
|
||||
found.after = [bell("All radio").dataset.bell, bell("Post and calls to you").dataset.bell];
|
||||
document.getElementById("settings-open").click();
|
||||
const sheet = await until(() => document.querySelector(".sheet-box form.settings"), 4000);
|
||||
found.general = {sections: all("section > h3", sheet).map(text), radio: all('[aria-label="Squelch"], [aria-label="Classes"], [aria-label="Speakers"], [aria-label="Mode"], .sound-row, .stream-row', sheet).length};
|
||||
document.querySelector(".sheet-head button").click();
|
||||
return found;
|
||||
})()""".replace("@HELPERS@", HELPERS).replace("@CLASHES@", OVERLAP).replace("@FITS@", FITS)
|
||||
GEAR_READ = """(async () => {@HELPERS@@SPOT_OPEN@
|
||||
const gear = spot ? all(".spot-head button", spot).find((button) => name(button) === "Read aloud") : null;
|
||||
if (!gear) {
|
||||
})()""".replace("@HELPERS@", HELPERS).replace("@CLASHES@", OVERLAP).replace("@BELLS@", BELLS).replace("@FITS@", FITS)
|
||||
BELL_READ = """(async () => {@HELPERS@@SPOT_OPEN@@BELLS@
|
||||
const face = spot ? spot.querySelector(".radio-face") : null;
|
||||
if (!face) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
gear.click();
|
||||
await until(() => spot.querySelector("#radio-gear .radio-read"), 4000);
|
||||
const face = spot.querySelector(".radio-face");
|
||||
return {
|
||||
squelch: Number(face.querySelector('input[aria-label="Squelch"]').value),
|
||||
tone: face.querySelector('button[aria-label="All radio tone"]').getAttribute("aria-pressed") === "true",
|
||||
post: all('#radio-gear [aria-label="Classes"] button', spot).find((chip) => text(chip) === "Post").getAttribute("aria-pressed") === "true",
|
||||
radio: bell("All radio").dataset.bell,
|
||||
post: bell("Post and calls to you").dataset.bell,
|
||||
@FITS@,
|
||||
};
|
||||
})()""".replace("@HELPERS@", HELPERS).replace("@SPOT_OPEN@", SPOT_OPEN).replace("@FITS@", FITS)
|
||||
})()""".replace("@HELPERS@", HELPERS).replace("@SPOT_OPEN@", SPOT_OPEN).replace("@BELLS@", BELLS).replace("@FITS@", FITS)
|
||||
|
||||
|
||||
class Station(http.server.BaseHTTPRequestHandler):
|
||||
|
||||
@@ -147,20 +147,20 @@ HOME = """(async () => {@HELPERS@@PROBES@
|
||||
}));
|
||||
const fresh = measure();
|
||||
const whole = tile("radio");
|
||||
const bar = whole.querySelector(".spot-head");
|
||||
const gear = bar ? all("button", bar).find((button) => button.getAttribute("aria-label") === "Read aloud") : null;
|
||||
const clear = bar ? all("button", bar).find((button) => button.getAttribute("aria-label") === "Cancel mayday") : null;
|
||||
if (gear) {
|
||||
gear.click();
|
||||
const active = whole.querySelector('.radio-modes button[aria-pressed="true"]');
|
||||
const opens = Boolean(active && active.querySelector(".mode-caret"));
|
||||
if (opens) {
|
||||
active.click();
|
||||
await sleep(200);
|
||||
}
|
||||
const filters = whole.querySelector(".radio-gear .radio-read");
|
||||
const menu = whole.querySelector(".radio-mode-menu:not([hidden])");
|
||||
const cancel = whole.querySelector("form.composer .radio-cancel");
|
||||
const tools = {
|
||||
gear: gear ? [gear.getAttribute("aria-expanded"), Boolean(filters), filters ? box(filters).bottom <= box(whole).bottom + 1 : null] : null,
|
||||
clear: clear ? [clear.disabled, clear.title] : null,
|
||||
menu: opens ? [active.getAttribute("aria-expanded"), Boolean(menu), menu ? box(menu).bottom <= box(whole).bottom + 1 : null] : null,
|
||||
cancel: cancel ? [cancel.hidden, cancel.title] : null,
|
||||
};
|
||||
if (gear) {
|
||||
gear.click();
|
||||
if (opens) {
|
||||
active.click();
|
||||
}
|
||||
const content = {
|
||||
tiles: all("#main .home-tile").map((node) => node.dataset.pin),
|
||||
|
||||
+33
-19
@@ -120,7 +120,14 @@ RADIO = """
|
||||
spot.querySelector(`.radio-tabs [data-tab="${id}"]`).click();
|
||||
await sleep(150);
|
||||
};
|
||||
const unlabelled = () => all(".radio-face :is(button, select, input), #radio-gear :is(button, select, input), .radio-logbox :is(button, select, input), .radio-station button", spot).filter((node) => node.getClientRects().length && !node.getAttribute("aria-label") && !text(node)).length;
|
||||
const modeMenu = async (mode, open) => {
|
||||
const button = spot.querySelector(`.radio-modes button[data-mode="${mode}"]`);
|
||||
if ((button.getAttribute("aria-expanded") === "true") !== open) {
|
||||
button.click();
|
||||
await sleep(200);
|
||||
}
|
||||
};
|
||||
const unlabelled = () => all(".radio-face :is(button, select, input), .radio-logbox :is(button, select, input), .radio-station button, form.composer :is(button, summary)", spot).filter((node) => node.getClientRects().length && !node.getAttribute("aria-label") && !text(node)).length;
|
||||
""".replace("@CUES@", ", ".join(f'"{name}": "{ident}"' for name, ident in CUES.items()))
|
||||
FACE = """(async () => {@HELPERS@@RADIO@
|
||||
await cpuShown("CPU 10 %");
|
||||
@@ -138,12 +145,15 @@ FACE = """(async () => {@HELPERS@@RADIO@
|
||||
const squelchLit = Boolean(await until(() => lamp().dataset.lit === "true" && audio().filters.length > atTest.filters, 6000));
|
||||
const squelch = {lit: squelchLit, filters: since(atTest).filters.map(([type]) => type), tts: since(atTest).tts};
|
||||
await until(() => lamp().dataset.lit === "false", 6000);
|
||||
const gear = all(".spot-head button", spot).find((button) => name(button) === "Read aloud");
|
||||
gear.click();
|
||||
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])]));
|
||||
all('#radio-gear .chips[aria-label="Fallback"] .chip', spot).find((chipNode) => text(chipNode) === "Hiss").click();
|
||||
const bells = all(".radio-knobs .knob-toggle", spot).map((button) => [name(button), button.dataset.bell]);
|
||||
await modeMenu("auto", true);
|
||||
const caret = all(".radio-modes .mode-caret", spot).filter((node) => node.getClientRects().length).map((node) => node.closest("button").dataset.mode);
|
||||
const groups = Object.fromEntries(all(".radio-mode-menu .chips", spot).map((group) => [group.getAttribute("aria-label"), all(".chip", group).map((chipNode) => [text(chipNode), chipNode.getAttribute("aria-pressed"), chipNode.disabled])]));
|
||||
all('.radio-mode-menu .chips[aria-label="Fallback"] .chip', spot).find((chipNode) => text(chipNode) === "Hiss").click();
|
||||
await sleep(150);
|
||||
const menuFits = fits();
|
||||
await modeMenu("auto", false);
|
||||
const send = [name(spot.querySelector("form.composer .ptt-more")), spot.querySelector("form.composer .radio-cancel").hidden];
|
||||
const stationsHead = text(spot.querySelector(".radio-station .group-title"));
|
||||
const ptt = spot.querySelector('form.composer button[type="submit"]');
|
||||
const pageFits = fits();
|
||||
@@ -157,7 +167,7 @@ FACE = """(async () => {@HELPERS@@RADIO@
|
||||
const stations = [document.querySelector("#sheet .sheet-box").getAttribute("aria-label"), all("#sheet .settings h3").map(text)];
|
||||
all("#sheet .sheet-head button").find((button) => name(button) === "Close").click();
|
||||
await sleep(200);
|
||||
return {display, modes, knobs, toneToggles, testButtons, squelch, labels, groups, stationsHead, ptt: [text(ptt), ptt.title], sections, stations, fits: pageFits, unlabelled: unlabelled(), palette: getComputedStyle(document.documentElement).getPropertyValue("--panel").trim(), violations: window.e2eViolations};
|
||||
return {display, modes, knobs, toneToggles, testButtons, squelch, labels, bells, caret, groups, menuFits, send, stationsHead, ptt: [text(ptt), ptt.title], sections, stations, fits: pageFits, unlabelled: unlabelled(), palette: getComputedStyle(document.documentElement).getPropertyValue("--panel").trim(), violations: window.e2eViolations};
|
||||
})()"""
|
||||
LOG = """(async () => {@HELPERS@@RADIO@
|
||||
await until(() => rows().length, 8000);
|
||||
@@ -183,6 +193,15 @@ LOG = """(async () => {@HELPERS@@RADIO@
|
||||
all(".radio-filters button", spot).find((button) => name(button) === "Clear filters").click();
|
||||
await sleep(150);
|
||||
const clearedChips = [chips(), search().value, rows().length];
|
||||
const muteOf = () => spot.querySelector(".radio-row .radio-mute");
|
||||
const sender = name(muteOf());
|
||||
muteOf().click();
|
||||
await sleep(150);
|
||||
const stored = () => JSON.parse(localStorage.getItem("kvb-orchestrator.radio") || "{}").muted || [];
|
||||
const muted = [sender, muteOf().getAttribute("aria-pressed"), stored().length, document.getElementById("popup").open];
|
||||
muteOf().click();
|
||||
await sleep(150);
|
||||
const unmuted = [muteOf().getAttribute("aria-pressed"), stored().length];
|
||||
spot.querySelector(".radio-row .radio-pick").click();
|
||||
const full = await until(() => document.getElementById("popup").open && document.querySelector("#popup .radio-full"), 4000);
|
||||
const opened = [document.getElementById("popup").open, text(full)];
|
||||
@@ -195,7 +214,7 @@ LOG = """(async () => {@HELPERS@@RADIO@
|
||||
await sleep(200);
|
||||
spot.querySelector(".radio-logbox").scrollIntoView({block: "start"});
|
||||
await sleep(200);
|
||||
return {counts, sent, received, every, posts, fromStage, narrowed, none, clearedChips, opened, kept: rows(), fits: fits()};
|
||||
return {counts, sent, received, every, posts, fromStage, narrowed, none, clearedChips, muted, unmuted, opened, kept: rows(), fits: fits()};
|
||||
})()"""
|
||||
LOG_KEPT = """(async () => {@HELPERS@@RADIO@
|
||||
await until(() => spot.querySelector(".radio-tabs [role=tab]"), 8000);
|
||||
@@ -307,18 +326,14 @@ MORSE_SPY = """() => {
|
||||
}""".replace("@SPY@", SPY)
|
||||
MORSE_KEYED = """
|
||||
const keyed = () => window.e2eMorse.filter((entry) => entry.stop !== null && entry.stop - entry.start > 1);
|
||||
const speed = () => spot.querySelector('#radio-gear input[aria-label="Morse speed"]');
|
||||
const rate = () => text(spot.querySelector("#radio-gear .morse-rate"));
|
||||
const gear = () => all(".spot-head button", spot).find((button) => name(button) === "Read aloud");
|
||||
const speed = () => spot.querySelector('.radio-mode-menu input[aria-label="Morse speed"]');
|
||||
const rate = () => text(spot.querySelector(".radio-mode-menu .morse-rate"));
|
||||
"""
|
||||
MORSE = """(async () => {@HELPERS@@RADIO@@KEYED@
|
||||
press("morse");
|
||||
await sleep(200);
|
||||
const mode = [pressed(), field("mode"), spot.querySelector('.radio-modes button[data-mode="morse"]').title];
|
||||
if (gear().getAttribute("aria-expanded") !== "true") {
|
||||
gear().click();
|
||||
await sleep(200);
|
||||
}
|
||||
await modeMenu("morse", true);
|
||||
const before = [speed().min, speed().max, speed().step, speed().value, rate()];
|
||||
speed().value = "@WPM@";
|
||||
speed().dispatchEvent(new Event("input", {bubbles: true}));
|
||||
@@ -327,16 +342,15 @@ MORSE = """(async () => {@HELPERS@@RADIO@@KEYED@
|
||||
const toast = await until(() => all("#toasts .toast strong").map(text).includes("Morse speed saved"), 15000);
|
||||
await sleep(300);
|
||||
const saved = [speed().value, rate()];
|
||||
const gearFits = fits();
|
||||
gear().click();
|
||||
await sleep(200);
|
||||
const menuFits = fits();
|
||||
await modeMenu("morse", false);
|
||||
const at = {tts: audio().tts.length, keyed: keyed().length};
|
||||
await cue("alarm");
|
||||
refreshNow();
|
||||
const playing = await until(() => keyed().length > at.keyed && lamp().dataset.lit === "true", 20000);
|
||||
const caption = spot.querySelector(".radio-caption");
|
||||
return {
|
||||
mode, before, dragged, toast: Boolean(toast), saved, gearFits, playing: Boolean(playing), keyed: keyed().slice(at.keyed), tts: audio().tts.length - at.tts,
|
||||
mode, before, dragged, toast: Boolean(toast), saved, menuFits, playing: Boolean(playing), keyed: keyed().slice(at.keyed), tts: audio().tts.length - at.tts,
|
||||
lamp: [text(lamp()), lamp().dataset.lit], caption: [caption.hidden, text(caption.querySelector("strong"))], fits: fits(),
|
||||
};
|
||||
})()""".replace("@KEYED@", MORSE_KEYED)
|
||||
|
||||
@@ -22,12 +22,20 @@ FILES = ("src/app.py", "src/view.js", "docs/notes.md")
|
||||
ROWS = 80
|
||||
COMMON = """
|
||||
const row = (ref) => document.querySelector(`#main .inbox-list > li[data-ref="${ref}"]`);
|
||||
const modeButton = (mode) => document.querySelector(`#grant-bar button[data-mode="${mode}"]`);
|
||||
const tray = () => document.querySelector("#grant-bar .grant-tray");
|
||||
const count = () => text(document.querySelector("#grant-bar .grant-count"));
|
||||
const split = () => document.querySelector("#grant-bar .grant-split");
|
||||
const menu = () => document.querySelector("#grant-bar details.grant-menu");
|
||||
const main = () => split() && split().firstElementChild;
|
||||
const count = () => menu() && menu().querySelector("summary").getAttribute("aria-label");
|
||||
const openMenu = async () => {
|
||||
if (!menu().open) {
|
||||
menu().querySelector("summary").click();
|
||||
}
|
||||
await until(() => menu().open, 2000);
|
||||
await sleep(100);
|
||||
};
|
||||
const grantOf = (ref) => row(ref) && row(ref).querySelector(".item-actions button.primary");
|
||||
const wide = () => document.documentElement.scrollWidth > innerWidth + 1;
|
||||
const switchState = () => [modeButton("direct").getAttribute("aria-pressed"), modeButton("select").getAttribute("aria-pressed"), tray().hidden, Boolean(document.querySelector("#main .inbox-actions"))];
|
||||
const switchState = () => [name(main()), count(), document.querySelector("#grant-bar #grant-direct") ? "select" : "direct"];
|
||||
const storedMode = async (mode) => {
|
||||
const end = Date.now() + 6000;
|
||||
while (Date.now() < end) {
|
||||
@@ -75,9 +83,9 @@ MODE = """(async () => {@HELPERS@@COMMON@
|
||||
key("Escape");
|
||||
await until(() => document.getElementById("sheet").hidden, 4000);
|
||||
const before = switchState();
|
||||
modeButton("select").click();
|
||||
main().click();
|
||||
const kept = await storedMode("select");
|
||||
await until(() => !tray().hidden, 4000);
|
||||
await until(() => switchState()[2] === "select", 4000);
|
||||
return {before, kept, after: switchState(), wide: wide()};
|
||||
})()"""
|
||||
COLLECT = """(async () => {@HELPERS@@COMMON@
|
||||
@@ -89,20 +97,25 @@ COLLECT = """(async () => {@HELPERS@@COMMON@
|
||||
}
|
||||
return send(path, init);
|
||||
};
|
||||
if (!(await until(() => row("@REVIEW@") && row("@ASK@") && row("@RUN@") && !tray().hidden, 8000))) {
|
||||
if (!(await until(() => row("@REVIEW@") && row("@ASK@") && row("@RUN@") && switchState()[2] === "select", 8000))) {
|
||||
return {error: text(document.getElementById("main"))};
|
||||
}
|
||||
const restored = switchState();
|
||||
const counts = [];
|
||||
const press = async (ref, expected) => {
|
||||
grantOf(ref).click();
|
||||
const settle = async (expected) => {
|
||||
await until(() => count() === expected, 3000);
|
||||
counts.push(count());
|
||||
};
|
||||
await press("@REVIEW@", "1 selected");
|
||||
await press("@ASK@", "2 selected");
|
||||
await press("@REVIEW@", "1 selected");
|
||||
await press("@REVIEW@", "2 selected");
|
||||
grantOf("@REVIEW@").click();
|
||||
await settle("1 selected");
|
||||
const pale = [grantOf("@REVIEW@").disabled, grantOf("@REVIEW@").classList.contains("picked")];
|
||||
grantOf("@ASK@").click();
|
||||
await settle("2 selected");
|
||||
await openMenu();
|
||||
all("#grant-bar .grant-picked button").find((button) => name(button).startsWith("Remove feat: three files")).click();
|
||||
await settle("1 selected");
|
||||
grantOf("@REVIEW@").click();
|
||||
await settle("2 selected");
|
||||
if (document.activeElement) {
|
||||
document.activeElement.blur();
|
||||
}
|
||||
@@ -114,12 +127,13 @@ COLLECT = """(async () => {@HELPERS@@COMMON@
|
||||
key("a");
|
||||
await until(() => count() === "3 selected", 3000);
|
||||
counts.push(count());
|
||||
const pressed = ["@REVIEW@", "@ASK@", "@RUN@"].map((ref) => grantOf(ref).getAttribute("aria-pressed"));
|
||||
const labels = all("#grant-bar .grant-tray button").map(name);
|
||||
return {restored, counts, pressed, labels, posted, wide: wide()};
|
||||
const pressed = ["@REVIEW@", "@ASK@", "@RUN@"].map((ref) => [grantOf(ref).getAttribute("aria-pressed"), grantOf(ref).disabled]);
|
||||
await openMenu();
|
||||
const labels = all("#grant-bar .grant-split button").map(name);
|
||||
return {restored, pale, counts, pressed, labels, posted, wide: wide()};
|
||||
})()"""
|
||||
SHEET = """(async () => {@HELPERS@@COMMON@
|
||||
all("#grant-bar .grant-tray button").find((button) => name(button) === "Grant selection (3)").click();
|
||||
main().click();
|
||||
await until(() => document.querySelector(".sheet-box .actions"), 4000);
|
||||
const confirm = all(".sheet-box .actions button").find((button) => text(button).startsWith("Grant "));
|
||||
return {listed: all(".sheet-box ul.mini > li strong").map(text), label: text(confirm), wide: wide()};
|
||||
@@ -150,9 +164,10 @@ DIRECT = """(async () => {@HELPERS@@COMMON@
|
||||
}
|
||||
return send(path, init);
|
||||
};
|
||||
modeButton("direct").click();
|
||||
await openMenu();
|
||||
document.querySelector("#grant-bar #grant-direct").click();
|
||||
const kept = await storedMode("direct");
|
||||
await until(() => tray().hidden && document.querySelector("#main .inbox-actions"), 4000);
|
||||
await until(() => switchState()[2] === "direct", 4000);
|
||||
const spare = await until(() => grantOf("@SPARE@"), 4000);
|
||||
const pressed = spare.getAttribute("aria-pressed");
|
||||
spare.click();
|
||||
@@ -229,18 +244,21 @@ class TestBulkGrant(base.OrchestratorE2ECase):
|
||||
self.assertEqual(diff["ended"]["opened"], [True, True, False], diff)
|
||||
self.assertEqual(diff["second"], {"opened": [True, True, False], "marked": [1]}, diff)
|
||||
self.assertEqual(diff["jumped"], {"opened": [True, True, True], "marked": [2], "atTop": True}, diff)
|
||||
self.assertEqual((mode["before"], mode["kept"], mode["after"]), (["true", "false", True, True], True, ["false", "true", False, False]), mode)
|
||||
selecting = ["Grant selection (0)", "0 selected", "select"]
|
||||
self.assertEqual((mode["before"], mode["kept"], mode["after"]), (["Select", "0 selected", "direct"], True, selecting), mode)
|
||||
self.assertNotIn("error", collect, collect)
|
||||
self.assertEqual(collect["restored"], ["false", "true", False, False], collect)
|
||||
self.assertEqual(collect["restored"], selecting, collect)
|
||||
self.assertEqual(collect["pale"], [True, True], collect)
|
||||
self.assertEqual(collect["counts"], ["1 selected", "2 selected", "1 selected", "2 selected", "3 selected"], collect)
|
||||
self.assertEqual((collect["pressed"], collect["posted"]), (["true"] * 3, []), collect)
|
||||
self.assertEqual((collect["labels"][0], collect["labels"][-1]), ("Grant selection (3)", "Clear"), collect)
|
||||
self.assertEqual((collect["pressed"], collect["posted"]), ([["true", True]] * 3, []), collect)
|
||||
self.assertEqual((collect["labels"][0], collect["labels"][-1]), ("Grant selection (3)", "Direct"), collect)
|
||||
self.assertEqual(sum(label.startswith("Remove ") for label in collect["labels"]), 3, collect)
|
||||
self.assertEqual((sheet["label"], len(sheet["listed"])), ("Grant 3", 3), sheet)
|
||||
items = sorted(f"{ref}:approve" for ref in ids.values())
|
||||
self.assertEqual(confirm["posted"], [["/api/sign", items], *([["/api/inbox/approve", items]] if signs else [])], confirm)
|
||||
self.assertEqual(confirm["count"], "0 selected" if signs else "3 selected", confirm)
|
||||
self.assertEqual(direct["kept"], True, direct)
|
||||
self.assertEqual(direct["after"], ["true", "false", True, True], direct)
|
||||
self.assertEqual(direct["after"], ["Select", "0 selected", "direct"] if signs else ["Grant selection (3)", "3 selected", "direct"], direct)
|
||||
self.assertEqual((direct["pressed"], direct["posted"]), (None, [[self.spare]]), direct)
|
||||
self.assertFalse(any(found["wide"] for found in (diff, mode, collect, sheet, confirm, direct)), width)
|
||||
|
||||
|
||||
@@ -47,15 +47,8 @@ GIBBER_SPY = """() => {
|
||||
};
|
||||
}""".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 fallbacks = () => all('.radio-mode-menu .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();
|
||||
@@ -70,11 +63,9 @@ GIBBER_KIT = """
|
||||
};
|
||||
"""
|
||||
GIBBER = """(async () => {@HELPERS@@RADIO@@KIT@
|
||||
press("gibberlink");
|
||||
press("quiet");
|
||||
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);
|
||||
await modeMenu("quiet", true);
|
||||
const before = fallbacks().map((chip) => [text(chip), chip.getAttribute("aria-pressed")]);
|
||||
fallbacks().find((chip) => text(chip) === "Morse").click();
|
||||
await sleep(150);
|
||||
@@ -82,9 +73,12 @@ GIBBER = """(async () => {@HELPERS@@RADIO@@KIT@
|
||||
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 label = text(spot.querySelector(".radio-mode-menu .radio-fallback .chips-label"));
|
||||
const gearFits = fits();
|
||||
await opened(false);
|
||||
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")), Boolean(spot.querySelector(".radio-mode-menu:not([hidden])"))];
|
||||
const at = {captured: window.e2eGibber.length, pans: window.e2ePans.length};
|
||||
const playing = await sent(at.captured);
|
||||
await sleep(300);
|
||||
@@ -201,6 +195,7 @@ class TestGibberlink(HubCase):
|
||||
self.assertEqual(played["mode"][:2], [["gibberlink"], "Gibberlink"], played["mode"])
|
||||
self.assertIn("MAYDAY", played["mode"][2])
|
||||
self.assertTrue(played["mode"][3])
|
||||
self.assertFalse(played["mode"][4], "switching to Gibberlink closes the Quiet fallback menu")
|
||||
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}))
|
||||
|
||||
@@ -21,6 +21,8 @@ import hub_e2e_kit as base
|
||||
from hub_e2e_kit import CHOICE_CHANNELS, OUT, WIDTHS, tone
|
||||
from hub_e2e_radio import (
|
||||
ADD_STATION,
|
||||
BELL_READ,
|
||||
BELL_SAVE,
|
||||
CALL,
|
||||
CANCELED,
|
||||
CLEAR_MAYDAY,
|
||||
@@ -28,8 +30,6 @@ from hub_e2e_radio import (
|
||||
COMPOSE_SEND,
|
||||
DLF_NODE,
|
||||
DLF_PATH,
|
||||
GEAR_READ,
|
||||
GEAR_SAVE,
|
||||
JUMPED,
|
||||
MEDIA_LOG,
|
||||
RADIO_CLICK,
|
||||
@@ -46,6 +46,8 @@ from hub_e2e_radio import (
|
||||
from hub_support import HOST_STATE
|
||||
from kvb_orchestrator import skill_scripts
|
||||
|
||||
SEND_GROUP = [["PTT", "PTT: push to transmit the message; your passkey signs it"], ["More send options", "More: send a test message only you hear"]]
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
|
||||
class TestHubRadio(base.OrchestratorE2ECase):
|
||||
@@ -260,23 +262,23 @@ class TestHubRadio(base.OrchestratorE2ECase):
|
||||
with self.subTest(width=width):
|
||||
self.assertNotIn("error", result)
|
||||
self.assertEqual(result["toolbar"], ["Priority", "Day/Night", "Drain", "Suspend", "Resume", "Status"])
|
||||
self.assertEqual((result["title"], result["shown"]), ("Cancel mayday: lift the radio silence so the agents write again; your passkey signs it", ""))
|
||||
self.assertEqual((result["title"], result["shown"]), ("Cancel mayday: lift the radio silence so the agents write again; your passkey signs it", "Cancel mayday"))
|
||||
self.assertEqual(result["declined"], {"question": [question], "posted": [], "toasts": []})
|
||||
self.assertEqual(result["accepted"], {"question": [question], "posted": ["/api/board/sign", "/api/board/clear-mayday"]})
|
||||
self.assertTrue((result["done"] or "").startswith("Cancel mayday: done"), result)
|
||||
self.assertEqual(self.scripts.calls, [(skill_scripts.RADIO, ["clear", "--force", "--session", "Operator"])] * len(WIDTHS))
|
||||
|
||||
def test_chromium_sends_every_class_from_the_radio_spot_and_keeps_its_gear_settings_through_a_reload_at_three_widths(self):
|
||||
def test_chromium_sends_every_class_from_the_radio_spot_and_keeps_its_bells_through_a_reload_at_three_widths(self):
|
||||
local = f"http://localhost:{self.port}/"
|
||||
values = {1920: ("0.35", "false", "true"), 1366: ("0.45", "true", "false"), 390: ("0.55", "false", "true")}
|
||||
values = {1920: ("0.35", "off", "speak"), 1366: ("0.45", "speak", "tone"), 390: ("0.55", "tone", "speak")}
|
||||
steps = [{"width": width, "height": height, "url": f"{local}?{width}-jump#stream/radio", "wait": 1200, "probe": RADIO_JUMP, "shot": self.shot(f"{width}-radio-header-spot-every-tab")} for width, height in WIDTHS]
|
||||
for width, height in WIDTHS:
|
||||
squelch, tone, post = values[width]
|
||||
gear = GEAR_SAVE.replace("@SQUELCH@", squelch).replace("@TONE@", tone).replace("@POST@", post)
|
||||
squelch, radio_bell, post = values[width]
|
||||
bells = BELL_SAVE.replace("@SQUELCH@", squelch).replace("@RADIO@", radio_bell).replace("@POST@", post)
|
||||
steps += [
|
||||
{"width": width, "height": height, "url": f"{local}?{width}#agents/orbit", "wait": 1200, "probe": SPOT_SEND.replace("@TEXT@", f"spot {width}"), "shot": self.shot(f"{width}-radio-spot-sent")},
|
||||
{"width": width, "height": height, "url": None, "wait": 0, "probe": gear, "shot": None},
|
||||
{"width": width, "height": height, "url": f"{local}?{width}-reloaded#agents/orbit", "wait": 1200, "probe": GEAR_READ, "shot": self.shot(f"{width}-radio-spot-gear")},
|
||||
{"width": width, "height": height, "url": None, "wait": 0, "probe": bells, "shot": None},
|
||||
{"width": width, "height": height, "url": f"{local}?{width}-reloaded#agents/orbit", "wait": 1200, "probe": BELL_READ, "shot": self.shot(f"{width}-radio-spot-bells")},
|
||||
]
|
||||
data = self.drive(steps, self.authenticator())
|
||||
(OUT / "chromium-radio-spot.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
@@ -289,28 +291,27 @@ class TestHubRadio(base.OrchestratorE2ECase):
|
||||
self.assertEqual(jump, JUMPED)
|
||||
for index, (width, _) in enumerate(WIDTHS):
|
||||
sent, saved, read = walked[3 * index : 3 * (index + 1)]
|
||||
squelch, tone, post = values[width]
|
||||
squelch, radio_bell, post = values[width]
|
||||
with self.subTest(width=width):
|
||||
for probe in (sent, saved, read):
|
||||
self.assertNotIn("error", probe)
|
||||
self.assertEqual((sent["closed"], sent["open"]), ([True, "false"], [False, "true", True]))
|
||||
self.assertEqual(sent["inline"], ["static", True, True])
|
||||
self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], CHOICE_CHANNELS, ["Record"]))
|
||||
self.assertEqual(sent["heads"], [["Read aloud", "Read aloud: the classes and agents the radio sounds for"], ["Cancel mayday", "Cancel mayday: lift the radio silence so the agents write again; your passkey signs it"]])
|
||||
self.assertEqual((sent["heads"], sent["send"], sent["cancel"]), (0, SEND_GROUP, True))
|
||||
self.assertEqual((sent["tall"], sent["wide"]), (width == 390, False))
|
||||
self.assertEqual([run["cls"] for run in sent["runs"]], CHOICE_CHANNELS)
|
||||
for run in sent["runs"]:
|
||||
direct = run["cls"] in ("post", "call")
|
||||
self.assertEqual((run["direct"], run["question"], run["left"]), (direct, [mayday] if run["cls"] == "mayday" else [], ""), run)
|
||||
self.assertTrue((run["toast"] or "").startswith(f"{labels[run['cls']]} to {'Stage' if direct else 'all'}: sent"), run)
|
||||
self.assertEqual((saved["expanded"], saved["clashes"]), ("true", [{"found": [], "outside": []}] * 2))
|
||||
self.assertEqual(saved["clashes"], [{"found": [], "outside": []}])
|
||||
self.assertEqual(saved["tones"], ["MAYDAY / PAN-PAN", "Reviews, asks, decisions", "Post and calls to you", "All radio", "Squelch", "speak while CPU < 50 %"])
|
||||
self.assertEqual([entry[0] for entry in saved["classes"]], ["Post", "Call", "Newsletter", "Broadcast", "MAYDAY", "PAN-PAN", "Sécurité"])
|
||||
self.assertEqual([entry[1:] for entry in saved["classes"] if entry[0] == "MAYDAY"], [["true", True]])
|
||||
self.assertEqual((saved["kept"], saved["after"]), ([float(squelch), tone == "true", post == "true"], ["false", False]))
|
||||
self.assertEqual(saved["bells"], ["MAYDAY / PAN-PAN tone", "Reviews, asks, decisions tone", "Post and calls to you tone", "All radio tone"])
|
||||
self.assertEqual((saved["kept"], saved["after"]), ([float(squelch), radio_bell != "off", post == "speak"], [radio_bell, post]))
|
||||
self.assertEqual(saved["general"], {"sections": ["Ambience", "Location", "Appearance", "Music", "Notifications", "Passkey"], "radio": 0})
|
||||
self.assertEqual((saved["tall"], saved["wide"]), (width == 390, False))
|
||||
self.assertEqual(read, {"squelch": float(squelch), "tone": tone == "true", "post": post == "true", "tall": width == 390, "wide": False})
|
||||
self.assertEqual(read, {"squelch": float(squelch), "radio": radio_bell, "post": post, "tall": width == 390, "wide": False})
|
||||
heads = {"post": ["post", "--to", "Stage"], "call": ["send", "call", "--to", "Stage"], "newsletter": ["post"]}
|
||||
radio = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO]
|
||||
sends = [(width, cls) for width, _ in WIDTHS for cls in CHOICE_CHANNELS]
|
||||
@@ -348,7 +349,7 @@ class TestHubRadio(base.OrchestratorE2ECase):
|
||||
self.assertNotIn("error", sent, sent)
|
||||
self.assertEqual((sent["closed"], sent["open"], sent["inline"]), ([True, "false"], [False, "true", True], ["static", True, True]))
|
||||
self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], CHOICE_CHANNELS, ["Record"]))
|
||||
self.assertEqual(sent["heads"], [["Read aloud", "Read aloud: the classes and agents the radio sounds for"], ["Cancel mayday", hint]])
|
||||
self.assertEqual((sent["heads"], sent["send"], sent["cancel"]), (0, SEND_GROUP, True))
|
||||
self.assertEqual((sent["tall"], sent["wide"]), (width == 390, False))
|
||||
self.assertEqual([run["cls"] for run in sent["runs"]], CHOICE_CHANNELS)
|
||||
for run in sent["runs"]:
|
||||
@@ -356,10 +357,10 @@ class TestHubRadio(base.OrchestratorE2ECase):
|
||||
self.assertEqual((run["direct"], run["question"], run["left"]), (direct, [mayday] if run["cls"] == "mayday" else [], f"spot {width} {run['cls']}"), run)
|
||||
self.assertTrue((run["toast"] or "").startswith(f"{labels[run['cls']]} to {'Stage' if direct else 'all'}: not signed"), run)
|
||||
self.assertIn("NotAllowedError", run["toast"], run)
|
||||
with self.subTest(browser="firefox", width=width, part="icon-only cancel mayday unsigned"):
|
||||
with self.subTest(browser="firefox", width=width, part="cancel mayday next to PTT unsigned"):
|
||||
self.assertNotIn("error", cleared, cleared)
|
||||
self.assertEqual(cleared["toolbar"], ["Priority", "Day/Night", "Drain", "Suspend", "Resume", "Status"])
|
||||
self.assertEqual((cleared["title"], cleared["shown"]), (hint, ""))
|
||||
self.assertEqual((cleared["title"], cleared["shown"]), (hint, "Cancel mayday"))
|
||||
self.assertEqual(cleared["declined"], {"question": [question], "posted": [], "toasts": []})
|
||||
self.assertEqual(cleared["accepted"], {"question": [question], "posted": ["/api/board/sign"]})
|
||||
self.assertTrue((cleared["done"] or "").startswith("Cancel mayday: not signed"), cleared)
|
||||
|
||||
@@ -114,8 +114,8 @@ class TestRadioLayout(kit.RadioLayoutCase):
|
||||
self.assertGreaterEqual(found["rows"], 2, home[moment])
|
||||
self.assertTrue(found["inside"], home[moment])
|
||||
self.assertTrue(found["filled"], home[moment])
|
||||
self.assertEqual(home["tools"]["gear"], ["true", True, True], home)
|
||||
self.assertEqual(home["tools"]["clear"], [True, "Cancel mayday: lift the radio silence so the agents write again; your passkey signs it"], home)
|
||||
self.assertEqual(home["tools"]["menu"], ["true", True, True], home)
|
||||
self.assertEqual(home["tools"]["cancel"], [True, "Cancel mayday: lift the radio silence so the agents write again; your passkey signs it"], home)
|
||||
content = home["content"]
|
||||
self.assertEqual(content["tiles"], [f"panel:{part}" for part in PARTS], home)
|
||||
self.assertEqual(content["radio"], [True, True, True], home)
|
||||
|
||||
@@ -144,15 +144,15 @@ class TestRadioSet(HubCase):
|
||||
shown = "50" if index == 0 or not signed else str(THRESHOLDS[base.WIDTHS[index - 1][0]])
|
||||
self.assertEqual(face["knobs"][-1][1:], ["0", "100", "10", shown])
|
||||
self.assertEqual(len(face["toneToggles"]), 4)
|
||||
self.assertEqual(face["testButtons"], [*(f"Test {knob[0]}" for knob in face["knobs"][:-1]), None])
|
||||
self.assertEqual(face["testButtons"], [*(f"Test {knob[0]}" for knob in face["knobs"][:-1]), "Radio check"])
|
||||
self.assertEqual(face["squelch"], {"lit": True, "filters": ["bandpass"], "tts": []}, face)
|
||||
self.assertEqual([label["text"] for label in face["labels"]], [*(knob[0] for knob in face["knobs"][:-1]), f"speak while CPU < {shown} %"])
|
||||
for label in face["labels"]:
|
||||
self.assertEqual((label["title"], label["row"]), (label["text"], True), label)
|
||||
self.assertTrue(label["whole"] or width == 390, label)
|
||||
self.assertEqual(face["groups"]["Classes"][4], ["MAYDAY", "true", True])
|
||||
self.assertEqual([entry[1] for entry in face["groups"]["Classes"]], ["false", "false", "false", "false", "true", "true", "true"])
|
||||
self.assertIn(["Stage", "true", False], face["groups"]["Agents"])
|
||||
self.assertEqual(face["bells"], [["MAYDAY / PAN-PAN tone", "speak"], ["Reviews, asks, decisions tone", "tone"], ["Post and calls to you tone", "tone"], ["All radio tone", "off"]])
|
||||
self.assertEqual((face["caret"], list(face["groups"]), face["menuFits"]), (["auto"], ["Fallback"], {"page": True, "panel": True}))
|
||||
self.assertEqual(face["send"], ["More send options", True])
|
||||
self.assertEqual(face["stationsHead"], "Internet radio")
|
||||
self.assertEqual(face["ptt"][0], "PTT")
|
||||
self.assertEqual([section for section in face["sections"] if section in ("Internet radio", "Tones", "Read radio aloud", "Radio")], [])
|
||||
@@ -170,6 +170,8 @@ class TestRadioSet(HubCase):
|
||||
self.assertEqual([row["line"] for row in log["narrowed"]], ["rebase done"])
|
||||
self.assertEqual(log["none"][0], 0)
|
||||
self.assertEqual(log["clearedChips"], [{"class": "", "from": "", "to": "", "agent": ""}, "", len(every)])
|
||||
self.assertTrue(log["muted"][0].startswith("Mute "), log["muted"])
|
||||
self.assertEqual((log["muted"][1:], log["unmuted"]), (["true", 1, False], ["false", 0]), log)
|
||||
self.assertEqual(log["opened"][0], True)
|
||||
self.assertTrue(log["opened"][1], log)
|
||||
self.assertEqual(log["fits"], {"page": True, "panel": True})
|
||||
@@ -265,7 +267,7 @@ class TestRadioSet(HubCase):
|
||||
self.assertEqual(keying["lamp"], ["RX", "true"])
|
||||
self.assertFalse(keying["caption"][0])
|
||||
self.assertTrue(keying["caption"][1].startswith("Stage"), keying)
|
||||
self.assertEqual((keying["gearFits"], keying["fits"]), ({"page": True, "panel": True}, {"page": True, "panel": True}), keying)
|
||||
self.assertEqual((keying["menuFits"], keying["fits"]), ({"page": True, "panel": True}, {"page": True, "panel": True}), keying)
|
||||
with self.subTest(browser=browser, width=width, part="morse stop"):
|
||||
self.assertNotIn("error", stopped, stopped)
|
||||
self.assertEqual(stopped, {"before": [True, "true", False], "cut": True, "quiet": True, "hidden": True, "later": 0}, stopped)
|
||||
|
||||
@@ -60,7 +60,7 @@ OPERATOR = """(async () => {@HELPERS@@UNLABELLED@
|
||||
["@TAG@ review", "@TAG@ ship", "@TAG@ commit"].forEach((words) => mine(words).querySelector('input[type="checkbox"]').click());
|
||||
await sleep(300);
|
||||
found.unlabelled = {main: unlabelled(document.getElementById("main"))};
|
||||
const grant = all("#main .inbox-actions button").find((button) => name(button).startsWith("Grant selection"));
|
||||
const grant = all("#grant-bar .grant-split button").find((button) => name(button).startsWith("Grant selection"));
|
||||
found.grant = name(grant);
|
||||
grant.click();
|
||||
await until(() => document.querySelector(".sheet-box .actions"), 4000);
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import unittest
|
||||
|
||||
from hub_support import HUB
|
||||
|
||||
COMPOSER = HUB / "templates" / "page-composer.js"
|
||||
PROBE = r"""
|
||||
const fs = require("fs");
|
||||
const vm = require("vm");
|
||||
const code = fs.readFileSync(process.argv[1], "utf8");
|
||||
const settle = async () => {
|
||||
for (let round = 0; round < 20; round += 1) {
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
};
|
||||
function rig() {
|
||||
const timers = [];
|
||||
const log = [];
|
||||
const sandbox = {
|
||||
TO_ONE: [], TO_ALL: [], state: {speech: {seconds: 30}}, Event: class {},
|
||||
window: {setTimeout: (run) => timers.push(run) && timers.length, clearTimeout: (id) => {
|
||||
timers[id - 1] = null;
|
||||
}},
|
||||
};
|
||||
vm.runInNewContext(code, sandbox);
|
||||
sandbox.startRecording = (parts) => log.push(`start ${parts.ptt || "click"}`);
|
||||
sandbox.stopRecording = (parts) => log.push(`stop ${parts.ptt || "click"}`);
|
||||
const handlers = {};
|
||||
const record = {disabled: false, addEventListener: (kind, run) => {
|
||||
(handlers[kind] = handlers[kind] || []).push(run);
|
||||
}};
|
||||
const parts = {record, recorder: null, ptt: "", hold: 0, swallow: false};
|
||||
sandbox.holdToTalk(parts);
|
||||
const fire = (kind, event) => (handlers[kind] || []).forEach((run) => run(event || {button: 0}));
|
||||
const tick = () => timers.splice(0).forEach((run) => run && run());
|
||||
return {sandbox, parts, fire, tick, log};
|
||||
}
|
||||
async function kept(ptt, heard) {
|
||||
const {sandbox, parts} = rig();
|
||||
let submits = 0;
|
||||
Object.assign(sandbox, {
|
||||
context: () => ({}), wavOf: async () => "wav", attachVoice: () => null, toast: () => null,
|
||||
send: async () => ({ok: true, data: {id: "n1"}}), heardNote: async () => heard,
|
||||
});
|
||||
Object.assign(parts, {ptt, status: {textContent: ""}, text: {value: "", dispatchEvent: () => true, focus: () => null, form: {requestSubmit: () => {
|
||||
submits += 1;
|
||||
}}}});
|
||||
await sandbox.keepRecording({size: 3}, parts);
|
||||
await settle();
|
||||
return {submits, ptt: parts.ptt, text: parts.text.value};
|
||||
}
|
||||
(async () => {
|
||||
const quick = rig();
|
||||
quick.fire("pointerdown");
|
||||
quick.fire("pointerup");
|
||||
quick.tick();
|
||||
const tapped = {log: quick.log.splice(0), swallow: quick.parts.swallow};
|
||||
const held = rig();
|
||||
held.fire("pointerdown");
|
||||
held.tick();
|
||||
const holding = held.parts.ptt;
|
||||
held.fire("pointerleave");
|
||||
const released = {holding, log: held.log.splice(0), ptt: held.parts.ptt, swallow: held.parts.swallow};
|
||||
const right = rig();
|
||||
right.fire("pointerdown", {button: 2});
|
||||
right.tick();
|
||||
console.log(JSON.stringify({
|
||||
tapped, released, right: right.log,
|
||||
sent: await kept("released", {status: "done", text: "hello"}),
|
||||
clicked: await kept("", {status: "done", text: "hello"}),
|
||||
empty: await kept("released", {status: "done", text: ""}),
|
||||
}));
|
||||
})().catch((error) => {
|
||||
console.error(error && error.stack || error);
|
||||
process.exit(1);
|
||||
});
|
||||
"""
|
||||
|
||||
|
||||
class TestHoldToTalk(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
done = subprocess.run(["node", "-e", PROBE, str(COMPOSER)], capture_output=True, text=True, timeout=60, check=False)
|
||||
if done.returncode != 0:
|
||||
raise AssertionError(done.stderr[-4000:])
|
||||
cls.data = json.loads(done.stdout)
|
||||
|
||||
def test_a_short_press_starts_nothing_and_leaves_the_click_to_toggle(self):
|
||||
self.assertEqual(self.data["tapped"], {"log": [], "swallow": False})
|
||||
|
||||
def test_holding_records_and_releasing_stops_and_swallows_the_trailing_click(self):
|
||||
self.assertEqual(self.data["released"], {"holding": "holding", "log": ["start holding", "stop released"], "ptt": "released", "swallow": True})
|
||||
|
||||
def test_only_the_primary_button_holds(self):
|
||||
self.assertEqual(self.data["right"], [])
|
||||
|
||||
def test_a_held_recording_sends_its_transcript_and_a_clicked_one_waits_for_the_check(self):
|
||||
self.assertEqual(self.data["sent"], {"submits": 1, "ptt": "", "text": "hello"})
|
||||
self.assertEqual(self.data["clicked"], {"submits": 0, "ptt": "", "text": "hello"})
|
||||
self.assertEqual(self.data["empty"]["submits"], 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,206 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import unittest
|
||||
|
||||
from hub_case import HubCase
|
||||
from hub_support import HUB
|
||||
|
||||
TEMPLATES = HUB / "templates"
|
||||
MODULES = ["page-constants.js", "page-reveal.js", "page-dom.js", "page-inbox.js", "page-grant.js"]
|
||||
PROBE = r"""
|
||||
const fs = require("fs");
|
||||
const vm = require("vm");
|
||||
const [dir, names] = [process.argv[1], JSON.parse(process.argv[2])];
|
||||
class El {
|
||||
constructor(tag) { Object.assign(this, {tag, children: [], attrs: {}, dataset: {}, style: {}, handlers: {}, hidden: false, textContent: "", value: ""}); }
|
||||
setAttribute(key, value) { this.attrs[key] = String(value); }
|
||||
getAttribute(key) { return Object.hasOwn(this.attrs, key) ? this.attrs[key] : null; }
|
||||
append(...nodes) { this.children.push(...nodes); }
|
||||
replaceChildren(...nodes) { this.children = nodes; }
|
||||
addEventListener(name, handler) { this.handlers[name] = handler; }
|
||||
fire(name) { return this.handlers[name]({stopPropagation() {}, preventDefault() {}}); }
|
||||
remove() {}
|
||||
}
|
||||
const all = (node) => [node, ...(node.children || []).filter((child) => child instanceof El).flatMap(all)];
|
||||
const text = (node) => (typeof node === "string" ? node : node instanceof El ? (node.children.length ? node.children.map(text).join("") : node.textContent) : "");
|
||||
const classed = (node, name) => all(node).filter((el) => (el.attrs.class || "").split(" ").includes(name));
|
||||
const document = {
|
||||
currentScript: null, body: new El("body"), hidden: false, activeElement: null,
|
||||
getElementById: (id) => Object.assign(new El("div"), {textContent: id === "emoji-bases" ? "[]" : ""}),
|
||||
createElement: (tag) => new El(tag), createElementNS: (ns, tag) => new El(tag),
|
||||
};
|
||||
const now = 1_800_000_000;
|
||||
const base = {agent: "Stage 2.0", to: "Stage 2.0", detail: "", green: false, gate: "", score: "", warnings: [], options: [], recommended: "", check: "", command: "", directory: "/repo", sha256: "s", runnable: false, deniable: true, job: null, rule: null, dry_run: null, diff: null, pinned: false, until: 0, held: false, ts: now};
|
||||
const question = "decide: keep or remove the donation section";
|
||||
const options = [{label: "Keep", description: "the section ships with the IAM PR"}, {label: "Remove", description: "drop it before the PR"}];
|
||||
const items = {
|
||||
row: {...base, kind: "operator", id: "operator/donation", title: question, command: question, detail: "Instruction text that asks for donations", check: "decision", options, recommended: "Remove"},
|
||||
other: {...base, kind: "operator", id: "operator/other", title: question, command: question, check: "decision", options},
|
||||
bare: {...base, kind: "operator", id: "operator/bare", title: "decide: rename it", command: "decide: rename it", check: "decision"},
|
||||
orphan: {...base, kind: "operator", id: "operator/orphan", title: question, command: question, check: "decision", options, agent: ""},
|
||||
run: {...base, kind: "operator", id: "operator/run", title: "make install", command: "make install", check: "manual", runnable: true},
|
||||
pick: {...base, kind: "decision", id: "d-1", title: "Layout?", deniable: false, recommended: "B", options: [{label: "A", description: "tabs", preview: "[A]\nline"}, {label: "B", description: "card", preview: "[B]"}, {label: "C", description: "none"}]},
|
||||
};
|
||||
const context = {
|
||||
console, document, JSON, Math, Date, Intl, Promise, Set, Map, Number, String, Array, Object, RegExp, Boolean, Error, setTimeout,
|
||||
Node: El, Element: El, HTMLElement: El,
|
||||
window: {location: {hash: "", hostname: "localhost", port: "8737", pathname: "/"}, setTimeout: () => 0, clearTimeout: () => {}, setInterval: () => 0, clearInterval: () => {}, getSelection: () => "", matchMedia: () => ({matches: false})},
|
||||
state: {inbox: [], radio: [], messages: [], settings: {}, now},
|
||||
ui: {screen: "inbox", busy: false, selected: new Set(), cursor: 0, snoozed: false, asOf: null},
|
||||
known: {batches: new Set()},
|
||||
ViewStore: {get: () => "direct", set: () => {}, on: () => {}},
|
||||
Faces: {SIZE: 64, of: () => ({parts: []})}, speech: {current: null}, openAgent: () => {},
|
||||
denySplit: () => new El("deny"), jobOpen: () => false, load: async () => {},
|
||||
diffBlocks: () => null, feedbackList: () => null, consoleOf: () => null, ruleRequestBody: () => null,
|
||||
items, all, text, classed,
|
||||
};
|
||||
const source = names.map((name) => fs.readFileSync(`${dir}/${name}`, "utf8")).join("\n");
|
||||
const probe = `
|
||||
const sent = [];
|
||||
const toasts = [];
|
||||
const submits = [];
|
||||
radioSend = async (message) => { sent.push(message); return true; };
|
||||
toast = (title) => { toasts.push(title); return {remove() {}}; };
|
||||
submit = async (entries, label) => { submits.push(label); };
|
||||
drawInbox = () => {};
|
||||
const shape = (node) => ({
|
||||
commands: classed(node, "command").length,
|
||||
question: classed(node, "question").map(text),
|
||||
pills: classed(node, "pill").map(text),
|
||||
options: classed(node, "option").filter((el) => el.tag === "button").map((el) => [el.children.map(text)[0], el.getAttribute("disabled") !== null]),
|
||||
other: classed(node, "other").length,
|
||||
choice: classed(node, "choice").length,
|
||||
to: classed(node, "answer-to").map(text),
|
||||
});
|
||||
const optionNamed = (node, label) => classed(node, "option").find((el) => el.tag === "button" && text(el.children[0]) === label);
|
||||
const preview = (node) => classed(node, "choice-preview").map((el) => el.textContent);
|
||||
const results = {};
|
||||
(async () => {
|
||||
results.row = shape(inboxItem(items.row, 0));
|
||||
await optionNamed(inboxItem(items.row, 0), "Keep").fire("click");
|
||||
results.picked = {sent: sent.splice(0), after: shape(inboxItem(items.row, 0))};
|
||||
const form = classed(inboxItem(items.other, 1), "other")[0];
|
||||
all(form).find((el) => el.tag === "input").value = "Ask Main first";
|
||||
await form.fire("submit");
|
||||
results.typed = {sent: sent.splice(0), after: shape(inboxItem(items.other, 1)).pills};
|
||||
results.bare = shape(inboxItem(items.bare, 2));
|
||||
await optionNamed(inboxItem(items.orphan, 3), "Keep").fire("click");
|
||||
results.orphan = {sent: sent.splice(0), toasts: toasts.splice(0)};
|
||||
results.run = shape(inboxItem(items.run, 4));
|
||||
const pick = inboxItem(items.pick, 5);
|
||||
results.pick = {shape: shape(pick), first: preview(pick)};
|
||||
optionNamed(pick, "A").fire("mouseenter");
|
||||
results.pick.hovered = preview(pick);
|
||||
optionNamed(pick, "C").fire("focus");
|
||||
results.pick.empty = preview(pick);
|
||||
await optionNamed(pick, "A").fire("click");
|
||||
results.pick.submits = submits.splice(0);
|
||||
results.pick.sent = sent.splice(0);
|
||||
console.log(JSON.stringify(results));
|
||||
})().catch((error) => { console.error(error && error.stack || error); process.exit(1); });
|
||||
`;
|
||||
vm.runInNewContext(`${source}\n${probe}`, {...context, process});
|
||||
"""
|
||||
|
||||
ANSWER = "Decision operator/donation\nAnswer: Keep"
|
||||
|
||||
|
||||
class TestDecisionRows(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
done = subprocess.run(["node", "-e", PROBE, str(TEMPLATES), json.dumps(MODULES)], capture_output=True, text=True, timeout=60, check=False)
|
||||
if done.returncode != 0:
|
||||
raise AssertionError(done.stderr[-4000:])
|
||||
cls.data = json.loads(done.stdout)
|
||||
|
||||
def test_a_decision_row_reads_as_a_question_with_its_options_and_a_free_answer_not_as_a_command(self):
|
||||
row = self.data["row"]
|
||||
self.assertEqual(row["commands"], 0)
|
||||
self.assertEqual(row["question"], ["decide: keep or remove the donation section"])
|
||||
self.assertIn("Decision", row["pills"])
|
||||
self.assertNotIn("Operator", row["pills"])
|
||||
self.assertEqual(row["options"], [["Keep", False], ["Remove", False]])
|
||||
self.assertEqual(row["other"], 1)
|
||||
self.assertEqual(row["to"], ["Your answer goes to Stage 2.0 as a passkey-signed post, with the row id and your answer only."])
|
||||
|
||||
def test_the_signed_answer_carries_no_text_an_agent_wrote_but_the_answer_and_names_its_recipient(self):
|
||||
picked = self.data["picked"]["sent"][0]
|
||||
self.assertNotIn("donation section", picked["text"])
|
||||
self.assertEqual(picked["to"], "Stage 2.0")
|
||||
|
||||
def test_a_picked_option_is_a_post_to_the_asking_agent_and_the_row_shows_it_answered(self):
|
||||
picked = self.data["picked"]
|
||||
self.assertEqual(picked["sent"], [{"to": "Stage 2.0", "text": ANSWER, "cls": "post", "upload": "", "voice": ""}])
|
||||
self.assertIn("answered: Keep", picked["after"]["pills"])
|
||||
self.assertEqual(picked["after"]["options"], [["Keep", True], ["Remove", True]])
|
||||
|
||||
def test_a_typed_answer_goes_the_same_way(self):
|
||||
typed = self.data["typed"]
|
||||
self.assertEqual([message["text"].split("\n")[1] for message in typed["sent"]], ["Answer: Ask Main first"])
|
||||
self.assertIn("answered: Ask Main first", typed["after"])
|
||||
|
||||
def test_a_row_without_options_still_offers_the_free_answer(self):
|
||||
self.assertEqual((self.data["bare"]["commands"], self.data["bare"]["options"], self.data["bare"]["other"]), (0, [], 1))
|
||||
|
||||
def test_a_row_without_an_adding_agent_sends_nothing_and_says_why(self):
|
||||
self.assertEqual(self.data["orphan"]["sent"], [])
|
||||
self.assertEqual(self.data["orphan"]["toasts"], ["Answer: no agent to send it to"])
|
||||
|
||||
def test_a_runnable_operator_row_keeps_its_command_box(self):
|
||||
self.assertEqual((self.data["run"]["commands"], self.data["run"]["question"], self.data["run"]["other"]), (1, [], 0))
|
||||
|
||||
def test_a_choice_card_shows_the_preview_of_the_focused_option_beside_the_options(self):
|
||||
pick = self.data["pick"]
|
||||
self.assertEqual((pick["shape"]["choice"], pick["shape"]["other"]), (1, 0))
|
||||
self.assertEqual((pick["first"], pick["hovered"], pick["empty"]), (["[B]"], ["[A]\nline"], [""]))
|
||||
self.assertEqual((pick["submits"], pick["sent"]), (["Choice: A"], []))
|
||||
|
||||
|
||||
class TestDecisionFeed(HubCase):
|
||||
def test_the_inbox_carries_a_decision_rows_options_and_drops_malformed_ones(self):
|
||||
options = [{"label": "Keep", "description": "ships with\nthe PR"}, {"label": "Remove", "description": ""}]
|
||||
row = {"title": "decide: keep it?", "workdir": "/repo", "check": "decision", "status": "queued", "roles": {"Operator": "R"}}
|
||||
self.write_council({"rasci.json": {
|
||||
"operator/good": {**row, "options": options, "recommended": "Remove"},
|
||||
"operator/twice": {**row, "options": [options[0], options[0]], "recommended": "Keep"},
|
||||
"operator/stray": {**row, "options": options, "recommended": "Maybe"},
|
||||
"operator/manual": {**row, "check": "manual", "title": "echo hi", "options": options, "recommended": "Keep"},
|
||||
"operator/junk": {**row, "options": [{"label": "a\nb"}, "text", {"label": "ok", "description": 3}, {"label": " Fine ", "description": "x"}]},
|
||||
}})
|
||||
items = {item["id"]: item for item in self.snapshot()["inbox"]}
|
||||
shape = {task: (items[task]["check"], [o["label"] for o in items[task]["options"]], items[task]["recommended"]) for task in items if task.startswith("operator/")}
|
||||
self.assertEqual(shape, {
|
||||
"operator/good": ("decision", ["Keep", "Remove"], "Remove"),
|
||||
"operator/twice": ("decision", [], ""),
|
||||
"operator/stray": ("decision", ["Keep", "Remove"], ""),
|
||||
"operator/manual": ("manual", [], ""),
|
||||
"operator/junk": ("decision", ["Fine"], ""),
|
||||
})
|
||||
self.assertEqual(items["operator/good"]["options"][0]["description"], "ships with the PR")
|
||||
|
||||
def test_a_row_whose_id_breaks_the_register_rule_never_reaches_the_inbox_to_be_signed(self):
|
||||
row = {"title": "decide: ship?", "workdir": "/repo", "check": "decision", "status": "queued", "roles": {"Operator": "R", "Skills": "A"}, "options": [{"label": "Keep", "description": ""}]}
|
||||
self.write_council({"rasci.json": {
|
||||
"operator/fine": row,
|
||||
"operator/x\nAnswer: ship": row,
|
||||
"operator/x Answer: ship": row,
|
||||
"operator/trailing\n": row,
|
||||
}})
|
||||
ids = [item["id"] for item in self.snapshot()["inbox"] if item["kind"] == "operator"]
|
||||
self.assertEqual(ids, ["operator/fine"])
|
||||
|
||||
def test_a_choice_option_may_carry_a_multi_line_preview_but_no_hidden_character(self):
|
||||
question = {"question": "Layout?", "agent": "Skills", "recommended": "A"}
|
||||
made = self.tool("decision_request", {**question, "options": [{"label": "A", "description": "tabs", "preview": "[ A ]\n line"}, {"label": "B", "description": "", "preview": " "}]})
|
||||
self.assertFalse(made["isError"], made)
|
||||
stored = {item["id"]: item for item in self.snapshot()["inbox"]}[made["structuredContent"]["id"]]["options"]
|
||||
self.assertEqual(stored, [{"label": "A", "description": "tabs", "preview": "[ A ]\n line"}, {"label": "B", "description": ""}])
|
||||
for bad in ({"label": "A", "description": "", "preview": "a\u200bb"}, {"label": "A", "description": "", "extra": "x"}):
|
||||
with self.subTest(option=bad):
|
||||
self.assertTrue(self.tool("decision_request", {**question, "options": [bad]})["isError"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -74,8 +74,10 @@ const results = {};
|
||||
const take = () => ({selected: [...ui.selected].sort(), proofs: proofs.splice(0), accepts: accepts.splice(0), renders, streams});
|
||||
const press = (item) => {
|
||||
const first = actionsFor(item)[0];
|
||||
return {pressed: first.getAttribute("aria-pressed"), title: first.getAttribute("title")};
|
||||
return {pressed: first.getAttribute("aria-pressed"), title: first.getAttribute("title"), disabled: Boolean(first.disabled), picked: (first.getAttribute("class") || "").split(" ").includes("picked")};
|
||||
};
|
||||
const labels = (node) => buttons(node).map((button) => button.getAttribute("aria-label"));
|
||||
const byName = (node, label) => buttons(node).find((button) => button.getAttribute("aria-label") === label);
|
||||
(async () => {
|
||||
state.inbox = Object.values(items).map((item) => ({...item}));
|
||||
const of = (key) => state.inbox.find((item) => item.id === items[key].id);
|
||||
@@ -95,17 +97,24 @@ const press = (item) => {
|
||||
results.rule = {...take(), press: press(of("rule"))};
|
||||
grantBoot();
|
||||
const bar = grantView.tray;
|
||||
const modes = grantView.modes;
|
||||
results.tray = {hidden: bar.hidden, text: text(bar), labels: buttons(bar).map((button) => button.getAttribute("aria-label")), modes: modes.map((button) => [button.dataset.mode, button.getAttribute("aria-pressed")]), listen: listeners.map(([path]) => path)};
|
||||
buttons(bar).pop().click();
|
||||
const summary = () => all(bar).find((node) => node.tag === "summary").getAttribute("aria-label");
|
||||
results.tray = {summary: summary(), labels: labels(bar), main: buttons(bar)[0].getAttribute("aria-label"), listen: listeners.map(([path]) => path)};
|
||||
byName(bar, "Remove make install").click();
|
||||
results.unpicked = take();
|
||||
byName(bar, "Clear").click();
|
||||
results.cleared = take();
|
||||
modes[0].click();
|
||||
byName(bar, "Direct").click();
|
||||
results.switched = sets.splice(0);
|
||||
drawGrant();
|
||||
results.direct_tray = {hidden: bar.hidden, children: bar.children.length, modes: modes.map((button) => button.getAttribute("aria-pressed"))};
|
||||
results.direct_tray = {summary: summary(), labels: labels(bar), main: buttons(bar)[0].getAttribute("id")};
|
||||
results.direct_press = press(of("green"));
|
||||
await approveOne(of("green"));
|
||||
results.direct = take();
|
||||
ui.selected.add(keyOf(of("ask")));
|
||||
results.direct_picked = press(of("ask"));
|
||||
drawGrant();
|
||||
results.direct_selection = {main: buttons(bar)[0].getAttribute("aria-label"), labels: labels(bar)};
|
||||
ui.selected.clear();
|
||||
console.log(JSON.stringify(results));
|
||||
})().catch((error) => { console.error(error && error.stack || error); process.exit(1); });
|
||||
`;
|
||||
@@ -132,10 +141,19 @@ class TestGrantMode(unittest.TestCase):
|
||||
self.assertEqual(self.data["collected"]["selected"], ["ask:a-1", "decision:d-1", "operator:operator/run", "review:r-green"])
|
||||
self.assertEqual(self.data["collected"]["proofs"], [])
|
||||
|
||||
def test_the_grant_button_shows_whether_its_item_is_selected(self):
|
||||
def test_a_picked_item_shows_a_pale_green_disabled_grant_button(self):
|
||||
self.assertEqual(self.data["unpressed"]["pressed"], "false")
|
||||
self.assertTrue(self.data["unpressed"]["title"].startswith("Select: "), self.data["unpressed"])
|
||||
self.assertEqual(self.data["pressed"]["pressed"], "true")
|
||||
self.assertEqual((self.data["unpressed"]["disabled"], self.data["unpressed"]["picked"]), (False, False))
|
||||
pressed = self.data["pressed"]
|
||||
self.assertEqual((pressed["pressed"], pressed["disabled"], pressed["picked"]), ("true", True, True))
|
||||
self.assertEqual(pressed["title"], "In the selection: take it out with ✕ in the Grant menu")
|
||||
|
||||
def test_a_checkbox_pick_in_direct_also_turns_the_button_pale_and_opens_the_grant_split(self):
|
||||
picked = self.data["direct_picked"]
|
||||
self.assertEqual((picked["pressed"], picked["disabled"], picked["picked"]), (None, True, True))
|
||||
self.assertEqual(self.data["direct_selection"]["main"], "Grant selection (1)")
|
||||
self.assertEqual(self.data["direct_selection"]["labels"][-1], "Select")
|
||||
|
||||
def test_a_red_gate_and_a_rule_stay_direct_in_select_and_say_why(self):
|
||||
self.assertEqual(self.data["red"]["proofs"], [["review:r-red"]])
|
||||
@@ -145,22 +163,29 @@ class TestGrantMode(unittest.TestCase):
|
||||
self.assertEqual(self.data["rule"]["proofs"], [])
|
||||
self.assertTrue(self.data["rule"]["press"]["title"].endswith(": acts at once, a rule is accepted one at a time"), self.data["rule"])
|
||||
|
||||
def test_the_tray_counts_the_selection_and_holds_its_actions(self):
|
||||
def test_one_split_grants_the_selection_and_its_menu_holds_the_rest(self):
|
||||
tray = self.data["tray"]
|
||||
self.assertFalse(tray["hidden"])
|
||||
self.assertTrue(tray["text"].startswith("4 selected"), tray)
|
||||
self.assertEqual(tray["labels"], ["Grant selection (4)", "Deny selection (2)", "Grant all green (1)", "Clear"])
|
||||
self.assertEqual(tray["modes"], [["direct", "false"], ["select", "true"]])
|
||||
self.assertEqual(tray["main"], "Grant selection (4)")
|
||||
self.assertEqual(tray["summary"], "4 selected")
|
||||
self.assertEqual(tray["labels"], [
|
||||
"Grant selection (4)", "Deny selection (2)", "Grant all green (1)",
|
||||
"Remove feat: green", "Remove git push: ask", "Remove make install", "Remove Which?",
|
||||
"Clear", "Direct",
|
||||
])
|
||||
self.assertEqual(tray["listen"], ["approval"])
|
||||
|
||||
def test_a_picked_item_leaves_the_selection_through_its_menu_entry(self):
|
||||
self.assertEqual(self.data["unpicked"]["selected"], ["ask:a-1", "decision:d-1", "review:r-green"])
|
||||
self.assertEqual(self.data["unpicked"]["proofs"], [])
|
||||
|
||||
def test_clear_empties_the_selection(self):
|
||||
self.assertEqual(self.data["cleared"]["selected"], [])
|
||||
|
||||
def test_the_switch_stores_the_mode_in_the_view_store(self):
|
||||
self.assertEqual(self.data["switched"], [["approval.mode", "direct"]])
|
||||
|
||||
def test_direct_hides_the_tray_and_grants_at_once(self):
|
||||
self.assertEqual(self.data["direct_tray"], {"hidden": True, "children": 0, "modes": ["true", "false"]})
|
||||
def test_direct_without_a_pick_shows_select_and_grants_at_once(self):
|
||||
self.assertEqual(self.data["direct_tray"], {"summary": "0 selected", "labels": ["Select", "Deny selection (0)", "Grant all green (1)", "Clear"], "main": "grant-select"})
|
||||
self.assertEqual(self.data["direct_press"]["pressed"], None)
|
||||
self.assertEqual(self.data["direct_press"]["title"], "Grant")
|
||||
self.assertEqual(self.data["direct"]["proofs"], [["review:r-green"]])
|
||||
|
||||
@@ -161,20 +161,60 @@ async function stalled() {
|
||||
await settle();
|
||||
return {before, after: [done, sandbox.speech.source], waits: waits.map((wait) => wait.ms), stops};
|
||||
}
|
||||
function pressed() {
|
||||
function element(tag, attrs, ...children) {
|
||||
return {
|
||||
tag, attrs: attrs || {}, children: children.flat().filter((child) => child !== null), dataset: {mode: (attrs || {})["data-mode"]}, hidden: Boolean((attrs || {}).hidden),
|
||||
setAttribute(key, value) {
|
||||
this.attrs[key] = value;
|
||||
},
|
||||
replaceChildren(...nodes) {
|
||||
this.children = nodes;
|
||||
},
|
||||
querySelectorAll() {
|
||||
return this.children.filter((child) => child.dataset && child.dataset.mode);
|
||||
},
|
||||
};
|
||||
}
|
||||
function faced(mode) {
|
||||
const calls = [];
|
||||
const sandbox = {RadioSet, h: (tag, attrs, ...children) => ({tag, attrs: attrs || {}, children: children.flat()}), icon: (name) => name, named: (label, hint) => ({"aria-label": label, title: hint})};
|
||||
const sandbox = {RadioSet, radioSet: RadioSet.valid({mode, fallback: "morse"}), settings: {morse: {wpm: 18}}, h: element, icon: (name) => name, named: (label, hint) => ({"aria-label": label, title: hint})};
|
||||
vm.runInNewContext(viewCode, sandbox);
|
||||
sandbox.knobs = () => [];
|
||||
sandbox.morseSpeed = () => element("label", {class: "morse-speed"});
|
||||
sandbox.context = () => calls.push("context");
|
||||
sandbox.keepRadio = (change) => calls.push(change);
|
||||
const modes = sandbox.faceplate({}).children.find((child) => child.attrs["aria-label"] === "Mode");
|
||||
const part = {};
|
||||
const face = sandbox.faceplate(part);
|
||||
const modes = face.children.find((child) => child.attrs["aria-label"] === "Mode");
|
||||
const button = (id) => modes.children.find((child) => child.dataset.mode === id);
|
||||
return {calls, part, modes, button, carets: modes.children.filter((child) => child.children.some((node) => node.attrs && node.attrs.class === "mode-caret")).map((child) => child.dataset.mode)};
|
||||
}
|
||||
function pressed() {
|
||||
const {calls, modes} = faced("silence");
|
||||
modes.children.forEach((button) => button.attrs.on.click());
|
||||
return calls;
|
||||
}
|
||||
function menus() {
|
||||
const out = {};
|
||||
for (const mode of ["auto", "quiet", "morse"]) {
|
||||
const {calls, part, button, carets} = faced(mode);
|
||||
button(mode).attrs.on.click();
|
||||
const opened = {calls: calls.splice(0), menuFor: part.menuFor, hidden: part.face.menu.hidden, shown: part.face.menu.children.map((node) => node.attrs.class), expanded: button(mode).attrs["aria-expanded"]};
|
||||
button(mode).attrs.on.click();
|
||||
const closed = {menuFor: part.menuFor, hidden: part.face.menu.hidden};
|
||||
out[mode] = {carets, opened, closed};
|
||||
}
|
||||
const {calls, part, button} = faced("auto");
|
||||
button("auto").attrs.on.click();
|
||||
const picks = part.face.menu.children[0].children.filter((node) => node.tag === "button").map((node) => [node.attrs["aria-label"], node.attrs["aria-pressed"]]);
|
||||
part.face.menu.children[0].children.find((node) => node.attrs["aria-label"] === "Hiss").attrs.on.click();
|
||||
button("morse").attrs.on.click();
|
||||
out.picks = {picks, calls, menuFor: part.menuFor};
|
||||
return out;
|
||||
}
|
||||
(async () => {
|
||||
console.log(JSON.stringify({
|
||||
auto: await queued(""), silence: await queued("silence"), quiet: await queued("quiet"), stalled: await stalled(), pressed: pressed(),
|
||||
auto: await queued(""), silence: await queued("silence"), quiet: await queued("quiet"), stalled: await stalled(), pressed: pressed(), menus: menus(),
|
||||
}));
|
||||
})();
|
||||
"""
|
||||
@@ -429,6 +469,14 @@ MESSAGES = [
|
||||
TWINS = [*LOG, {"ts": 90, "from": "Docs", "to": [], "class": "newsletter", "text": "twin one"}, {"ts": 90, "from": "Docs", "to": [], "class": "broadcast", "text": "twin two"}]
|
||||
|
||||
|
||||
TONES = ("mayday", "review", "direct", "radio")
|
||||
BELL_SET = {
|
||||
"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}},
|
||||
"classes": ["mayday", "pan-pan", "security", "newsletter"],
|
||||
"muted": ["s1"],
|
||||
}
|
||||
|
||||
|
||||
def run(calls: dict[str, list[list]]) -> dict:
|
||||
done = subprocess.run(["node", "-e", PROBE, str(RADIOSET), json.dumps(calls)], capture_output=True, text=True, timeout=60, check=True)
|
||||
return json.loads(done.stdout)
|
||||
@@ -468,6 +516,9 @@ class TestRadioSetModule(unittest.TestCase):
|
||||
"choices": [["choices", LOG]],
|
||||
"cleared": [["cleared", entries[8]]],
|
||||
"bursts": [["burst", 0.45], ["burst", 0]],
|
||||
"bells": [["bell", BELL_SET, tone] for tone in TONES] + [["bell", {**BELL_SET, "classes": ["mayday", "post"]}, "direct"]],
|
||||
"rings": [["ring", BELL_SET, tone] for tone in TONES],
|
||||
"mutes": [["muting", BELL_SET, "s1"], ["muting", BELL_SET, "s2"]],
|
||||
})
|
||||
cls.modes, cls.lives = modes, lives
|
||||
|
||||
@@ -507,6 +558,21 @@ class TestRadioSetModule(unittest.TestCase):
|
||||
self.assertEqual(self.plan(mode, live, "voiceless"), [])
|
||||
self.assertNotEqual(self.plan("auto", 0, "security"), [])
|
||||
|
||||
def test_each_row_bell_reads_off_tone_or_speak_from_its_tone_and_classes(self):
|
||||
self.assertEqual(self.data["bells"], ["speak", "tone", "tone", "off", "tone"])
|
||||
|
||||
def test_a_bell_press_moves_off_to_tone_to_speak_and_a_row_without_classes_skips_speak(self):
|
||||
mayday, review, direct, radio = self.data["rings"]
|
||||
sounds = BELL_SET["sounds"]
|
||||
self.assertEqual((mayday["sounds"]["mayday"], mayday["classes"]), ({**sounds["mayday"], "on": False}, ["newsletter"]))
|
||||
self.assertEqual((review["sounds"]["review"]["on"], review["classes"]), (False, BELL_SET["classes"]))
|
||||
self.assertEqual((direct["sounds"]["direct"]["on"], direct["classes"]), (True, [*BELL_SET["classes"], "post", "call"]))
|
||||
self.assertEqual((radio["sounds"]["radio"], radio["classes"]), ({**sounds["radio"], "on": True}, ["mayday", "pan-pan", "security"]))
|
||||
self.assertEqual(mayday["sounds"]["review"], sounds["review"])
|
||||
|
||||
def test_muting_toggles_one_agent_and_keeps_the_others(self):
|
||||
self.assertEqual(self.data["mutes"], [{"muted": []}, {"muted": ["s1", "s2"]}])
|
||||
|
||||
def test_the_burst_is_band_passed_noise_of_about_0_6_seconds_at_the_given_loudness(self):
|
||||
loud, silent = self.data["bursts"]
|
||||
self.assertTrue(0.4 <= loud["seconds"] <= 0.8, loud)
|
||||
@@ -598,6 +664,22 @@ class TestTransmit(unittest.TestCase):
|
||||
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", {"mode": "gibberlink"}, "context"])
|
||||
|
||||
def test_a_second_press_on_auto_quiet_or_morse_opens_its_setting_instead_of_switching(self):
|
||||
shown = {"auto": ["chips radio-fallback"], "quiet": ["chips radio-fallback"], "morse": ["morse-speed"]}
|
||||
for mode, menu in self.data["menus"].items():
|
||||
if mode == "picks":
|
||||
continue
|
||||
with self.subTest(mode=mode):
|
||||
self.assertEqual(menu["carets"], ["auto", "quiet", "morse"])
|
||||
self.assertEqual(menu["opened"], {"calls": [], "menuFor": mode, "hidden": False, "shown": shown[mode], "expanded": "true"})
|
||||
self.assertEqual(menu["closed"], {"menuFor": "", "hidden": True})
|
||||
|
||||
def test_the_fallback_menu_picks_the_fallback_and_another_mode_closes_it(self):
|
||||
picks = self.data["menus"]["picks"]
|
||||
self.assertEqual(picks["picks"], [["Gibberlink", "false"], ["Morse", "true"], ["Hiss", "false"]])
|
||||
self.assertEqual(picks["calls"], [{"fallback": "burst"}, {"mode": "morse"}, "context"])
|
||||
self.assertEqual(picks["menuFor"], "")
|
||||
|
||||
|
||||
class TestSpeechModes(unittest.TestCase):
|
||||
@classmethod
|
||||
|
||||
@@ -66,7 +66,7 @@ const find = (node, test, out = []) => {
|
||||
return out;
|
||||
};
|
||||
const sandbox = {
|
||||
Receipts, RadioSet, Node, NS: "svg", HUMAN: "Operator", DAY: 86400, WEEKDAYS: [], revealed: String,
|
||||
Receipts, RadioSet, radioSet: RadioSet.valid({muted: ["s2"]}), Node, NS: "svg", HUMAN: "Operator", DAY: 86400, WEEKDAYS: [], revealed: String,
|
||||
document: {createElement: (tag) => new Node(tag), createElementNS: (ns, tag) => new Node(tag)},
|
||||
relative: {format: () => "ago"}, absolute: {format: (date) => `at ${date.getTime() / 1000}`},
|
||||
Faces: {of: () => ({parts: []}), SIZE: 10}, speech: {current: null}, look: {hidden: new Set()}, PRESENCE: {}, STATUS: {},
|
||||
@@ -82,6 +82,7 @@ const shape = (node) => ({
|
||||
})),
|
||||
more: find(node, (item) => item.attrs.class === "readers-more").map((item) => ({text: text(item), title: item.attrs.title})),
|
||||
groups: find(node, (item) => item.attrs.class === "readers").map((item) => item.attrs["aria-label"]),
|
||||
mutes: find(node, (item) => item.attrs.class === "radio-mute").map((item) => [item.attrs["aria-label"], item.attrs["aria-pressed"], find(item, (part) => part.attrs["data-face"] !== undefined).map((part) => part.attrs["data-face"])]),
|
||||
});
|
||||
console.log(JSON.stringify({
|
||||
events: input.events.map((entry) => shape(sandbox.probe.eventRow(entry))),
|
||||
@@ -885,7 +886,7 @@ class TestReceiptsPage(unittest.TestCase):
|
||||
cls.data = page({
|
||||
"people": {"s2": {"name": "Two", "now": "Two", "names": ["Two"]}},
|
||||
"events": [call, crowd, unnamed],
|
||||
"logs": [log, {**log, "readers": [], "acks": []}, {**log, "readers": readers(9), "acks": []}],
|
||||
"logs": [log, {**log, "readers": [], "acks": []}, {**log, "readers": readers(9), "acks": []}, {**log, "from": "Two", "source": "s2"}, {**log, "source": "s5"}],
|
||||
"strips": [{"readers": readers(8), "acks": ["r7", "gone"]}, {"readers": readers(9), "acks": []}, {}],
|
||||
"labels": [{"name": "Two", "read": 1004, "acked": True}, {"name": "Three", "read": None, "acked": False}, {"name": "Four", "read": 1007, "approximate": True, "acked": False}],
|
||||
"signatures": [
|
||||
@@ -912,12 +913,15 @@ class TestReceiptsPage(unittest.TestCase):
|
||||
self.assertEqual([reader["label"] for reader in call["readers"]], [reader["title"] for reader in call["readers"]])
|
||||
self.assertEqual([reader["face"] for reader in call["readers"]], [["s2"], ["Three"]])
|
||||
self.assertEqual((call["groups"], call["more"]), (["Read by 2"], []))
|
||||
log, silent, _ = self.data["logs"]
|
||||
log, silent = self.data["logs"][:2]
|
||||
self.assertEqual([(reader["session"], reader["badges"]) for reader in log["readers"]], [("s2", 1), ("s3", 0)])
|
||||
self.assertEqual(log["routes"], ["Skills → Main"])
|
||||
self.assertEqual((silent["readers"], silent["groups"]), ([], []))
|
||||
self.assertEqual(self.data["events"][2]["readers"], [])
|
||||
|
||||
def test_a_log_row_from_an_agent_leads_with_its_avatar_that_mutes_it(self):
|
||||
self.assertEqual([row["mutes"] for row in self.data["logs"]], [[], [], [], [["Mute Two", "true", ["s2"]]], [["Mute Skills", "false", ["s5"]]]])
|
||||
|
||||
def test_more_than_eight_readers_collapse_into_plus_n_with_the_full_list_on_hover(self):
|
||||
crowd = self.data["events"][1]
|
||||
self.assertEqual([reader["session"] for reader in crowd["readers"]], [f"r{n}" for n in range(8)])
|
||||
|
||||
@@ -184,6 +184,26 @@ class TestOperator(unittest.TestCase):
|
||||
def _register(self) -> dict[str, dict]:
|
||||
return json.loads((self.root / "rasci.json").read_text(encoding="utf-8"))
|
||||
|
||||
def test_a_decision_row_keeps_its_options_and_pick_and_a_re_add_without_them_drops_both(self):
|
||||
question = ["add", "pick", "--dir", str(self.base), "--command", "decide: keep or remove it", "--reason", "only the operator may", "--check", "decision"]
|
||||
self._out(*question, "--option", "Keep=ships with the PR", "--option", "Remove = drop it first", "--recommended", "Remove")
|
||||
row = self._register()["operator/pick"]
|
||||
self.assertEqual((row["options"], row["recommended"]), ([{"label": "Keep", "description": "ships with the PR"}, {"label": "Remove", "description": "drop it first"}], "Remove"))
|
||||
self._out(*question)
|
||||
self.assertEqual({"options", "recommended"} & set(self._register()["operator/pick"]), set())
|
||||
|
||||
def test_options_need_a_decision_row_distinct_labels_and_a_known_pick(self):
|
||||
add = ["add", "bad", "--dir", str(self.base), "--command", "decide: x", "--reason", "r"]
|
||||
refused = {
|
||||
"manual": self._run(*add[:-2], "--command", "echo hi", "--reason", "r", "--check", "manual", "--option", "A"),
|
||||
"twice": self._run(*add, "--check", "decision", "--option", "A=x", "--option", "A=y"),
|
||||
"unknown pick": self._run(*add, "--check", "decision", "--option", "A", "--recommended", "B"),
|
||||
"pick alone": self._run(*add, "--check", "decision", "--recommended", "A"),
|
||||
"empty label": self._run(*add, "--check", "decision", "--option", "=only text"),
|
||||
}
|
||||
self.assertEqual({name: result.returncode for name, result in refused.items()}, dict.fromkeys(refused, 2))
|
||||
self.assertNotIn("operator/bad", self._register() if (self.root / "rasci.json").exists() else {})
|
||||
|
||||
def _session(self, sid: str, name: str) -> None:
|
||||
(self.home / ".claude" / "sessions" / f"{sid}.json").write_text(json.dumps({"sessionId": sid, "name": name}), encoding="utf-8")
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ const source = given.files.map((name) => fs.readFileSync(`${dir}/${name}`, "utf8
|
||||
class FakeNode {
|
||||
constructor(tag) { this.tag = tag; this.attrs = {}; this.children = []; }
|
||||
setAttribute(key, value) { this.attrs[key] = value; }
|
||||
getAttribute(key) { return key in this.attrs ? this.attrs[key] : null; }
|
||||
append(...children) { this.children.push(...children); }
|
||||
replaceChildren(...children) { this.children = children; }
|
||||
addEventListener() {}
|
||||
|
||||
@@ -221,6 +221,8 @@ class TestRasci(unittest.TestCase):
|
||||
(("set", "work/a", "--after", "work/nope"), "no task of the register"),
|
||||
(("set", "work/new", "--after", "work/nope"), "no task of the register"),
|
||||
(("set", "work/a", "--after", "Bad Task"), "invalid task"),
|
||||
(("set", "work/a", "--after", "work/b\n"), "invalid task"),
|
||||
(("set", "work/new\n"), "invalid task"),
|
||||
):
|
||||
with self.subTest(args=args):
|
||||
result = self._run(*args)
|
||||
|
||||
Reference in new issue
Block a user