feat(hub): requirements 023 to 031 and line comments on grant-time code

023 box heads: one head band per box under its top border; in widget mode
its controls join the widget title band.
024 Match card content: merge cards show their diff (the runner previews a
review's tree against its worktree HEAD), every card carries legal and
architecture scores, the null under command cards is gone.
025 Radio speak card: no hint text, a rounder flowing card, a MAYDAY toggle
beside push to talk.
026 widget zoom: zoom a widget's content by keyboard and the context menu.
027 slash skill suggestions: every field that messages agents suggests
skills after a slash, from a skills index the tree timer writes.
028 Resources accounts: an Accounts panel (provider, renewal, resets, usage
and remaining, host-local, emails never in git) and panel checkboxes.
029 Controls layout: Rules and Groups pages laid out.
030 Yes/No answers as buttons, and nothing hides: rows the runner cannot
run stay greyed with the reason.
031 mic in fields.
Line comments (operator 2026-11-24): wherever code waits for a grant
(Waits on Operator, the stream, the review overlay) selected lines or a
right-clicked row take a comment that marks its lines and collects on the
card; Deny opens with them as the reason and Call preselected, Grant sends
them after the signed grant as one post. Requirement 003 decision 4 and
its contract follow.

Tests are written for every requirement and run once on this head.

🎯 Fix: 80 %
💥 Break: 20 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: ~95 %
🏆 Score: 61
🚦 Gate: ⛔ fix 80 % < 90, break 20 % > 5; security ~95 % < 100: ask the operator before the commit

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-25 01:22:03 +00:00
1 parent 7d1926e3de
commit 2722cda1b5
120 files changed
+5372 -486

No files matched your search

+57 -18
View File
@@ -29,9 +29,11 @@
tokens: add the input, output, cache-read and cache-write tokens of the
usage fields in the Claude Code transcripts under --transcripts since
each file's byte offset to <state>/tokens.jsonl as {t, agent, model,
input, output, cache_read, cache_write}, t the hour; agent is the
name the council claim of the session carries, else the session id's
first 8 characters. A message counts once by its message id and
input, output, cache_read, cache_write, account?}, t the hour; agent
is the name the council claim of the session carries, else the
session id's first 8 characters; account is the email the
SessionStart hook mapped the session to in the council's
session-accounts.jsonl, left out for an unmapped session. A message counts once by its message id and
request id, also when written over several lines or copied into a
fork's transcript. <state>/offsets.json holds {files: {path: offset},
seen: {hour: [key digest]}}, seen keeping the hours this run read and
@@ -97,6 +99,8 @@ HOST_DIGITS = (("cpu", 1), ("ram", 1), ("swap", 1), ("load", 2), ("psi_some", 2)
CLAIMS = ("*/claim.json", "*/*/claim.json")
SAMPLES = "samples.jsonl"
TOKENS = "tokens.jsonl"
SESSION_ACCOUNTS = "session-accounts.jsonl"
EMAIL_CHARS = 254
OFFSETS = "offsets.json"
TICKS = "cpu.json"
SWAPPED = "swap.json"
@@ -115,18 +119,28 @@ def read_text(path: Path) -> str:
return ""
def read_json(path: Path) -> object:
def read_capped(path: Path) -> str:
"""Returns:
The parsed JSON of path, read without following a symlink and only
from a regular file of at most JSON_BYTES; None when that fails.
The text of path, read without following a symlink and only from a
regular file of at most JSON_BYTES; "" when that fails.
"""
try:
with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), "rb") as handle:
if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
return None
return ""
data = handle.read(JSON_BYTES + 1)
return None if len(data) > JSON_BYTES else json.loads(data.decode("utf-8"))
except (OSError, ValueError, RecursionError):
return "" if len(data) > JSON_BYTES else data.decode("utf-8")
except (OSError, ValueError):
return ""
def read_json(path: Path) -> object:
"""Returns:
The parsed JSON of read_capped(path); None when that fails.
"""
try:
return json.loads(read_capped(path))
except (ValueError, RecursionError):
return None
@@ -526,8 +540,12 @@ def retain(rows: list[dict], now: float) -> list[dict]:
def read_rows(path: Path) -> list[dict]:
return json_lines(read_text(path))
def json_lines(text: str) -> list[dict]:
rows = []
for line in read_text(path).splitlines():
for line in text.splitlines():
try:
row = json.loads(line)
except (ValueError, RecursionError):
@@ -608,6 +626,20 @@ def claim_names(council: Path) -> dict[str, str]:
return names
def session_accounts(council: Path) -> dict[str, str]:
"""Returns:
Each session's account email from the lines the SessionStart hook
appends to <council>/session-accounts.jsonl, the last one winning.
Agents may write the file, so it is read through read_capped() and
an email longer than EMAIL_CHARS is dropped.
"""
found = {}
for row in json_lines(read_capped(council / SESSION_ACCOUNTS)):
if isinstance(row.get("session"), str) and isinstance(row.get("email"), str) and len(row["email"]) <= EMAIL_CHARS:
found[row["session"]] = row["email"]
return found
def epoch(value: object) -> float | None:
if not isinstance(value, str):
return None
@@ -700,24 +732,30 @@ def scan(path: Path, start: int, budget: int, seen: dict[int, set[str]]) -> tupl
def token_rows(sums: dict[tuple, list[int]]) -> list[dict]:
"""Args:
sums: per (t, agent, model, width) the counts in COUNTS order.
sums: per (t, agent, model, width, account) the counts in COUNTS
order, account "" for a session the hook mapped to none.
Returns:
One token row per key in key order; a row other than hourly names
its width.
its width, a row of a mapped session its account.
"""
return [{"t": t, "agent": agent, "model": model, **dict(zip(NAMES, counts, strict=True)), **({} if width == HOUR else {"width": width})} for (t, agent, model, width), counts in sorted(sums.items())]
return [
{"t": t, "agent": agent, "model": model, **dict(zip(NAMES, counts, strict=True)), **({} if width == HOUR else {"width": width}), **({"account": account} if account else {})}
for (t, agent, model, width, account), counts in sorted(sums.items())
]
def token_key(row: dict, line: float) -> tuple:
"""Returns:
(t, agent, model, width) of the row a token row merges into: its day
(UTC) when the row is daily or the day ended by line, else its hour.
(t, agent, model, width, account) of the row a token row merges
into: its day (UTC) when the row is daily or the day ended by line,
else its hour.
"""
day = int(row["t"] // DAY * DAY)
account = row["account"] if isinstance(row.get("account"), str) else ""
if row.get("width") == DAY or day + DAY <= line:
return day, row["agent"], row["model"], DAY
return row["t"], row["agent"], row["model"], HOUR
return day, row["agent"], row["model"], DAY, account
return row["t"], row["agent"], row["model"], HOUR, account
def add(sums: dict[tuple, list[int]], key: tuple, counts: tuple[int, ...]) -> None:
@@ -775,6 +813,7 @@ def count_tokens(transcripts: Path, council: Path, state: Path, now: float, budg
offsets = stored.get("files") if isinstance(stored, dict) and isinstance(stored.get("files"), dict) else {}
seen = seen_of(stored.get("seen") if isinstance(stored, dict) else None)
names = claim_names(council)
accounts = session_accounts(council)
sums: dict[tuple, list[int]] = {}
files, touched = {}, set()
for path in sorted(transcripts.rglob("*.jsonl")):
@@ -791,7 +830,7 @@ def count_tokens(transcripts: Path, council: Path, state: Path, now: float, budg
seen.setdefault(hour, set()).update(read)
touched.add(hour)
for ts, session, model, counts in found:
add(sums, (int(ts // HOUR * HOUR), names.get(session) or session[:8], model, HOUR), counts)
add(sums, (int(ts // HOUR * HOUR), names.get(session) or session[:8], model, HOUR, accounts.get(session, "")), counts)
rows = token_rows(sums)
append_rows(state / TOKENS, rows)
kept = {"files": files, "seen": kept_seen(seen, touched, now)}
+40 -4
View File
@@ -220,13 +220,49 @@ def preview(row: dict, rules: Path | None) -> dict | None:
return {"task": row["task"], "command": row["command"], "head": head, **shown}
def review_preview(row: dict, rules: Path | None) -> dict | None:
"""Args:
row: a pending review that shipped no diff, with id, worktree, tree
and head, the HEAD the hub last saw, None for none.
rules: the MEDUSA rules directory.
Returns:
{id, head, diff}: the review's tree against its worktree's HEAD
(staged_diff.tree_diff), or {id, head, error} when it cannot be
built; None while HEAD is the one the hub saw.
"""
try:
head = staged_diff.head_of(Path(row["worktree"]))
except PREVIEW_FAILURES as error:
head, shown = "", {"error": str(error)[:ERROR_LIMIT]}
else:
shown = None
if head == row["head"]:
return None
if shown is None:
try:
shown = {"diff": staged_diff.tree_diff(Path(row["worktree"]), row["tree"], rules)[0]}
except PREVIEW_FAILURES as error:
shown = {"error": str(error)[:ERROR_LIMIT]}
return {"id": row["id"], "head": head, **shown}
def oversized(shown: dict, keys: tuple[str, ...]) -> dict:
if len(json.dumps(shown).encode()) <= hub_limits.DIFF_BODY_LIMIT:
return shown
return {**{key: shown[key] for key in keys}, "error": f"the preview passes the hub's {hub_limits.DIFF_BODY_LIMIT} bytes"}
def previews(base: str, rules: Path | None) -> None:
for row in call(base, PREVIEWS, None)["rows"]:
listed = call(base, PREVIEWS, None)
for row in listed["rows"]:
shown = preview(row, rules)
if shown is not None and len(json.dumps(shown).encode()) > hub_limits.DIFF_BODY_LIMIT:
shown = {"task": row["task"], "command": row["command"], "head": shown["head"], "error": f"the preview passes the hub's {hub_limits.DIFF_BODY_LIMIT} bytes"}
if shown is not None:
call(base, PREVIEWS, shown)
call(base, PREVIEWS, oversized(shown, ("task", "command", "head")))
for row in listed["reviews"]:
shown = review_preview(row, rules)
if shown is not None:
call(base, PREVIEWS, oversized(shown, ("id", "head")))
def council_refusal(council: Path) -> str | None:
+4 -3
View File
@@ -209,12 +209,13 @@ def digest(data: bytes | None) -> str:
def view_of(path: str) -> dict:
"""Returns:
{"path", "exists", "sha256", "error", "settings"}: settings only the
{"path", "exists", "folder", "sha256", "error", "settings"}: folder
False when the path's directory is missing, settings only the
permissions and sandbox sections; error why the file was unreadable,
for anything unforeseen only the exception's class, so one bad path
never keeps the others or the view from being written.
"""
entry = {"path": path, "exists": False, "sha256": "", "error": "", "settings": {}}
entry = {"path": path, "exists": False, "folder": True, "sha256": "", "error": "", "settings": {}}
try:
return read_view(path, entry)
except Exception as error: # noqa: BLE001
@@ -225,7 +226,7 @@ def read_view(path: str, entry: dict) -> dict:
try:
parent = parent_of(path)
except FileNotFoundError:
return {**entry, "error": MISSING_DIRECTORY}
return {**entry, "folder": False, "error": MISSING_DIRECTORY}
except OSError as error:
return {**entry, "error": f"a link or no directory on the path: {error.strerror}"}
try:
+143
View File
@@ -0,0 +1,143 @@
#!/usr/bin/env python3
"""Args:
--home: the home whose ~/.claude/skills and ~/.agents/skills are read.
--tree: the branch-tree.json pkgmgr branch tree writes; each of its
repositories' .claude/skills and .agents/skills are read.
--output: the index the Agent Orchestrator serves at /api/skills, e.g.
~/.local/state/pkgmgr/tree/skills-index.json.
Returns:
Runs on the host, because the hub's container sees no repository:
replaces --output with {"written": <epoch>, "skills": [{"name",
"description", "source"}]}, one entry per skill folder holding a
SKILL.md, sorted by name and source; source is ~/.claude/skills,
~/.agents/skills or the repository's path. The exit code is 0.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import stat
import tempfile
import time
from pathlib import Path
HOME_SOURCES = (".claude/skills", ".agents/skills")
SKILL_FILE = "SKILL.md"
HEAD_BYTES = 16384
TREE_BYTES = 8 << 20
NAME = re.compile(r"[A-Za-z0-9:_.-]{1,100}")
DESCRIPTION_CHARS = 300
FIELD = re.compile(r"^(name|description):[ \t]*(.*)$")
BLOCKS = (">", "|", ">-", "|-", ">+", "|+")
def read_head(path: Path, limit: int) -> str:
"""Returns:
The first limit bytes of path as text, read without following a
symlink and only from a regular file.
Raises:
OSError: path is missing, a symlink or no regular file.
"""
handle = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
with os.fdopen(handle, "rb") as stream:
if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode):
raise OSError(f"{path}: no regular file")
return stream.read(limit).decode("utf-8", "replace")
def front_matter(text: str) -> dict[str, str]:
"""Returns:
name and description from the YAML front matter that opens text,
each one line with its quotes stripped, a folded or literal block
joined into it; none without a closed front matter.
"""
lines = text.splitlines()
if not lines or lines[0].strip() != "---":
return {}
found, folding = {}, None
for line in lines[1:]:
if line.strip() == "---":
return {key: " ".join(value.split()) for key, value in found.items()}
match = FIELD.match(line)
if match:
value = match.group(2).strip()
folding = match.group(1) if value in BLOCKS else None
found[match.group(1)] = "" if folding else value.strip("\"'")
elif folding and line[:1] in (" ", "\t"):
found[folding] += f" {line.strip()}"
else:
folding = None
return {}
def skill_of(folder: Path, source: str) -> dict | None:
"""Returns:
{name, description, source} of a skill folder: the front matter's
name, else the folder's; None without a readable SKILL.md or with a
name outside NAME.
"""
try:
fields = front_matter(read_head(folder / SKILL_FILE, HEAD_BYTES))
except OSError:
return None
name = fields.get("name") or folder.name
if not NAME.fullmatch(name):
return None
return {"name": name, "description": fields.get("description", "")[:DESCRIPTION_CHARS], "source": source}
def skills_in(root: Path, source: str) -> list[dict]:
try:
folders = sorted(path for path in root.iterdir() if path.is_dir())
except OSError:
return []
return [found for folder in folders if (found := skill_of(folder, source)) is not None]
def repositories(tree: Path) -> list[str]:
"""Returns:
The absolute repository paths of the branch tree; none when it is
unreadable.
"""
try:
scan = json.loads(read_head(tree, TREE_BYTES))
except (OSError, ValueError, RecursionError):
return []
repos = scan.get("repos") if isinstance(scan, dict) else None
return sorted({repo["path"] for repo in repos if isinstance(repo, dict) and isinstance(repo.get("path"), str) and repo["path"].startswith("/")}) if isinstance(repos, list) else []
def index(home: Path, tree: Path) -> list[dict]:
found = [skill for part in HOME_SOURCES for skill in skills_in(home / part, f"~/{part}")]
found += [skill for repo in repositories(tree) for part in HOME_SOURCES for skill in skills_in(Path(repo) / part, repo)]
unique = {(skill["name"], skill["source"]): skill for skill in found}
return [unique[key] for key in sorted(unique)]
def write(output: Path, data: dict) -> None:
with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=output.parent, prefix=f".{output.name}.", delete=False) as handle:
try:
json.dump(data, handle)
except BaseException:
os.unlink(handle.name)
raise
os.replace(handle.name, output)
def main() -> int:
parser = argparse.ArgumentParser(description="Index the skills an agent message may name for the Agent Orchestrator.")
parser.add_argument("--home", type=Path, required=True)
parser.add_argument("--tree", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
write(args.output, {"written": time.time(), "skills": index(args.home, args.tree)})
return 0
if __name__ == "__main__":
raise SystemExit(main())
+168
View File
@@ -0,0 +1,168 @@
from __future__ import annotations
import contextlib
import datetime
import re
from pathlib import Path
from .errors import Missing, ToolError
from .fields import FIELDS, decode, visible
from .ledger import Ledger
from .records import read_jsonl
from .resources import HOUR, RESOURCES, TOKENS, rows_between
from .settings import flag, section
ACCOUNTS = "accounts.json"
SESSION_ACCOUNTS = "session-accounts.jsonl"
KEYS = ("provider", "email", "renewal", "reset", "resubscribe", "autorenew", "limit", "note")
MOMENT = ("day", "time")
EMAIL = re.compile(r"[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9-]{1,63}(?:\.[A-Za-z0-9-]{1,63})*\.[A-Za-z]{2,24}")
TIME = re.compile(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]")
DATE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
PROVIDER = re.compile(r"(?=[^\x00-\x1f\x7f]*\S)[^\x00-\x1f\x7f]{1,40}")
NOTE_LIMIT = 200
LIMIT_CAP = 10**15
RECENT = 8 * 24 * HOUR
COUNTS = ("input", "output", "cache_read", "cache_write")
def moment(value: object, name: str) -> dict:
"""Returns:
{day, time}: day 0 for Sunday to 6 for Saturday as Date.getDay()
counts, time HH:MM local; anything else raises ToolError.
"""
data = section(value, name, MOMENT)
day, time = data["day"], data["time"]
if isinstance(day, bool) or not isinstance(day, int) or not 0 <= day <= 6:
raise ToolError(f"{name}.day must be a weekday from 0 (Sunday) to 6 (Saturday)")
if not isinstance(time, str) or not TIME.fullmatch(time):
raise ToolError(f"{name}.time must be a time HH:MM")
return {"day": day, "time": time}
def resubscribe(value: object) -> str:
if value == "":
return ""
if isinstance(value, str) and DATE.fullmatch(value):
with contextlib.suppress(ValueError):
return datetime.date.fromisoformat(value).isoformat()
raise ToolError("resubscribe must be a date YYYY-MM-DD or empty")
def valid_account(raw: object) -> dict:
"""Args:
raw: the account as the page sent it, every key of KEYS.
Returns:
The account; a missing or unknown key, a bad email, weekday, time or
date, or a negative limit raises ToolError.
"""
data = section(raw, "account", KEYS)
if not isinstance(data["provider"], str) or not PROVIDER.fullmatch(data["provider"]):
raise ToolError("provider must be one line of 1 to 40 characters")
if not isinstance(data["email"], str) or not EMAIL.fullmatch(data["email"]):
raise ToolError("email must be an address like name@example.org")
limit = data["limit"]
if limit is not None and (isinstance(limit, bool) or not isinstance(limit, int) or not 0 <= limit <= LIMIT_CAP):
raise ToolError(f"limit must be empty or a whole number of tokens from 0 to {LIMIT_CAP}")
if not isinstance(data["note"], str) or len(data["note"]) > NOTE_LIMIT:
raise ToolError(f"note must be text of at most {NOTE_LIMIT} characters")
account = {
"provider": data["provider"].strip(),
"email": data["email"],
"renewal": moment(data["renewal"], "renewal"),
"reset": moment(data["reset"], "reset"),
"resubscribe": resubscribe(data["resubscribe"]),
"autorenew": flag(data["autorenew"], "autorenew"),
"limit": limit,
"note": data["note"].strip(),
}
visible({"provider": account["provider"], "note": account["note"]})
return account
def mapping(file: Path) -> dict[str, str]:
"""Returns:
Each session's email, the last line the SessionStart hook wrote for
it winning, in the order the sessions first appear.
"""
found: dict[str, str] = {}
for row in read_jsonl(file):
session, email = row.get("session"), row.get("email")
if isinstance(session, str) and isinstance(email, str) and EMAIL.fullmatch(email):
found[session] = email
return found
def active(file: Path) -> str | None:
"""Returns:
The email of the newest mapping line: the account the host's
Claude Code logged in with at the last session start.
"""
emails = [row.get("email") for row in read_jsonl(file)]
valid = [email for email in emails if isinstance(email, str) and EMAIL.fullmatch(email)]
return valid[-1] if valid else None
def usage(rows: list[dict], now: float) -> dict[str, dict]:
"""Args:
rows: token rows {t, agent, model, input, output, cache_read,
cache_write, account?, width?}.
now: the epoch seconds the recent hours end at.
Returns:
Per account email, "" for rows of no mapped session: {total, hours},
total the tokens of every row, hours [t, tokens] per hourly row of
the last 8 days in time order, for the page to sum from the local
weekly reset and midnight.
"""
found: dict[str, dict] = {}
for row in rows:
account = row.get("account") if isinstance(row.get("account"), str) else ""
tokens = sum(value for value in (row.get(name) for name in COUNTS) if isinstance(value, int) and not isinstance(value, bool) and value > 0)
entry = found.setdefault(account, {"total": 0, "hours": {}})
entry["total"] += tokens
t = row.get("t")
if "width" not in row and isinstance(t, int | float) and now - RECENT <= t <= now:
entry["hours"][int(t)] = entry["hours"].get(int(t), 0) + tokens
return {account: {"total": entry["total"], "hours": sorted(entry["hours"].items())} for account, entry in found.items()}
class Accounts:
def __init__(self, state: Path, kept: Path, council: Path) -> None:
self.ledger = Ledger(state / ACCOUNTS)
self.tokens = kept / RESOURCES / TOKENS
self.sessions = council / SESSION_ACCOUNTS
def view(self, now: float) -> dict:
"""Returns:
{accounts, active, usage}: the stored accounts, the active
account's email or None, and usage() of every token row.
"""
return {"accounts": self.ledger.listed(), "active": active(self.sessions), "usage": usage(rows_between(self.tokens, 0, now, 0), now)}
def save(self, body: bytes) -> dict:
"""Args:
body: {account, id}: id "" adds the account, else it replaces
the account of that id.
"""
data = section(decode(body), "body", ("account", "id"))
account = valid_account(data["account"])
if data["id"] == "":
return self.ledger.add(account)
changed = self.ledger.change(self.known(data), account)
if changed is None:
raise Missing("no such account")
return changed
def drop(self, account_id: str) -> dict:
if not self.ledger.remove(account_id):
raise Missing("no such account")
return {"removed": account_id}
@staticmethod
def known(data: dict) -> str:
pattern, hint = FIELDS["id"]
if not isinstance(data["id"], str) or not pattern.fullmatch(data["id"]):
raise ToolError(f"id must be empty or {hint}")
return data["id"]
+6 -5
View File
@@ -253,22 +253,23 @@ class Firewall:
def settings_files(self) -> tuple[list[dict], dict]:
"""Returns:
The listed settings files the host writer last read, each
{"path", "exists", "sha256", "error", "settings", "own"} with
settings only the part signing.settings_view() keeps, and the
view's written time, error and tools_of().
{"path", "exists", "folder", "sha256", "error", "settings", "own"}
with settings only the part signing.settings_view() keeps and
folder False only when the writer found no directory for the
path, and the view's written time, error and tools_of().
"""
view = read_json(self.firewall_spool.root / VIEW)
files = view.get("files") if isinstance(view, dict) else None
if not isinstance(files, list):
return [], {"written": None, "error": "no settings view yet: the kvb-orchestrator-firewall unit writes it on the host", "tools": None}
shown = [{**entry, "settings": signing.settings_view(entry["settings"]), "error": str(entry.get("error") or ""), "own": entry.get("own") is True} for entry in files if shaped_file(entry)]
shown = [{**entry, "settings": signing.settings_view(entry["settings"]), "error": str(entry.get("error") or ""), "folder": entry.get("folder") is not False, "own": entry.get("own") is True} for entry in files if shaped_file(entry)]
return shown, {"written": view.get("written"), "error": "", "tools": tools_of(shown, view.get("known"))}
def firewall(self) -> dict:
files, meta = self.settings_files()
now = time.time()
asks = self.recent_subjects("ask", now)
listed = [{key: entry[key] for key in ("path", "exists", "sha256", "error")} | {"groups": counted(grouped(entry["settings"].get("permissions")), asks, now), "sandbox": sandbox_entries(entry["settings"].get("sandbox"), "sandbox")} for entry in files]
listed = [{key: entry[key] for key in ("path", "exists", "folder", "sha256", "error")} | {"groups": counted(grouped(entry["settings"].get("permissions")), asks, now), "sandbox": sandbox_entries(entry["settings"].get("sandbox"), "sandbox")} for entry in files]
rules = {rule["id"]: stored_hits(rule, asks, now) for rule in self.rules.listed()}
return {**meta, "files": listed, "lists": list(signing.SETTINGS_LISTS), "patterns": deny_patterns(), "groups": self.groups.listed(), "sets": self.rule_sets.listed(), "days": RECENT_DAYS, "rules": rules}
+14 -2
View File
@@ -13,6 +13,7 @@ from .exchange import PLAIN_CSP, Exchange
from .rates import rated
from .resources import RESOURCES, sampled
from .scores import scored
from .skillindex import SKILLS_INDEX, served
BODY_LIMIT = 1 << 20
UPLOAD_LIMIT = 50 << 20
@@ -78,7 +79,9 @@ FIREWALL_STATE = re.compile(r"/api/firewall/settings/([0-9a-f]{16})")
FIREWALL_DROP = re.compile(r"/api/firewall/(groups|sets)/([0-9a-f]{16})/delete")
FIREWALL_STATUS = {"settings_preview": HTTPStatus.OK, "change_settings": HTTPStatus.ACCEPTED, "add_group": HTTPStatus.CREATED, "add_set": HTTPStatus.CREATED}
WAV_POSTS = (STT_ROUTE, VOICE_ROUTE)
ACTION_POSTS = ("/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS)
ACCOUNTS_ROUTE = "/api/accounts"
ACCOUNT_DROP = re.compile(r"/api/accounts/([0-9a-f]{16})/delete")
ACTION_POSTS = (ACCOUNTS_ROUTE, "/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS)
class Handler(Exchange):
@@ -137,8 +140,12 @@ class Handler(Exchange):
self.answer(lambda: hub.events(self.query()), HTTPStatus.OK)
elif path == "/api/tree":
self.answer(hub.repositories, HTTPStatus.OK)
elif path == "/api/skills":
self.answer(lambda: served(hub.tree.file.with_name(SKILLS_INDEX)), HTTPStatus.OK)
elif path == MATCH_ROUTE:
self.answer(hub.match_cards, HTTPStatus.OK)
elif path == ACCOUNTS_ROUTE:
self.answer(lambda: hub.accounts.view(time.time()), HTTPStatus.OK)
elif path == "/api/resources":
self.answer(lambda: sampled(hub.kept / RESOURCES, hub.span(self.query(), time.time())), HTTPStatus.OK)
elif path == "/api/scores":
@@ -182,6 +189,11 @@ class Handler(Exchange):
return lambda body: self.answer(lambda: hub.sign_board(body), HTTPStatus.OK)
if board:
return lambda body: self.answer(lambda: hub.board(board.group(1), body), HTTPStatus.OK)
drop = ACCOUNT_DROP.fullmatch(path)
if path == ACCOUNTS_ROUTE:
return lambda body: self.answer(lambda: hub.accounts.save(body), HTTPStatus.OK)
if drop:
return lambda _body: self.answer(lambda: hub.accounts.drop(drop.group(1)), HTTPStatus.OK)
reveal = REVEAL_ROUTE.fullmatch(path)
if reveal:
method = hub.sign_reveal if reveal.group(3) else hub.reveal
@@ -263,7 +275,7 @@ class Handler(Exchange):
return None
def posted(self, path: str) -> bool:
return any(pattern.fullmatch(path) for pattern in (INBOX_ROUTE, UNDO_ROUTE, RULE_ROUTE, REQUEST_ROUTE, RUNNER_ROUTE, FIREWALL_DROP, REVEAL_ROUTE))
return any(pattern.fullmatch(path) for pattern in (INBOX_ROUTE, UNDO_ROUTE, RULE_ROUTE, REQUEST_ROUTE, RUNNER_ROUTE, FIREWALL_DROP, REVEAL_ROUTE, ACCOUNT_DROP))
def runner(self, path: str, body: bytes) -> None:
hub = self.server.hub
+3
View File
@@ -10,6 +10,7 @@ from pathlib import Path
import jinja2
from markupsafe import Markup
from .accounts import Accounts
from .approving import Approving
from .artifacts import Touched
from .asking import Asking
@@ -140,6 +141,7 @@ class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Den
match_snapshots: Ledger
merge_previews: Ledger
live_state: LiveState
accounts: Accounts
def hosts(self) -> tuple[str, str]:
return f"127.0.0.1:{self.public_port}", f"localhost:{self.public_port}"
@@ -208,6 +210,7 @@ def open_hub(council: Path, pages: Path, public_port: int, state: Path, host_sta
voice_notes=VoiceNotes(state / "voice", host_state / "voice", speech, lambda: {message["voice"] for message in messages.listed() if message.get("voice")}),
replay=state / "replay" / "messages.json",
view_store=ViewStore(state / "view.json"),
accounts=Accounts(state, places.kept, council),
match_snapshots=Ledger(state / "match.json"),
merge_previews=Ledger(state / "previews.json"),
live_state=LiveState(live_ttl),
+4 -3
View File
@@ -8,7 +8,7 @@ from .council import read_claims
from .denying import requester_of
from .errors import ToolError
from .fields import decode, expect
from .jobs import console_of
from .jobs import console_of, row_blocked
from .names import Directory
from .records import digest, iso_epoch
from .register import adder, operator_rows, runnable
@@ -21,7 +21,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": "", "multi": False, "check": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False, "answered": "", "reviews": []}
base = {"agent": "", "to": "", "detail": "", "green": False, "gate": "", "score": "", "warnings": [], "options": [], "recommended": "", "multi": False, "check": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False, "answered": "", "reviews": [], "blocked": ""}
items = []
for review in self.reviews.pending():
created = iso_epoch(review["created"]) or now
@@ -38,6 +38,7 @@ class Inbox:
fields = {"title": decision["question"][:300], "agent": decision["agent"], "green": recommended != "", "options": decision["options"], "recommended": recommended, "multi": bool(decision.get("multi"))}
items.append({**base, "kind": "decision", "id": decision["id"], "ts": decision["created_ts"], **fields})
held = self.open_jobs()
reasons = self.blocked_rows(now)
consoles = self.consoles()
pattern = task_pattern(self.scripts.skills)
rows = [row for row in operator_rows(tasks) if pattern is not None and pattern.fullmatch(row["task"])]
@@ -45,7 +46,7 @@ class Inbox:
busy = row["task"] in held
answer = self.answers.get(row["task"])
fields = {"answered": answer["label"] if answered(answer, row) else "", "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"])), "reviews": self.linked(row["command"])}
state = {"runnable": runnable(row) and not busy, "deniable": not busy, "job": console_of(consoles.get(row["task"])), "reviews": self.linked(row["command"]), "blocked": row_blocked(row, reasons)}
items.append({**base, "kind": "operator", "id": row["task"], "ts": self.watch.first(row["task"], now), **fields, **state})
listed = {row["task"] for row in rows}
for task, job in consoles.items():
+42
View File
@@ -14,6 +14,7 @@ CONSOLE = ("id", "status", "code", "output", "created_ts", "started", "finished"
TASK_JOB = "task"
GATE_JOB = "gate"
CHANGES = (TASK_JOB, GATE_JOB)
UNRUNNABLE = "The hub runner needs a command and an absolute directory, and this row lacks one; run it with operator.py run in a terminal."
def runner_job(job: dict) -> dict:
@@ -32,10 +33,51 @@ def console_of(job: dict | None) -> dict | None:
return None if job is None else {**{key: job[key] for key in CONSOLE}, "output": job["output"][-OUTPUT_LIMIT:]}
def minutes_since(ts: float | None, now: float) -> int:
return max(0, round((now - (ts or now)) / 60))
def blocked_reasons(jobs: list[dict], now: float) -> dict[str, str]:
"""Args:
jobs: every hub job record.
Returns:
Per task with a queued or running job why its row cannot be run or
denied now: how long the runner runs it, or how long it waits and
which job the runner, which runs one job at a time, started last.
"""
open_jobs = [job for job in jobs if job["status"] in JOB_OPEN]
running = max((job for job in open_jobs if job["status"] == "running"), key=lambda job: job["started"] or 0, default=None)
ahead = "" if running is None else f" behind {running['task']}, which runs for {minutes_since(running['started'], now)} min"
reasons = {}
for job in sorted(open_jobs, key=lambda job: job["created_ts"]):
if job["status"] == "running":
reasons[job["task"]] = f"The hub runner runs it for {minutes_since(job['started'], now)} min; its result comes in Waits on Operator."
else:
reasons[job["task"]] = f"Queued in the hub runner for {minutes_since(job['created_ts'], now)} min{ahead}; the runner runs one job at a time."
return reasons
def row_blocked(row: dict, reasons: dict[str, str]) -> str:
"""Args:
row: an open operator row.
reasons: blocked_reasons() of the hub jobs.
Returns:
Why no area can run or deny the row now, "" when one can: its open
hub job, else for a command row without a command or an absolute
directory UNRUNNABLE; a decision row is answered, never run.
"""
return reasons.get(row["task"]) or ("" if row["check"] == "decision" or runnable(row) else UNRUNNABLE)
class Jobs:
def open_jobs(self) -> set[str]:
return {job["task"] for job in self.jobs.listed() if job["status"] in JOB_OPEN}
def blocked_rows(self, now: float) -> dict[str, str]:
return blocked_reasons(self.jobs.listed(), now)
def consoles(self) -> dict[str, dict]:
latest: dict[str, dict] = {}
for job in sorted(self.jobs.listed(), key=lambda job: job["created_ts"]):
+24 -6
View File
@@ -8,6 +8,7 @@ from .denying import requester_of
from .diffs import stored_diff
from .errors import Conflict, Missing, ToolError
from .fields import decode, expect, field
from .jobs import row_blocked
from .payloads import denied_roots, payload_files, payload_hash
from .previewing import merge_hash
from .records import digest, iso_epoch, read_jsonl
@@ -59,8 +60,8 @@ class Matching:
senders = {review["id"]: review.get("agent", "") for review in reviews}
cards = [{**self.commit_card(review, born_of(senders[review["id"]], names, claims), labels), "to": requester_of(claims, senders[review["id"]])[0]} for review in reviews if not self.batches.holds("review", review["id"])]
tasks = read_register(self.council / REGISTER)
held = self.open_jobs()
rows = [row for row in operator_rows(tasks) if row["check"] != "decision" and row["task"] not in held]
blocked = self.blocked_rows(now)
rows = [row for row in operator_rows(tasks) if row["check"] != "decision"]
releasing = {f"operator:{row['task']}" for row in rows if self.batches.holds("operator", row["task"])}
roots = denied_roots(self.settings_files()[0])
scan = self.tree.get()
@@ -68,7 +69,7 @@ class Matching:
if f"operator:{row['task']}" in releasing:
continue
owner = adder(tasks[row["task"]])
cards.append({**self.command_card(row, owner, born_of(owner, names, claims), roots, scan, labels), "to": requester_of(claims, owner)[0]})
cards.append({**self.command_card(row, owner, born_of(owner, names, claims), roots, scan, labels), "to": requester_of(claims, owner)[0], "blocked": row_blocked(row, blocked)})
items = self.inbox(now, tasks, self.directory(claims, read_jsonl(self.council / NEWS), now))
cards += [self.waiting_card(item, born_of(item["agent"], names, claims), scan, labels) for item in items if self.waits(item)]
asked = {row["task"] for row in operator_rows(tasks) if row["check"] == "decision"}
@@ -82,6 +83,17 @@ class Matching:
store.remove(snapshot["id"])
return {"now": now, "cards": cards}
def match_open(self, inbox: list[dict]) -> int:
"""Returns:
How many cards match_cards() lists that can be decided, by its
filters without building them: pending reviews, open command rows
not held by a release and without a row_blocked() reason, and the
inbox items waits() keeps.
"""
reviews = sum(1 for review in self.reviews.pending() if not self.batches.holds("review", review["id"]))
rows = sum(1 for row in self.open_rows() if not self.batches.holds("operator", row["task"]) and not row_blocked(row, {}))
return reviews + rows + sum(1 for item in inbox if self.waits(item))
def commit_card(self, review: dict, born: float | None, labels: dict | None) -> dict:
live = review.get("live_tree")
reason = "the staged tree changed since it was added" if live not in (None, review["tree"]) else ""
@@ -89,12 +101,17 @@ class Matching:
files = stored_diff(self.reviews.pages, "review", review["id"])["diff"]
except Missing:
files = None
preview = self.review_preview(review["id"])
if preview is not None:
files = preview.get("diff")
reason = reason or ("HEAD moved since it was added" if preview.get("moved") else "")
place = {"repo": repository_of(review.get("repo", "")), "branch": review["branch"], "worktree": review["worktree"]}
return {
"id": f"review:{review['id']}", "kind": "commit", "ref": review["id"], "agent": review.get("agent", ""), "born": born, "created_ts": iso_epoch(review["created"]),
**place, "title": review["title"], "score": review.get("score", ""), "metrics": metric_chips(review.get("score", ""), labels, True), "gate": review.get("gate", ""),
"hash": review["tree"], "live_hash": live or review["tree"],
"stale": bool(reason), "stale_reason": reason, "files": files, "command": "", "directory": review["worktree"], "reason": "",
"diff_error": None if preview is None else preview.get("error"),
}
def card_payload(self, row: dict, roots: list[str] | None) -> tuple[list[dict], str, dict | None]:
@@ -113,10 +130,11 @@ class Matching:
"""Returns:
Whether an inbox item is a Match card of its own: an ask, a
choice, a rule request, or a decision row not yet answered with
its current question, none held by a release in its undo window;
commits and commands have their own cards.
its current question, none held by a release in its undo window
nor snoozed in Waits on Operator; commits and commands have their
own cards.
"""
if item["held"]:
if item["held"] or item["until"]:
return False
if item["kind"] == "operator":
return item["check"] == "decision" and not item["settled"] and item["job"] is None and not item["answered"]
+60 -7
View File
@@ -4,9 +4,9 @@ import json
import re
import time
from .diffs import valid_diff
from .diffs import stored_diff, valid_diff
from .errors import Conflict, Missing, ToolError
from .fields import bounded, decode, expect
from .fields import bounded, decode, expect, field
from .records import digest
from .register import OPERATOR, REGISTER, operator_rows, read_register
from .signed import signing
@@ -15,12 +15,18 @@ OBJECT_ID = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}")
ERROR_LIMIT = 500
SHOWN = ("task", "command", "head", "base", "target", "diff")
FAILED = ("task", "command", "head", "error")
REVIEW_SHOWN = ("id", "head", "diff")
REVIEW_FAILED = ("id", "head", "error")
def card_id(task: str) -> str:
return f"operator:{task}"
def review_card(review_id: str) -> str:
return f"review:{review_id}"
def object_id(payload: dict, name: str, empty: bool) -> str:
value = payload[name]
if not isinstance(value, str) or not (OBJECT_ID.fullmatch(value) or (empty and value == "")):
@@ -51,22 +57,69 @@ class Previewing:
found = self.merge_previews.get(card_id(row["task"]))
return found if found is not None and found["command"] == row["command"] else None
def shipped(self, review_id: str) -> bool:
try:
return bool(stored_diff(self.reviews.pages, "review", review_id)["diff"])
except Missing:
return False
def review_preview(self, review_id: str) -> dict | None:
"""Returns:
The runner's diff of a review that shipped none, its staged tree
against its worktree's HEAD: {head, diff} or {head, error}, with
moved, the HEAD it saw later, once HEAD moved; None before any.
"""
return None if self.shipped(review_id) else self.merge_previews.get(review_card(review_id))
def preview_rows(self) -> dict:
"""Returns:
{"rows"}: every open operator row in an absolute directory with
the HEAD of the preview the hub holds, None for none, for the
runner to preview the git merges among them.
{"rows", "reviews"}: every open operator row in an absolute
directory with the HEAD of the preview the hub holds, None for
none, for the runner to preview the git merges among them; and
every pending review in an absolute worktree that shipped no
diff, with its tree and the HEAD the hub last saw, for the
runner to diff the tree against HEAD.
"""
rows = [row for row in self.open_rows() if row["directory"].startswith("/")]
return {"rows": [{"task": row["task"], "command": row["command"], "directory": row["directory"], "head": (self.preview_of(row) or {}).get("head")} for row in rows]}
reviews = [review for review in self.reviews.pending() if review["worktree"].startswith("/") and not self.shipped(review["id"])]
seen = {review["id"]: self.merge_previews.get(review_card(review["id"])) or {} for review in reviews}
return {
"rows": [{"task": row["task"], "command": row["command"], "directory": row["directory"], "head": (self.preview_of(row) or {}).get("head")} for row in rows],
"reviews": [{"id": review["id"], "worktree": review["worktree"], "tree": review["tree"], "head": seen[review["id"]].get("moved") or seen[review["id"]].get("head")} for review in reviews],
}
def record_review_preview(self, payload: dict) -> dict:
expect(payload, REVIEW_FAILED if "error" in payload else REVIEW_SHOWN)
review_id = field(payload, "id")
review = self.reviews.get(review_id)
if review is None or review["status"] != "pending":
raise Missing(review_id)
head = object_id(payload, "head", "error" in payload)
key = review_card(review_id)
found = self.merge_previews.get(key)
if found is not None and "diff" in found and found["head"] != head:
self.merge_previews.change(key, {"moved": head})
return {"id": key, "head": head}
record = {"head": head, "taken": time.time()}
if "error" in payload:
record["error"] = bounded(payload, "error", ERROR_LIMIT)
else:
record["diff"] = valid_diff(payload["diff"])
self.merge_previews.remove(key)
self.merge_previews.insert(key, record)
return {"id": key, "head": head}
def record_preview(self, body: bytes) -> dict:
"""Args:
body: from the runner, {task, command, head, base, target, diff}
for a git merge row, or {task, command, head, error} when it
could not preview it; head is empty when HEAD is unreadable.
could not preview it; {id, head, diff} or {id, head, error}
for a review that shipped no diff; head is empty when HEAD is
unreadable.
"""
payload = decode(body)
if "id" in payload:
return self.record_review_preview(payload)
expect(payload, FAILED if "error" in payload else SHOWN)
task = payload["task"]
if not isinstance(task, str) or not task.startswith(OPERATOR) or not signing.TASK.fullmatch(task):
+9 -4
View File
@@ -10,7 +10,7 @@ LABELS = "kvb-check-score/labels.json"
FILE_LIMIT = 64 << 20
VARIATION = "️"
VALUE = r"([0-9]+(?:\.[0-9]+)?(?:\s*%|:[0-9]+(?:\.[0-9]+)?)?|–|-|new)(?![0-9.])"
CHIP_EXTRAS = ("value",)
CHIP_EXTRAS = ("legal", "architecture", "value")
def checked(labels: object) -> dict | None:
@@ -71,7 +71,8 @@ def metric_chips(score: str, labels: dict | None, bare: bool) -> list[dict]:
text, where "fix 2 tests" is no score.
Returns:
In label order, then the CHIP_EXTRAS, per metric whose emoji (with or
In label order, each CHIP_EXTRAS entry right before the metric its
"before" names, else after all, per metric whose emoji (with or
without its variation selector) or label or former label stands
right before a value in score (the label alone only when bare), the
first such value: {"id", "emoji", "label", "value"}; none without
@@ -79,8 +80,12 @@ def metric_chips(score: str, labels: dict | None, bare: bool) -> list[dict]:
"""
found = []
extras = (labels or {}).get("extras")
shown = [(key, extras[key]) for key in CHIP_EXTRAS if isinstance(extras, dict) and checked({"metrics": {key: extras.get(key)}})]
for key, metric in [*(labels or {}).get("metrics", {}).items(), *shown]:
ordered = list((labels or {}).get("metrics", {}).items())
for key in CHIP_EXTRAS:
if isinstance(extras, dict) and checked({"metrics": {key: extras.get(key)}}):
keys = [name for name, _ in ordered]
ordered.insert(keys.index(extras[key]["before"]) if extras[key].get("before") in keys else len(ordered), (key, extras[key]))
for key, metric in ordered:
emoji = re.escape(metric["emoji"].removesuffix(VARIATION)) + f"{VARIATION}?"
names = "|".join(re.escape(name) for name in (metric["label"], *metric.get("former", [])))
alone = rf"|\b(?:{names})\s*:?\s*" if bare else ""
@@ -0,0 +1,40 @@
from __future__ import annotations
import re
from pathlib import Path
from .records import read_json
SKILLS_INDEX = "skills-index.json"
NAME = re.compile(r"[A-Za-z0-9:_.-]{1,100}")
TEXT_CHARS = 300
SOURCE_CHARS = 1000
SKILLS_LIMIT = 2000
def entry(raw: object) -> dict | None:
"""Returns:
{name, description, source} of an index row whose name matches NAME
and whose description and source are strings within their limits;
None for any other row.
"""
if not isinstance(raw, dict):
return None
name, description, source = raw.get("name"), raw.get("description"), raw.get("source")
if not isinstance(name, str) or not NAME.fullmatch(name) or not isinstance(description, str) or not isinstance(source, str) or not source or len(source) > SOURCE_CHARS:
return None
return {"name": name, "description": description[:TEXT_CHARS], "source": source}
def served(file: Path) -> dict:
"""Args:
file: the index client/skills_index.py writes next to the branch tree.
Returns:
{"skills"}: its valid rows, at most SKILLS_LIMIT, sorted by name and
source; none while the file is missing or unreadable.
"""
data = read_json(file)
rows = data.get("skills") if isinstance(data, dict) else None
found = [shown for raw in rows[:SKILLS_LIMIT] if (shown := entry(raw)) is not None] if isinstance(rows, list) else []
return {"skills": sorted(found, key=lambda row: (row["name"], row["source"]))}
+4 -3
View File
@@ -9,6 +9,7 @@ from .crons import cron_event
from .errors import Missing, ToolError
from .events import event, event_filters, wanted
from .fields import instant, single, whole
from .jobs import row_blocked
from .names import Directory
from .receipts import read_of
from .records import iso_epoch, read_jsonl
@@ -81,12 +82,12 @@ class Timeline:
source = directory.key(decision["agent"], decision["created_ts"])
who = {"agent": directory.at(source, decision["created_ts"]) or decision["agent"], "now": directory.now(source), "session": source}
rows.append(event({"id": f"decision:{decision['id']}", "ts": decision["created_ts"], "kind": "decision", **who, "title": decision["question"][:300], "text": text, "waiting": status == "pending", "ref": ref}))
held = self.open_jobs()
reasons = self.blocked_rows(now)
for row in operator_rows(tasks):
first = self.watch.first(row["task"], now)
if first <= end:
ref = {key: row[key] for key in ("task", "directory", "check", "status")}
rows.append(event({"id": f"operator:{row['task']}", "ts": first, "kind": "operator", "title": row["command"], "text": row["why"], "waiting": row["task"] not in held, "ref": ref}))
ref = {**{key: row[key] for key in ("task", "directory", "check", "status")}, "blocked": row_blocked(row, reasons)}
rows.append(event({"id": f"operator:{row['task']}", "ts": first, "kind": "operator", "title": row["command"], "text": row["why"], "waiting": True, "ref": ref}))
rows += [change for change in self.watch.listed() if begin <= change["ts"] <= end]
rows += [cron_event(cron, directory) for cron in self.schedules(claims, now) if cron["created"] <= end and (cron["active"] or cron["created"] >= begin)]
rows += [row for row in self.log.listed() if begin <= row["ts"] <= end]
+3 -3
View File
@@ -58,9 +58,9 @@ ENCODER_CSP = (
)
def badges(inbox: list[dict], claims: list[dict], jobs: list[dict], now: float) -> dict[str, int]:
def badges(cards: int, claims: list[dict], jobs: list[dict], now: float) -> dict[str, int]:
return {
"tasks": sum(1 for item in inbox if not item["until"] and not item["settled"]),
"tasks": cards,
"agents": len({claim["agent"] for claim in claims if claim["beat"] is not None and claim["beat"] >= now - ACTIVE}),
"artifacts": sum(1 for job in jobs if job["status"] in JOB_OPEN),
}
@@ -146,7 +146,7 @@ class View:
"speech": {**self.speech.describe(), "gate": self.speech_gate.state()},
"people": people,
"inbox": inbox,
"badges": badges(inbox, claims, self.jobs.listed(), now),
"badges": badges(self.match_open(inbox), claims, self.jobs.listed(), now),
"pending": self.batches.listed(),
"rules": [{**{key: value for key, value in rule.items() if key != "proof"}, "signed": rule.get("proof") is not None} for rule in self.rules.listed()],
"approvers": self.keys(),
+44 -8
View File
@@ -15,9 +15,9 @@ from .settings import flag, section
VIEW_LIMIT = 64 << 10
CHANGE_LIMIT = 2 * VIEW_LIMIT + (1 << 10)
VIEW = {
"resources": {"hidden": [], "tokens": "interval", "combined": False, "combinedHidden": []},
"resources": {"hidden": [], "tokens": "interval", "panels": ["hardware", "tokens", "accounts"], "combinedHidden": []},
"burn": {"overlays": []},
"home": {"pins": []},
"home": {"pins": [], "zoom": {}},
"kanban": {"hidden": []},
"legend": {"views": {}, "tiles": {}},
"approval": {"mode": "direct"},
@@ -37,8 +37,10 @@ OVERLAYS = ("fix", "break", "tokens", "velocity", "security", "score")
KANBAN_LAYERS = ("line", "jobs")
PINS_LIMIT = 64
SPAN = (1, 12)
ZOOM = (50, 200, 10)
METRIC = "metric"
CHARTS = ("hardware", "tokens", "combined")
PANELS = (*CHARTS, "accounts")
SHOWN_LIMIT = 100
FNV_PRIME = 0x01000193
FNV_SEEDS = (0x811C9DC5, 0x01000193)
@@ -145,6 +147,30 @@ def pins(value: object) -> list[dict]:
return found
def zooms(value: object) -> dict[str, int]:
"""Returns:
home.zoom: pin keys kind:id to a whole percent from 50 to 200 in
steps of 10; anything else raises ToolError.
"""
low, high, step = ZOOM
if not isinstance(value, dict) or not all(isinstance(key, str) and PIN_KEY.fullmatch(key) for key in value):
raise ToolError("home.zoom must map pin keys kind:id to a percent")
if not all(not isinstance(zoom, bool) and isinstance(zoom, int) and low <= zoom <= high and zoom % step == 0 for zoom in value.values()):
raise ToolError(f"home.zoom must hold whole percents from {low} to {high} in steps of {step}")
return dict(value)
def shown_panels(value: object) -> list[str]:
"""Returns:
resources.panels: the distinct Resources panels shown, at least
one; anything else raises ToolError.
"""
panels = members(value, "resources.panels", "panels", PANELS)
if not panels:
raise ToolError("resources.panels must show at least one panel")
return panels
def legend_flags(value: object, name: str, known: Callable[[str], object], what: str) -> dict[str, bool]:
"""Args:
value: a map of legend owners to whether their legend shows.
@@ -168,7 +194,7 @@ def valid_view(raw: object) -> dict:
Returns:
The document with every key of VIEW and nothing else; any other
key, a missing one or a malformed value raises ToolError. The
legend state of a tile whose pin left Home is dropped.
legend state and zoom of a tile whose pin left Home are dropped.
"""
data = section(raw, "view", tuple(VIEW))
resources = section(data["resources"], "resources", tuple(VIEW["resources"]))
@@ -188,11 +214,11 @@ def valid_view(raw: object) -> dict:
"resources": {
"hidden": series_ids(resources["hidden"], "resources.hidden"),
"tokens": resources["tokens"],
"combined": flag(resources["combined"], "resources.combined"),
"panels": shown_panels(resources["panels"]),
"combinedHidden": series_ids(resources["combinedHidden"], "resources.combinedHidden"),
},
"burn": {"overlays": members(burn["overlays"], "burn.overlays", "metrics", OVERLAYS)},
"home": {"pins": pinned},
"home": {"pins": pinned, "zoom": {key: zoom for key, zoom in zooms(home["zoom"]).items() if key in keys}},
"kanban": {"hidden": members(kanban["hidden"], "kanban.hidden", "layers", KANBAN_LAYERS)},
"legend": {
"views": legend_flags(legend["views"], "legend.views", LEGEND_PANELS.__contains__, f"panels of {', '.join(LEGEND_PANELS)}"),
@@ -204,10 +230,20 @@ def valid_view(raw: object) -> dict:
def upgraded(raw: object) -> object:
"""Returns:
A stored document of an older hub with each VIEW section it lacks
at its default; anything else as it is.
A stored document of an older hub with each VIEW section, and each
key of a section, it lacks at its default, and resources.combined,
which resources.panels replaced, turned into the panels it showed;
anything else as it is.
"""
return {**copy.deepcopy(VIEW), **raw} if isinstance(raw, dict) else raw
if not isinstance(raw, dict):
return raw
resources = raw.get("resources")
if isinstance(resources, dict) and "combined" in resources and "panels" not in resources:
combined = resources["combined"] is True
kept = {key: value for key, value in resources.items() if key != "combined"}
raw = {**raw, "resources": {**kept, "panels": ["combined", "accounts"] if combined else list(VIEW["resources"]["panels"])}}
merged = {**copy.deepcopy(VIEW), **raw}
return {name: {**copy.deepcopy(VIEW[name]), **value} if name in VIEW and isinstance(value, dict) else value for name, value in merged.items()}
def slot(view: dict, path: object) -> tuple[dict, str]:
@@ -1,5 +1,5 @@
[Unit]
Description=Agent Orchestrator tree: pkgmgr branch tree and the pkgmgr branch cleanup --local dry run into the files the orchestrator reads, while its page polls
Description=Agent Orchestrator tree: pkgmgr branch tree, the pkgmgr branch cleanup --local dry run and the skills index into the files the orchestrator reads, while its page polls
[Service]
Type=oneshot
@@ -7,6 +7,7 @@ Environment=PATH=/usr/bin:/bin
ExecCondition=/bin/sh -c 'test -n "$(find %h/.local/state/kvb-orchestrator/tree-heartbeat -mmin -5 2>/dev/null)"'
ExecStart=%h/.local/share/kvb-orchestrator/pkgmgr/bin/pkgmgr branch tree --format json --output %h/.local/state/pkgmgr/tree/branch-tree.json
ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/local_plan.py --tree %h/.local/state/pkgmgr/tree/branch-tree.json --pkgmgr %h/.local/share/kvb-orchestrator/pkgmgr/bin/pkgmgr --budget 240
ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/skills_index.py --home %h --tree %h/.local/state/pkgmgr/tree/branch-tree.json --output %h/.local/state/pkgmgr/tree/skills-index.json
Nice=10
IOSchedulingClass=idle
CPUQuota=50%
+40
View File
@@ -0,0 +1,40 @@
const Answers = (() => {
const plain = (option) => String(option.label).trim().toLowerCase();
/**
* @param item - an inbox item or Match card with kind, and for a choice its options and multi.
* @returns {Object|null} {yes, no}: the labels of a single choice whose only options are Yes and No, else null.
*/
function pair(item) {
const options = item.options || [];
if (item.multi || options.length !== 2) {
return null;
}
const yes = options.find((option) => plain(option) === "yes");
const no = options.find((option) => plain(option) === "no");
return yes && no ? {yes: yes.label, no: no.label} : null;
}
/**
* @param item - as pair() takes it.
* @returns {boolean} whether Accept and Reject answer it without a numbered form: a permission ask or a Yes/No choice.
*/
const boolean = (item) => item.kind === "ask" || pair(item) !== null;
/**
* @param no - the No label of the choice.
* @param text - the typed comment, maybe empty or multi-line.
* @param limit - the longest answer the hub takes.
* @returns {string} No without a comment, else "No: comment" on one line as the Other answer, cut to limit; never an option label.
*/
function declined(no, text, limit) {
const line = text.replace(/\s+/g, " ").trim();
return line ? `${no}: ${line}`.slice(0, limit).trim() : no;
}
return {pair, boolean, declined};
})();
if (typeof module === "object" && module.exports) {
module.exports = Answers;
}
+1 -8
View File
@@ -1,7 +1,6 @@
const Diffs = (() => {
"use strict";
const COLLAPSE = 400;
const QUOTE_LIMIT = 2000;
const HUNK = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;
const KINDS = {"+": "add", "-": "del", " ": "ctx"};
@@ -45,15 +44,9 @@ const Diffs = (() => {
return [from, from + quote.split("\n").length - 1];
}
function quoted(text) {
const clean = String(text).trim();
return clean.length > QUOTE_LIMIT ? `${clean.slice(0, QUOTE_LIMIT)}…` : clean;
}
const feedback = (ref, path, from, to, quote, words) => `Feedback on ${ref} ${path}:${from}-${to}: "${quoted(quote)}" ${String(words).trim()}`;
const feedbackOf = (messages, ref) => messages.filter((message) => String(message.text).startsWith(`Feedback on ${ref} `));
return {COLLAPSE, QUOTE_LIMIT, rows, collapsed, span, lineSpan, quoted, feedback, feedbackOf};
return {COLLAPSE, rows, collapsed, span, lineSpan, feedbackOf};
})();
if (typeof module === "object" && module.exports) {
module.exports = Diffs;
+32 -9
View File
@@ -90,11 +90,11 @@ h1 { margin: 0; font-size: var(--fs-lg); font-weight: 680; letter-spacing: -.01e
.updated.offline::before { background: var(--bad); box-shadow: 0 0 0 3px var(--bad-soft); }
body.leitstand { --fs-xs: 13px; --fs-sm: 14px; --fs-md: 16px; --fs-lg: 18px; --fs-xl: 21px; --fs-2xl: 26px; --fs-3xl: 44px; }
.shell { padding: var(--sp-4) var(--sp-4) var(--sp-6); }
main { min-width: 0; min-height: calc(100vh - var(--head) - var(--sp-6) - var(--sp-4)); padding: var(--sp-5) var(--sp-5) 80px; background: var(--glass); border: 1px solid color-mix(in srgb, var(--line) 70%, transparent); border-radius: var(--radius-lg); box-shadow: var(--shadow); }
main { --main-pad: var(--sp-5); --main-top: var(--main-pad); min-width: 0; min-height: calc(100vh - var(--head) - var(--sp-6) - var(--sp-4)); padding: var(--main-top) var(--main-pad) 80px; background: var(--glass); border: 1px solid color-mix(in srgb, var(--line) 70%, transparent); border-radius: var(--radius-lg); box-shadow: var(--shadow); }
@media (max-width: 640px) {
.top, .navbar, .banner { gap: var(--sp-2); padding: var(--sp-2) var(--sp-3); }
.shell { padding: var(--sp-2) var(--sp-2) var(--sp-6); }
main { padding: var(--sp-3) var(--sp-3) 88px; border-radius: var(--radius); }
main { --main-pad: var(--sp-3); padding: var(--main-top) var(--main-pad) 88px; border-radius: var(--radius); }
.menu-box { position: fixed; top: auto; right: var(--sp-2); left: var(--sp-2); width: auto; }
.replay { flex-basis: 100%; min-width: 0; }
.sheet { padding: 0; }
@@ -217,9 +217,12 @@ table.diff tr.more td { padding: 8px 16px; color: var(--muted); font-style: ital
.route .headline { font-weight: 600; overflow-wrap: anywhere; }
.filters { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin-bottom: 10px; }
.filters select, .filters input, .field { padding: 6px 10px; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--panel); }
.filters input[type="search"] { flex: 1; min-width: 200px; }
.filters input[type="search"], .filters > .mic-line { flex: 1; min-width: 200px; }
.graph { display: grid; gap: 14px; }
.controls { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 18px; padding: 10px 14px; }
.box-head { display: flex; flex: none; flex-wrap: wrap; align-items: center; gap: 6px 10px; margin: calc(-1 * var(--main-top)) calc(-1 * var(--main-pad)) 0; padding: 4px 6px 4px 8px; border-bottom: 1px solid var(--line); font-size: var(--fs-sm); }
.box-head > .box-title { display: inline-flex; align-items: center; gap: 6px; margin: 0; font-size: var(--fs-sm); font-weight: 650; }
.box-head .field { padding-block: 3px; }
.box-head > .box-slot { display: contents; }
.segmented { display: inline-flex; padding: 3px; gap: 2px; border-radius: 10px; background: var(--sunken); border: 1px solid var(--line); }
.segmented button { padding: 4px 11px; border: 0; border-radius: 8px; background: transparent; color: var(--muted); font-size: var(--fs-sm); font-weight: 580; cursor: pointer; }
.segmented button[aria-selected="true"], .segmented button[aria-pressed="true"] { background: var(--panel); color: var(--text); box-shadow: var(--shadow); }
@@ -341,15 +344,27 @@ textarea { width: 100%; min-height: 84px; padding: 8px 10px; border: 1px solid v
.palette-box input { width: 100%; padding: 14px 16px; border: 0; background: transparent; font-size: var(--fs-lg); outline: none; }
.palette-row { display: flex; align-items: center; gap: 6px; padding-right: 10px; border-bottom: 1px solid var(--line); }
.palette-row input { flex: 1; min-width: 0; }
.mic { flex: none; }
.mic-frame { min-width: 0; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--panel); }
.mic-frame:focus-within { outline: 2px solid var(--accent); outline-offset: 1px; }
.mic-frame > :is(input, textarea, .field) { border: 0; border-radius: 0; background: transparent; box-shadow: none; outline: none; }
.mic-line { display: flex; align-items: stretch; width: 100%; }
:is(.filters, .box-head, .palette-row, .row, .tool-add, .actions, .chips) > .mic-line { flex: 1 1 12rem; width: auto; }
.mic-line > input { flex: 1; width: auto; min-width: 0; }
.mic-area { display: flex; flex-direction: column; width: 100%; }
.mic-area > textarea { display: block; width: 100%; min-width: 0; }
.mic-foot { display: flex; align-items: center; gap: 6px; min-height: 32px; padding: 2px 3px 2px 8px; border-top: 1px solid var(--line); }
.mic { display: inline-grid; flex: none; place-items: center; min-width: 34px; padding: 0 8px; border: 0; background: transparent; color: var(--muted); cursor: pointer; }
.mic:hover:not(:disabled) { background: var(--hover); color: var(--text); }
.mic:disabled { cursor: not-allowed; opacity: .55; }
.mic-line > .mic { border-left: 1px solid var(--line); border-radius: 0 9px 9px 0; }
.mic-foot > .mic { min-height: 28px; border-radius: 8px; }
.palette-row > .mic-line { border: 0; border-radius: 0; }
.mic[aria-pressed="true"] { background: var(--bad-soft); color: var(--bad); animation: mic-pulse 1.2s ease-in-out infinite; }
.mic-auto { margin-left: 4px; vertical-align: middle; }
textarea + .mic-auto { display: flex; margin: 4px 0 0 auto; }
.mic-live { position: fixed; left: 50%; bottom: calc(18px + env(safe-area-inset-bottom, 0px)); z-index: 60; display: flex; align-items: center; gap: 8px; max-width: calc(100vw - 32px); padding: 8px 14px; transform: translateX(-50%); border-radius: 999px; background: var(--bad); color: #fff; font-weight: 650; box-shadow: var(--shadow-lift); }
.mic-live[hidden] { display: none; }
.mic-live::before { content: ""; flex: none; width: 10px; height: 10px; border-radius: 50%; background: #fff; animation: mic-pulse 1s ease-in-out infinite; }
@keyframes mic-pulse { 50% { opacity: .45; } }
@media (max-width: 640px) { .btn.small.mic { min-width: 44px; min-height: 44px; } }
@media (max-width: 640px) { .mic { min-width: 44px; } .mic-foot > .mic { min-height: 44px; } }
@media (prefers-reduced-motion: reduce) { .mic[aria-pressed="true"], .mic-live::before { animation: none; } }
.palette-list { max-height: 55vh; margin: 0; padding: 6px; overflow: auto; list-style: none; }
.palette-list li { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px; cursor: pointer; }
@@ -407,7 +422,8 @@ textarea + .mic-auto { display: flex; margin: 4px 0 0 auto; }
.wt { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; padding: 7px 10px; border-radius: 8px; background: var(--sunken); font-size: var(--fs-sm); }
.wt code { overflow-wrap: anywhere; }
.rule-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 10px; }
.rule-form { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px; align-items: end; }
.rule-form { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px; align-items: start; }
.rule-form > label.check, .rule-form > button { align-self: end; }
.rule-form label, .sound-row label { display: grid; gap: 4px; color: var(--muted); font-size: var(--fs-sm); }
.sound-row { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(120px, 220px) auto; align-items: center; gap: var(--sp-3); padding: var(--sp-2) 0; border-bottom: 1px solid var(--line); }
.settings { display: grid; gap: var(--sp-5); }
@@ -550,6 +566,10 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
{% include "glossary.js" %}
{% include "settings-files.js" %}
{% include "answers.js" %}
{% include "ancestry.js" %}
{% include "popup.js" %}
@@ -676,11 +696,14 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
{% include "page-mic.js" %}
{% include "page-slash.js" %}
{% include "page-bubbles.js" %}
{% include "page-alerts.js" %}
{% include "page-resources.js" %}
{% include "page-accounts.js" %}
{% include "page-rates.js" %}
+139
View File
@@ -0,0 +1,139 @@
const ACCOUNT_DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const ACCOUNT_COLUMNS = ["Provider", "Email", "Renewal", "Next reset", "Resubscribe", "Autorenew", "Since reset", "Today", "Total", "Remaining", ""];
const accountsView = {data: null, busy: false, body: null};
const momentText = (moment) => `${ACCOUNT_DAYS[moment.day]} ${moment.time}`;
function accountsPanel() {
const body = h("div", {class: "acc-body"});
accountsView.body = body;
const add = iconBtn("bi-plus-lg", "Add account", "btn small soft", () => accountSheet(null), "Add account: provider, email, renewal and weekly reset; kept on this host only");
const panel = h("section", {class: "card res-panel res-accounts", "data-panel": "resources-accounts", "aria-label": "Accounts"},
h("div", {class: "res-head", "data-star-slot": ""}, h("span", {class: "res-title", title: "Accounts", "aria-label": "Accounts"}, icon("bi-person-badge")), h("span", {class: "acc-title"}, "Accounts"), h("span", {class: "spacer"}), add), body);
return {panel, body};
}
async function fetchAccounts() {
if (accountsView.busy) {
return;
}
accountsView.busy = true;
try {
const response = await fetch("/api/accounts", {cache: "no-store"});
if (response.ok) {
accountsView.data = await response.json();
}
} catch {
ui.offline = true;
}
accountsView.busy = false;
drawAccounts();
}
/**
* @param data - /api/accounts: {accounts, active, usage}.
* @param now - epoch milliseconds.
* @returns the table rows: each account with its next reset and usage, sorted by the next reset, then one
* unassigned row for the tokens of no stored account, when there are any.
*/
function accountRows(data, now) {
const empty = {total: 0, hours: []};
const rows = data.accounts.map((account) => ({account, next: Resources.nextMoment(account.reset, now), used: Resources.accountUsage(data.usage[account.email] || empty, account.reset, now)}));
rows.sort((a, b) => a.next - b.next || a.account.email.localeCompare(b.account.email));
const known = new Set(data.accounts.map((account) => account.email));
const rest = Object.entries(data.usage).filter(([email]) => !known.has(email)).map(([, entry]) => entry);
const unassigned = {total: rest.reduce((sum, entry) => sum + entry.total, 0), hours: rest.flatMap((entry) => entry.hours)};
return unassigned.total ? [...rows, {account: null, next: null, used: Resources.accountUsage(unassigned, null, now)}] : rows;
}
function accountRow(row, active) {
const count = (value) => (value === null ? "–" : Resources.compact(value));
if (row.account === null) {
return h("tr", {class: "acc-unassigned", "data-account": ""}, h("td", {colspan: 6}, "Unassigned: sessions the SessionStart hook mapped to no stored account"),
h("td", {}, "–"), h("td", {}, count(row.used.today)), h("td", {}, count(row.used.total)), h("td", {}, "–"), h("td", {}));
}
const {account} = row;
const remaining = account.limit === null ? null : Math.max(0, account.limit - row.used.since);
const isActive = account.email === active;
return h("tr", {"data-account": account.id, ...(isActive ? {"data-active": ""} : {})},
h("td", {}, account.provider), h("td", {}, account.email, isActive ? h("span", {class: "pill", "data-tone": "ok", title: "The account Claude Code logged in with at the last session start"}, "active") : null),
h("td", {}, momentText(account.renewal)), h("td", {title: momentText(account.reset)}, absolute.format(new Date(row.next))), h("td", {}, account.resubscribe || "–"),
h("td", {}, account.autorenew ? "yes" : "no"), h("td", {}, count(row.used.since)), h("td", {}, count(row.used.today)), h("td", {}, count(row.used.total)),
h("td", {title: account.limit === null ? "No weekly limit set" : `Limit ${account.limit} minus the tokens since the last reset`}, count(remaining)),
h("td", {}, iconBtn("bi-pencil", `Edit ${account.email}`, "btn small ghost", () => accountSheet(account), "Edit or remove this account")));
}
function accountsContent(data) {
if (data === null) {
return h("p", {class: "muted"}, "…");
}
const rows = accountRows(data, Date.now());
if (!rows.length) {
return h("p", {class: "muted"}, "No account yet. Add one: it stays on this host, in the hub's state only.");
}
return h("div", {class: "acc-scroll"}, h("table", {class: "acc-table"},
h("thead", {}, h("tr", {}, ACCOUNT_COLUMNS.map((name) => h("th", {scope: "col"}, name)))),
h("tbody", {}, rows.map((row) => accountRow(row, data.active)))));
}
function drawAccounts() {
const body = accountsView.body;
if (body && body.isConnected) {
body.replaceChildren(accountsContent(accountsView.data));
}
}
function homeAccounts() {
homeFetch("accounts", fetchAccounts);
return h("div", {class: "acc-body"}, accountsContent(accountsView.data));
}
function momentFields(label, moment) {
const day = h("select", {class: "field", "aria-label": `${label} weekday`}, ACCOUNT_DAYS.map((name, index) => h("option", {value: String(index), ...(moment && moment.day === index ? {selected: true} : {})}, name)));
const time = h("input", {type: "time", class: "field", "aria-label": `${label} time`, value: moment ? moment.time : "00:00"});
return {day, time, row: h("div", {class: "acc-field"}, h("span", {}, label), h("div", {class: "acc-pair"}, day, time))};
}
function accountSheet(account) {
const text = (label, type, value, extra) => h("input", {type, class: "field", "aria-label": label, value, ...extra});
const provider = text("Provider", "text", account ? account.provider : "", {maxlength: 40});
const email = text("Email", "email", account ? account.email : "", {});
const renewal = momentFields("Renewal", account && account.renewal);
const reset = momentFields("Weekly reset", account && account.reset);
const resubscribe = text("Resubscribe", "date", account ? account.resubscribe : "", {});
const autorenew = h("input", {type: "checkbox", "aria-label": "Autorenew", ...(account && account.autorenew ? {checked: true} : {})});
const limit = text("Weekly token limit", "number", account && account.limit !== null ? String(account.limit) : "", {min: 0, step: 1});
const note = text("Note", "text", account ? account.note : "", {maxlength: 200});
const labelled = (label, input) => h("label", {class: "acc-field"}, h("span", {}, label), input);
const save = h("button", {type: "button", class: "btn primary"}, icon("bi-check-lg"), "Save");
save.addEventListener("click", async () => {
const fields = {
provider: provider.value.trim(), email: email.value.trim(), renewal: {day: Number(renewal.day.value), time: renewal.time.value}, reset: {day: Number(reset.day.value), time: reset.time.value},
resubscribe: resubscribe.value, autorenew: autorenew.checked, limit: limit.value === "" ? null : Number(limit.value), note: note.value.trim(),
};
const result = await sendJson("/api/accounts", {id: account ? account.id : "", account: fields});
if (!result.ok) {
toast("Account: not saved", fail(result), false);
return;
}
closeSheet();
fetchAccounts();
});
const remove = account ? h("button", {type: "button", class: "btn danger"}, icon("bi-trash"), "Remove") : null;
if (remove) {
remove.addEventListener("click", async () => {
const result = await sendJson(`/api/accounts/${account.id}/delete`, {});
if (!result.ok) {
toast("Account: not removed", fail(result), false);
return;
}
closeSheet();
fetchAccounts();
});
}
openSheet(account ? `Account: ${account.email}` : "Add account", [
h("p", {class: "muted"}, "Kept on this host in the hub's state, mode 0600; never in git, the view store or the radio."),
h("div", {class: "acc-form"}, labelled("Provider", provider), labelled("Email", email), renewal.row, reset.row, labelled("Resubscribe", resubscribe),
labelled("Autorenew", autorenew), labelled("Weekly token limit", limit), labelled("Note", note)),
h("div", {class: "actions"}, remove, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), save)], false);
provider.focus();
}
+3 -3
View File
@@ -88,13 +88,13 @@
function openAgent(who, anchor, closed) {
const key = agentKey(who);
const name = nameOf(key);
const text = h("textarea", {"aria-label": `Message to ${name}`, placeholder: `Message to ${name} …`});
const text = h("textarea", {"aria-label": `Message to ${name}`, placeholder: `Message to ${name} …`, "data-skills": ""});
const file = h("input", {type: "file", class: "field", "aria-label": "Attach file"});
const button = h("button", {type: "submit", class: "btn primary icon-only", ...named("Send")}, icon("bi-send"));
const classes = choice("to-one", TO_ONE, "post");
const form = h("form", {class: "popup-form"}, text, file, classes,
const form = h("form", {class: "popup-form"}, micFrame(text, []), file, classes,
h("p", {class: "muted"}, "Post arrives at the end of the turn, Call at once with a read receipt; your passkey signs, verifiable with operator_message."),
h("div", {class: "actions"}, h("span", {class: "spacer"}), micButton(text, false), button));
h("div", {class: "actions"}, h("span", {class: "spacer"}), button));
form.addEventListener("submit", async (event) => {
event.preventDefault();
if (!text.value.trim()) {
+2 -2
View File
@@ -277,8 +277,8 @@
drawArtifacts();
fetchTree();
}, 0);
const controls = h("div", {class: "card controls"}, viewSwitch("artifacts"), view === "3d" ? layoutTools("artifacts") : view === "tree" ? null : picker,
h("div", {class: "toolbar", role: "toolbar", "aria-label": "Artifacts"}, search, reload, removeAll, apply), count);
const controls = boxHead("Artifacts", "", viewSwitch("artifacts"), view === "3d" ? layoutTools("artifacts") : view === "tree" ? null : picker,
h("div", {class: "toolbar"}, search, reload, removeAll, apply), count);
const body = view === "tree" ? h("div", {class: "tree-panel", "data-panel": "artifacts/tree"}, list) : h("div", {class: "card stage-card", "data-panel": `artifacts/${view}`}, stageBox, legendBox);
return h("div", {class: "graph"}, controls, body);
}
+7 -3
View File
@@ -17,11 +17,15 @@
.sort(([one, a], [two, b]) => a.localeCompare(b) || one.localeCompare(two));
async function confirmAct(action, agents) {
const [, label, question] = actionOf(action);
const [, , question] = actionOf(action);
const names = new Map(nightAgents());
if (!window.confirm(agents.length ? question.replace("all agents", agents.map((sid) => names.get(sid) || sid).join(", ")) : question)) {
return;
if (window.confirm(agents.length ? question.replace("all agents", agents.map((sid) => names.get(sid) || sid).join(", ")) : question)) {
await signedAct(action, agents);
}
}
async function signedAct(action, agents) {
const [, label] = actionOf(action);
const chosen = agents.length ? {agents} : {};
const signed = await signedProof("/api/board/sign", {action, ...chosen}, label);
if (signed) {
+1
View File
@@ -41,6 +41,7 @@
window.addEventListener("resize", placeStations);
skyPanel();
micWatch();
slashWatch();
radioSpot();
radio.element = radioElement();
drawSky();
+1 -1
View File
@@ -4,7 +4,7 @@
async function requestChoices(cls) {
const direct = TO_ONE.some(([id]) => id === cls);
const to = direct ? [...choiceAsk.to].sort((a, b) => a.localeCompare(b)) : ["*"];
if ((direct && !to.length) || (cls === "mayday" && !confirmMayday())) {
if ((direct && !to.length) || (cls === "mayday" && !window.confirm(MAYDAY_ASK))) {
return;
}
const label = `Choice request (${CLASSES[cls]}) to ${direct ? to.join(", ") : "all"}`;
+77 -24
View File
@@ -1,4 +1,4 @@
const CHANNELS = [...TO_ONE, ...TO_ALL];
const CHANNELS = [...TO_ONE, ...TO_ALL].filter(([id]) => id !== "mayday");
const CHANNEL_HINTS = {
post: "Post arrives at the end of the turn.",
call: "Call arrives at once, with a read receipt.",
@@ -6,14 +6,52 @@
broadcast: "Broadcast reaches all at once.",
"pan-pan": "PAN-PAN: urgent, to all, at once.",
security: "Sécurité: safety notice to all stations, now.",
mayday: "MAYDAY: all agents pause writing steps until you cancel it.",
};
const MAYDAY_ASK = "Send a mayday to all? All agents pause writing steps until you cancel it.";
const VOICE_POLL = 700;
const HOLD_MS = 350;
const composer = {live: null};
function confirmMayday() {
return window.confirm("Send a mayday to all? All agents pause writing steps until you cancel it.");
/**
* @param {boolean} silence whether a mayday holds the radio silent.
* @returns {Object} {pressed, label, hint}: the MAYDAY toggle's face: Cancel mayday while one is active.
*/
function maydayFace(silence) {
const [, cancel, , cancelHint] = actionOf("clear-mayday");
return silence ? {pressed: true, label: cancel, hint: cancelHint} : {pressed: false, label: "MAYDAY", hint: "MAYDAY: send the message as mayday to all; all agents pause writing steps until you cancel it"};
}
function drawMayday(button) {
const shown = maydayFace(Boolean(state.silence));
button.setAttribute("aria-pressed", String(shown.pressed));
button.title = shown.hint;
button.replaceChildren(icon("bi-life-preserver"), shown.label);
}
/**
* @param {Element} form the composer the question shows in, above its footer, its last child.
* @param {string} question what the operator confirms.
* @param {string} yes the confirming button's label.
* @returns {Promise<boolean>} true on yes, false on Cancel or Escape; nothing leaves the page before.
*/
function inlineConfirm(form, question, yes) {
form.querySelectorAll(".mayday-confirm").forEach((node) => node.remove());
return new Promise((resolve) => {
const done = (answer) => {
box.remove();
resolve(answer);
};
const accept = h("button", {type: "button", class: "btn small danger", on: {click: () => done(true)}}, yes);
const box = h("div", {class: "mayday-confirm", role: "alertdialog", "aria-label": question}, h("p", {}, question), h("div", {class: "actions"}, h("button", {type: "button", class: "btn small ghost", on: {click: () => done(false)}}, "Cancel"), accept));
box.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
event.stopPropagation();
done(false);
}
});
form.lastElementChild.before(box);
accept.focus();
});
}
async function radioSend(message) {
@@ -169,12 +207,11 @@
}
function composerForm() {
const channel = h("select", {class: "field"}, CHANNELS.map(([id, label]) => h("option", {value: id}, label)));
const channel = h("select", {class: "field"}, CHANNELS.map(([id, label]) => h("option", {value: id, title: CHANNEL_HINTS[id]}, label)));
const recipient = h("select", {class: "field"});
const toField = h("label", {}, "To", recipient);
const text = h("textarea", {"aria-label": "Message", placeholder: "Message to the agents …", maxlength: 20000});
const text = h("textarea", {"aria-label": "Message", placeholder: "Message to the agents …", maxlength: 20000, "data-skills": ""});
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, 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");
@@ -199,38 +236,54 @@
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 mayday = h("button", {type: "button", class: "btn small danger mayday-toggle", "aria-pressed": "false"});
drawMayday(mayday);
const sync = () => {
const direct = TO_ONE.some(([id]) => id === channel.value);
toField.hidden = !direct;
hint.textContent = `${CHANNEL_HINTS[channel.value]} Your passkey signs every message.`;
channel.title = hint.textContent;
toField.hidden = !TO_ONE.some(([id]) => id === channel.value);
channel.title = CHANNEL_HINTS[channel.value];
};
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, 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);
const form = h("form", {class: "composer"}, h("div", {class: "composer-grid"}, h("label", {}, "Channel", channel), toField), micFrame(text, [record]), replay,
h("div", {class: "actions"}, status, h("div", {class: "ptt-split", role: "group", "aria-label": "Send"}, submit, testMenu(text, channel)), mayday));
const empty = () => {
if (!text.value.trim()) {
toast("Nothing to send", ["Write a text or record one; the transcript lands in the field for checking."], false);
return;
}
if ((direct && !recipient.value) || (channel.value === "mayday" && !confirmMayday())) {
return;
}
return !text.value.trim();
};
const send = async (to, cls) => {
submit.disabled = true;
if (await radioSend({to: direct ? recipient.value : "*", text: text.value, upload: "", cls: channel.value, voice: attach.checked ? parts.voice : ""})) {
mayday.disabled = true;
if (await radioSend({to, text: text.value, upload: "", cls, voice: attach.checked ? parts.voice : ""})) {
text.value = "";
status.textContent = "";
attachVoice(parts, "");
}
submit.disabled = false;
mayday.disabled = false;
};
mayday.addEventListener("click", async () => {
if (state.silence) {
if (await inlineConfirm(form, actionOf("clear-mayday")[2], maydayFace(true).label)) {
await signedAct("clear-mayday", []);
}
return;
}
if (!empty() && (await inlineConfirm(form, MAYDAY_ASK, "Send mayday"))) {
await send("*", "mayday");
}
});
form.addEventListener("submit", async (event) => {
event.preventDefault();
const direct = TO_ONE.some(([id]) => id === channel.value);
if (empty() || (direct && !recipient.value)) {
return;
}
await send(direct ? recipient.value : "*", channel.value);
});
attachVoice(parts, "");
return {form, recipient, text, channel, clear};
return {form, recipient, text, channel, mayday};
}
function holdToTalk(parts) {
+1 -1
View File
@@ -75,7 +75,7 @@
direct: [[740, 0, 0.2]],
radio: [[520, 0, 0.07]],
};
const KEYS = [["Ctrl+K", "Commands, views, agents and AI command"], ["Right-click", "Context menu: the element's commands, then the tab's, then the general ones"], ["Shift+right-click", "The browser's own context menu"], ["Menu key · Shift+F10", "Context menu of the focused element: ↑ / ↓ move, Enter runs, Esc closes"], ["1 · 2 · 3 · 4", "Stream · Agents · Artifacts · Tasks"], ["j / k", "Waits on Operator: next / previous entry"], ["x", "Waits on Operator: select entry"], ["a", "Waits on Operator: grant entry (3 s to undo)"], ["Enter", "Waits on Operator: open entry"], ["f", "Feedback on the selected lines of a diff or a command"], ["→ · ← · ↑", "Match: accept · reject with feedback · later"],["/", "Search the stream"], ["h", "Look at the sky: drag turns the view, wheel or two fingers zoom, Esc ends"], ["Arrows · + / − · 0", "Sky (focused): turn · zoom · reset"], ["Drag · wheel", "3D: turn, right drag pans, wheel zooms"],["🎙 hold", "Voice input into the agent field or the command line, never sent automatically"], ["?", "This help"], ["Esc", "Close"]];
const KEYS = [["Ctrl+K", "Commands, views, agents and AI command"], ["Right-click", "Context menu: the element's commands, then the tab's, then the general ones"], ["Shift+right-click", "The browser's own context menu"], ["Menu key · Shift+F10", "Context menu of the focused element: ↑ / ↓ move, Enter runs, Esc closes"], ["1 · 2 · 3 · 4", "Stream · Agents · Artifacts · Tasks"], ["j / k", "Waits on Operator: next / previous entry"], ["x", "Waits on Operator: select entry"], ["a", "Waits on Operator: grant entry (3 s to undo)"], ["Enter", "Waits on Operator: open entry"], ["f", "Comment on the selected lines of a diff or a command: it goes with Deny as a call, or after Grant as a post"], ["→ · ← · ↑", "Match: accept · reject with feedback · later"],["/", "Search the stream"], ["h", "Look at the sky: drag turns the view, wheel or two fingers zoom, Esc ends"], ["Arrows · + / − · 0", "Sky (focused): turn · zoom · reset"], ["Drag · wheel", "3D: turn, right drag pans, wheel zooms"], ["+ / − · 0 · Ctrl+wheel", "Home tile (focused): zoom its content in · out · reset"],["🎙 hold", "Voice input into the agent field or the command line, never sent automatically"], ["?", "This help"], ["Esc", "Close"]];
const calm = window.matchMedia("(prefers-reduced-motion: reduce)");
const relative = new Intl.RelativeTimeFormat("en", {numeric: "auto"});
const absolute = new Intl.DateTimeFormat("en-GB", {dateStyle: "medium", timeStyle: "short"});
+12 -1
View File
@@ -37,7 +37,7 @@
}
function ctxPathItems(node, path) {
return [...feedbackItems(), ...(path === "-" ? [] : [ctxCopyItem("Copy path", path)])];
return [...feedbackItems(node), ...(path === "-" ? [] : [ctxCopyItem("Copy path", path)])];
}
function ctxEntryItems(node, ref) {
@@ -69,6 +69,15 @@
return [...opens, {label: pinned ? "Unpin from Home" : "Pin to Home", hint: entry.title, run: () => homePress(target.kind, target.id, entry.title, target.view)}];
}
function ctxTileItems(node, key) {
const hint = `${node.querySelector(".home-title").textContent}: zoom its content`;
return [
{label: "Zoom in", hint: `${hint} (+)`, run: () => homeZoomBy(key, 1)},
{label: "Zoom out", hint: `${hint} (-)`, run: () => homeZoomBy(key, -1)},
{label: `Reset zoom (${homeZoom(key)} %)`, hint: `${hint} (0)`, run: () => homeZoomBy(key, 0)},
];
}
const CTX_KINDS = [
{kind: "task", id: ctxAttr("data-task"), title: (id) => `Task ${id}`, items: ctxTaskItems},
{kind: "agent", id: ctxAgentOf, title: (key) => nameOf(key), items: ctxAgentItems},
@@ -78,6 +87,7 @@
{kind: "rule", id: ctxAttr("data-rule", "data-entry"), title: (id) => `Rule ${id}`, items: (node, id) => [ctxCopyItem("Copy rule", id)]},
{kind: "pick", id: ctxAttr("data-pick"), title: ctxPickTitle, items: ctxPickItems},
{kind: "pin", id: ctxPinOf, title: (target) => ctxPinEntry(target).title, items: ctxPinItems},
{kind: "tile", id: (node) => (node.matches(".home-tile[data-pin]") ? node.dataset.pin : null), title: (key) => `Tile ${key}`, items: ctxTileItems},
];
/**
@@ -175,6 +185,7 @@
function ctxOpen(target, at) {
closeMenus(null);
ctxMenu.back = document.activeElement;
diffView.hit = target;
ctxShow(ctxSections(target), at);
}
+39 -4
View File
@@ -9,8 +9,12 @@
* @param {string} reason the operator's reason, possibly empty.
* @param {string} to the agent a direct channel tells; a class to all keeps the item's requester.
*/
function denyNow(item, channel, reason, to) {
return submit([{...entryOf(item, "reject", ""), channel, reason, to: DIRECT_DENY.has(channel) ? to : item.to}], `Denial (${CLASSES[channel]}): ${short(item.title)}`);
async function denyNow(item, channel, reason, to) {
const denied = await submit([{...entryOf(item, "reject", ""), channel, reason, to: DIRECT_DENY.has(channel) ? to : item.to}], `Denial (${CLASSES[channel]}): ${short(item.title)}`);
if (denied && lineNotes(keyOf(item))) {
setLineMarks(keyOf(item), []);
}
return denied;
}
/**
@@ -57,7 +61,8 @@
h("span", {}, h("strong", {}, CLASSES[id]), small));
});
recipient.addEventListener("change", paintDeny);
const reason = h("textarea", {class: "field", maxlength: DENY_REASON, rows: 3, placeholder: "e.g. make the gate green first"});
const reason = h("textarea", {class: "field", maxlength: DENY_REASON, rows: 3, placeholder: "e.g. make the gate green first", "data-skills": item.repo || ""});
reason.value = lineNotes(keyOf(item)).slice(0, DENY_REASON);
confirm.addEventListener("click", () => {
const channel = picked().value;
closeSheet();
@@ -78,7 +83,7 @@
}
function denySplit(item) {
const main = iconBtn("bi-x-lg", "Deny", "btn small danger", () => denyNow(item, "post", "", item.to), item.to ? `Deny: by post to ${revealed(item.to)}, 3 s to undo` : "Deny: the card names no agent; pick one under Deny via …");
const main = iconBtn("bi-x-lg", "Deny", "btn small danger", () => (lineNotes(keyOf(item)) ? denySheet(item) : denyNow(item, "post", "", item.to)), item.to ? `Deny: by post to ${revealed(item.to)}, 3 s to undo; with line comments it opens Deny via … with them as the reason` : "Deny: the card names no agent; pick one under Deny via …");
main.disabled = !item.to;
const more = h("button", {type: "button", class: "btn small danger icon-only", "aria-haspopup": "dialog", ...named("Deny via …", "Deny via another channel or with a reason")}, caret());
more.addEventListener("click", (event) => {
@@ -87,3 +92,33 @@
});
return h("div", {class: "deny-split", role: "group", "aria-label": "Deny"}, main, more);
}
/**
* @param {Object} item a Yes/No choice or decision row.
* @param {string} no its No label.
* @param {Function} answer sends the label it is given.
*/
function declineSheet(item, no, answer) {
const words = h("textarea", {class: "field", rows: 4, maxlength: OTHER_LIMIT, "aria-label": "Comment", "data-skills": ""});
const confirm = h("button", {type: "button", class: "btn danger"}, icon("bi-x-lg"), revealed(no));
confirm.addEventListener("click", () => {
closeSheet();
answer(Answers.declined(no, words.value, OTHER_LIMIT));
});
openSheet(`${revealed(no)}: ${short(item.title)}`, [h("p", {class: "muted"}, `Optional: what to do instead; it goes with the answer ${revealed(no)} on one line.`), reasonChips(words), words,
h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), confirm)], false);
words.focus();
}
/**
* @param {Object} item a Yes/No choice or decision row.
* @param {Function} answer sends the label it is given: chooseOne() for a choice, answerPick() for a row.
* @returns {HTMLElement[]} the grant button answering Yes and the decline button answering No with an optional comment.
*/
function yesNoButtons(item, answer) {
const {yes, no} = Answers.pair(item);
return [
h("button", {type: "button", class: "btn small primary", disabled: ui.busy, ...named(revealed(yes), `${revealed(yes)}: answer ${short(item.title)}`), on: {click: () => answer(yes)}}, icon("bi-check-lg"), revealed(yes)),
h("button", {type: "button", class: "btn small danger", disabled: ui.busy, ...named(revealed(no), `${revealed(no)}: answer it, with an optional comment on what to do instead`), on: {click: () => declineSheet(item, no, answer)}}, icon("bi-x-lg"), revealed(no)),
];
}
+1 -1
View File
@@ -78,7 +78,7 @@
send.addEventListener("click", () => how.pick(item.options.filter((option) => how.toggled.has(option.label)).map((option) => option.label).join(PICKED), false));
}
const typed = chosen.length === 1 && !item.options.some((option) => option.label === chosen[0]) ? chosen[0] : null;
const input = h("input", {class: "field", type: "text", maxlength: OTHER_LIMIT, placeholder: how.other, "aria-label": `Other answer to ${item.id}`, value: typed || drafts.get(item.id) || null, disabled: how.locked});
const input = h("input", {class: "field", type: "text", maxlength: OTHER_LIMIT, placeholder: how.other, "aria-label": `Other answer to ${item.id}`, value: typed || drafts.get(item.id) || null, disabled: how.locked, "data-skills": item.repo || ""});
input.addEventListener("input", () => drafts.set(item.id, input.value));
const other = h("form", {class: "option other"}, input,
h("button", {type: "submit", class: "btn small", disabled: how.locked, ...named("Send", revealed(`Send this text: ${how.hint}`))}, icon("bi-send"), "Send"));
+115 -38
View File
@@ -1,8 +1,56 @@
const DIFF_TONES = {A: "ok", M: "info", D: "bad", R: "violet", B: "neutral"};
const HIDDEN_NOTES = new Set(["masked", "content withheld"]);
const diffView = {cache: new Map(), revealed: new Map(), version: 0, float: null, picked: null, timer: 0};
const LINE_NOTES_GO = "Your line comments go to the requesting agent with Deny as a call, or after Grant as a post.";
const LINE_JOIN = ";\n";
const diffView = {cache: new Map(), revealed: new Map(), marks: new Map(), version: 0, float: null, picked: null, timer: 0, hit: null};
const revealedOf = (item) => diffView.revealed.get(keyOf(item)) || new Map();
const hiddenFile = (item, file) => HIDDEN_NOTES.has(file.note) && !revealedOf(item).has(file.path);
const lineMarksOf = (ref) => diffView.marks.get(ref) || [];
const lineSpanOf = (mark) => `${mark.path}:${mark.from === mark.until ? mark.from : `${mark.from}-${mark.until}`}`;
/**
* @param {string} ref the keyOf() of an inbox item.
* @returns {string} its line comments as "path:line: comment" in the order they were set, joined by LINE_JOIN so they
* stay apart once a denial folds the lines into one; "" without one.
*/
const lineNotes = (ref) => lineMarksOf(ref).map((mark) => `${lineSpanOf(mark)}: ${mark.comment}`).join(LINE_JOIN);
/**
* @param {string} ref the keyOf() of an inbox item.
* @param {Object[]} marks its line comments [{path, from, until, comment}]; empty forgets them.
*/
function setLineMarks(ref, marks) {
if (marks.length) {
diffView.marks.set(ref, marks);
} else {
diffView.marks.delete(ref);
}
diffView.version += 1;
drawInbox();
drawStream();
repaintReview();
}
/**
* @param {string} ref the keyOf() of the item the rows belong to.
* @param {string} path the file the rows show.
* @param {HTMLElement[]} rows its table rows; a code row carries data-line.
* @returns {HTMLElement[]} the rows, each commented one marked and its comments shown after the last line they cover.
*/
function withLineMarks(ref, path, rows) {
const marks = lineMarksOf(ref).filter((mark) => mark.path === path);
const placed = new Set();
return rows.flatMap((row) => {
const line = Number(row.dataset.line);
if (!marks.some((mark) => line >= mark.from && line <= mark.until)) {
return [row];
}
row.setAttribute("class", `${row.getAttribute("class") || ""} marked`.trim());
const here = marks.filter((mark) => mark.until === line && !placed.has(mark));
here.forEach((mark) => placed.add(mark));
return [row, ...here.map((mark) => h("tr", {class: "match-mark", "data-line": line}, h("td", {colspan: row.children.length}, icon("bi-chat-square-text"), h("span", {class: "match-mark-text"}, revealed(mark.comment)))))];
});
}
function forgetRevealed() {
const waiting = new Set(state.inbox.map(keyOf));
@@ -105,7 +153,7 @@
if (file.status === "B" || !file.patch) {
return h("section", {class: "diff-file", "data-path": file.path, "data-status": file.status, "data-patch": "none", "data-hidden": shown}, h("div", {class: "diff-head"}, head));
}
const table = h("table", {class: "diff"}, h("tbody", {}, Diffs.rows(file.patch).map(patchRow)));
const table = h("table", {class: "diff"}, h("tbody", {}, withLineMarks(keyOf(item), file.path, Diffs.rows(file.patch).map(patchRow))));
return h("section", {class: "diff-file", "data-path": file.path, "data-status": file.status, "data-hidden": shown},
h("details", {open: !Diffs.collapsed(file)}, h("summary", {class: "diff-head"}, head), h("div", {class: "diff-scroll"}, table)));
}
@@ -126,7 +174,58 @@
function feedbackList(ref) {
const sent = Diffs.feedbackOf(state.messages, ref);
return sent.length ? h("ul", {class: "feedback-list", "aria-label": `Feedback: ${sent.length}`}, sent.map((message) => h("li", {}, icon("bi-chat-left-text"), h("span", {class: "text"}, message.text), when(message.created_ts)))) : null;
const marks = lineMarksOf(ref);
const marked = marks.map((mark, index) => h("li", {class: "line-mark"}, icon("bi-bookmark-fill"), h("code", {}, revealed(lineSpanOf(mark))), h("span", {class: "text"}, revealed(mark.comment)),
iconBtn("bi-x-lg", "Remove comment", "btn small ghost", () => setLineMarks(ref, marks.filter((_, at) => at !== index)), `Remove the comment on ${revealed(lineSpanOf(mark))}`)));
return sent.length || marks.length ? h("ul", {class: "feedback-list", "aria-label": `Feedback: ${sent.length + marks.length}`, title: marks.length ? LINE_NOTES_GO : null}, marked,
sent.map((message) => h("li", {}, icon("bi-chat-left-text"), h("span", {class: "text"}, message.text), when(message.created_ts)))) : null;
}
/**
* @param {HTMLElement} row a code row with data-line, as a right-click hits it.
* @returns {Object|null} the row as the lines a comment covers, like selectionFeedback(); null outside a [data-path] region of an item with a requester.
*/
function rowPick(row) {
const region = row.closest("[data-path]");
const card = region && region.closest("[data-ref]");
if (!card || !card.dataset.to || !row.dataset.line || row.classList.contains("match-mark") || row.closest(".match-card")) {
return null;
}
const line = Number(row.dataset.line);
return {ref: card.dataset.ref, to: card.dataset.to, path: region.dataset.path, from: line, until: line, anchor: row, inline: Boolean(region.closest("#sheet"))};
}
/**
* @param {Object} picked the lines to comment: {ref, to, path, from, until, anchor, inline}; inline puts the field
* under the anchor instead of a sheet of its own.
*/
function markLines(picked) {
hideFeedback();
const words = h("textarea", {class: "field", rows: 3, maxlength: OTHER_LIMIT, "aria-label": "Comment", placeholder: "Comment on these lines", "data-skills": ""});
const save = () => {
const comment = words.value.trim();
if (!comment) {
words.focus();
return false;
}
setLineMarks(picked.ref, [...lineMarksOf(picked.ref), {path: picked.path, from: picked.from, until: picked.until, comment}]);
rememberComment(comment);
return true;
};
const head = h("code", {}, revealed(lineSpanOf(picked)));
const chips = presetChips(words, savedComments(), "Recent comments");
const saveButton = (cls, done) => h("button", {type: "button", class: cls, ...named("Save comment", LINE_NOTES_GO), on: {click: () => save() && done()}}, icon("bi-bookmark-fill"), "Save");
if (picked.inline) {
const box = h("div", {class: "match-comment-box"}, head, chips, words);
const field = picked.anchor.tagName === "TR" ? h("tr", {class: "match-comment"}, h("td", {colspan: picked.anchor.children.length}, box)) : h("div", {class: "match-comment"}, box);
box.append(h("div", {class: "actions"}, btn("Cancel", "btn small ghost", () => field.remove()), saveButton("btn small primary", () => field.remove())));
document.querySelectorAll("#sheet .match-comment").forEach((open) => open.remove());
picked.anchor.after(field);
} else {
openSheet("Comment", [h("div", {class: "who"}, icon("bi-chat-left-text"), person(picked.to), head), h("p", {class: "muted"}, LINE_NOTES_GO), chips, words,
h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), saveButton("btn primary", closeSheet))], false);
}
words.focus();
}
function selectionFeedback() {
@@ -143,36 +242,12 @@
}
const quote = selection.toString();
const code = region.querySelector("code");
const lines = region.classList.contains("command") && code
? Diffs.lineSpan(code.textContent, quote)
: Diffs.span([...region.querySelectorAll("tr[data-line]")].filter((row) => range.intersectsNode(row)).map((row) => Number(row.dataset.line)));
const rows = [...region.querySelectorAll("tr[data-line]")].filter((row) => !row.classList.contains("match-mark") && range.intersectsNode(row));
const lines = region.classList.contains("command") && code ? Diffs.lineSpan(code.textContent, quote) : Diffs.span(rows.map((row) => Number(row.dataset.line)));
if (!lines) {
return null;
}
return {ref: card.dataset.ref, to: card.dataset.to, path: region.dataset.path, from: lines[0], until: lines[1], quote, rect: range.getBoundingClientRect()};
}
function feedbackSheet(picked) {
hideFeedback();
const words = h("textarea", {class: "field", rows: 4, "aria-label": "Feedback", title: "Feedback"});
const send = iconBtn("bi-send", "Send feedback", "btn primary", async () => {
if (!words.value.trim()) {
words.focus();
return;
}
send.disabled = true;
const sent = await radioSend({to: picked.to, text: Diffs.feedback(picked.ref, picked.path, picked.from, picked.until, picked.quote, words.value), upload: "", cls: "post", voice: ""});
send.disabled = false;
if (sent) {
closeSheet();
}
}, `Send feedback: a post to ${picked.to}`);
openSheet("Feedback", [
h("div", {class: "who"}, icon("bi-chat-left-text"), person(picked.to), h("code", {}, `${picked.path}:${picked.from}-${picked.until}`)),
h("pre", {class: "notes"}, Diffs.quoted(picked.quote)),
words,
h("div", {class: "actions"}, h("span", {class: "spacer"}), send)], false);
words.focus();
return {ref: card.dataset.ref, to: card.dataset.to, path: region.dataset.path, from: lines[0], until: lines[1], anchor: rows.length ? rows[rows.length - 1] : region, inline: Boolean(region.closest("#sheet")), rect: range.getBoundingClientRect()};
}
function hideFeedback() {
@@ -185,9 +260,9 @@
function showFeedback(picked, x, y) {
if (!diffView.float) {
diffView.float = h("div", {class: "feedback-float", role: "toolbar", hidden: true},
h("button", {type: "button", class: "btn small primary icon-only", ...named("Feedback", "Feedback (f): a post with the selected lines to the requesting agent"), on: {
h("button", {type: "button", class: "btn small primary icon-only", ...named("Comment", `Comment (f) on the selected lines. ${LINE_NOTES_GO}`), on: {
mousedown: (event) => event.preventDefault(),
click: () => diffView.picked && feedbackSheet(diffView.picked),
click: () => diffView.picked && markLines(diffView.picked),
}}, icon("bi-chat-left-text")));
document.body.append(diffView.float);
}
@@ -210,18 +285,20 @@
}
/**
* @returns the context menu items of a [data-path] region, a diff file or a command: Feedback while lines of one are
* selected.
* @param {HTMLElement} node the [data-path] region the menu is for.
* @returns the context menu items of a diff file or a command: Comment on the selected lines, else on the code row the
* right-click hit.
*/
function feedbackItems() {
const picked = selectionFeedback();
return picked ? [{label: "Feedback", hint: "f: a post with the selected lines to the requesting agent", run: () => feedbackSheet(picked)}] : [];
function feedbackItems(node) {
const row = diffView.hit && node.contains(diffView.hit) ? diffView.hit.closest("tr[data-line]") : null;
const picked = selectionFeedback() || (row ? rowPick(row) : null);
return picked ? [{label: "Comment", hint: `f: ${lineSpanOf(picked)}. ${LINE_NOTES_GO}`, run: () => markLines(picked)}] : [];
}
function feedbackKey() {
const picked = selectionFeedback();
if (picked) {
feedbackSheet(picked);
markLines(picked);
}
return Boolean(picked);
}
+1
View File
@@ -21,6 +21,7 @@
const caret = () => icon("bi-caret-down-fill", "caret");
const named = (label, hint) => ({title: hint || label, "aria-label": label});
const iconBtn = (name, label, cls, run, hint) => h("button", {type: "button", class: `${cls} icon-only`, ...named(label, hint), on: {click: run}}, icon(name));
const boxHead = (label, cls, ...children) => h("div", {class: cls ? `box-head ${cls}` : "box-head", role: children.flat(Infinity).some((child) => child instanceof Node && child.getAttribute("role") === "toolbar") ? "group" : "toolbar", "aria-label": label}, ...children);
const dash = (value) => (value === "" || value === "-" || value === null || value === undefined ? "–" : value);
const targetsOf = (row) => (row.to.length ? row.to.join(", ") : "all");
const fixed = (value) => value.toFixed(1);
+37 -11
View File
@@ -23,7 +23,7 @@
};
const SWITCH_TITLES = {enableArtifact: "Artifacts"};
const OTHER_OP = {add: "remove", remove: "add"};
const firewall = {data: null, busy: false, staged: {}, dom: null, targets: new Set(), picks: {}, shown: new Set(ROW_FILTERS.map(([id]) => id)), open: new Set(), tab: CONTROL_TABS[0][0]};
const firewall = {data: null, busy: false, staged: {}, dom: null, targets: new Set(), picks: {}, shown: new Set(ROW_FILTERS.map(([id]) => id)), open: new Set(), tab: CONTROL_TABS[0][0], missing: false};
const knownAgents = () => Object.keys(people()).filter((key) => key !== HUMAN && SESSION_KEY.test(key)).sort();
const firewallGroups = () => (firewall.data ? firewall.data.groups : []);
@@ -214,7 +214,7 @@
tabs[id] = h("button", {type: "button", role: "tab", id: `controls-tab-${id}`, "data-tab": id, "aria-controls": `controls-${id}`, "aria-selected": String(firewall.tab === id), on: {click: () => pick(id)}}, icon(glyph), label);
views[id] = h("div", {class: "stack", role: "tabpanel", id: `controls-${id}`, "aria-labelledby": `controls-tab-${id}`, hidden: firewall.tab !== id}, panels[id]);
}
return h("div", {class: "stack controls"}, h("h2", {class: "title"}, "Controls"), h("div", {class: "segmented", role: "tablist", "aria-label": "Controls"}, Object.values(tabs)), Object.values(views), bar);
return h("div", {class: "stack fw-controls"}, boxHead("Controls", "", h("h2", {class: "box-title"}, "Controls"), h("div", {class: "segmented", role: "tablist", "aria-label": "Controls"}, Object.values(tabs))), Object.values(views), bar);
}
async function firewallPost(path, payload, label) {
@@ -224,15 +224,28 @@
return result.ok;
}
/**
* @param {string} label the field's name, shown above the chips.
* @param {Array} items [value, text, leading node or null] per chip.
* @param {HTMLElement|null} empty what the field shows when items is empty.
* @returns {Object} {node, chosen}: the field and a reader of the checked values.
*/
function checkChips(label, items, empty) {
const boxes = items.map(([value, text, lead]) => ({value, box: h("input", {type: "checkbox", value}), text, lead}));
const node = h("div", {class: "fw-chips-field"}, h("span", {class: "fw-chips-label"}, label), items.length
? h("div", {class: "chips check-chips", role: "group", "aria-label": label}, boxes.map(({box, text, lead}) => h("label", {class: "chip check-chip"}, box, lead, h("span", {}, text))))
: empty);
return {node, chosen: () => boxes.filter(({box}) => box.checked).map(({value}) => value)};
}
function groupsCard() {
const name = h("input", {class: "field", type: "text", placeholder: "builders", "aria-label": "Group name"});
const members = h("select", {class: "field", multiple: true, size: Math.min(Math.max(knownAgents().length, 2), 6), "aria-label": "Members"}, knownAgents().map((key) => h("option", {value: key}, labelOf(key))));
const form = h("form", {class: "fw-form", "aria-label": "New agent group"}, h("label", {}, "Name", name), h("label", {}, "Members", members),
const members = checkChips("Members", knownAgents().map((key) => [key, labelOf(key), face(key, false)]), h("p", {class: "muted"}, "No agent known yet: agents appear once they post or claim work."));
const form = h("form", {class: "fw-form", "aria-label": "New agent group"}, h("label", {}, "Name", name), members.node,
h("button", {type: "submit", class: "btn soft", ...named("Add group", "Add group: name the chosen agents as one rule target")}, icon("bi-people"), "Add group"));
form.addEventListener("submit", async (event) => {
event.preventDefault();
const chosen = [...members.selectedOptions].map((option) => option.value).sort();
await firewallPost("/api/firewall/groups", {name: name.value.trim(), members: chosen}, "Group added");
await firewallPost("/api/firewall/groups", {name: name.value.trim(), members: members.chosen().sort()}, "Group added");
});
const rows = firewallGroups().map((group) => h("div", {class: "rule-row", "data-group": group.name}, h("strong", {}, revealed(group.name)), h("span", {class: "muted"}, revealed(group.members.map(labelOf).join(", "))), h("span", {class: "spacer"}),
iconBtn("bi-trash3", "Delete group", "btn small danger", () => firewallPost(`/api/firewall/groups/${encodeURIComponent(group.id)}/delete`, {}, "Group deleted"), revealed(`Delete group ${group.name}: rules signed for it keep their agents`))));
@@ -244,12 +257,13 @@
function setsCard() {
const name = h("input", {class: "field", type: "text", placeholder: "ci", "aria-label": "Set name"});
const days = h("input", {class: "field", type: "number", min: 1, max: 366, value: 7, "aria-label": "Days"});
const chosen = h("select", {class: "field", multiple: true, size: Math.min(Math.max(state.rules.length, 2), 6), "aria-label": "Rules"}, state.rules.map((rule) => h("option", {value: rule.id}, revealed(`${rule.kind} ${rule.tool} ${rule.pattern}`.replace(" ", " ")))));
const form = h("form", {class: "fw-form", "aria-label": "New rule set"}, h("label", {}, "Name", name), h("label", {}, "Days", days), h("label", {}, "Rules", chosen),
const chosen = checkChips("Rules", state.rules.map((rule) => [rule.id, revealed(`${rule.kind} ${rule.tool} ${rule.pattern}`.replace(" ", " ")), null]),
h("p", {class: "muted"}, "No rule yet: create one under Rules, New hub rule for automatic grants, then pick it here."));
const form = h("form", {class: "fw-form", "aria-label": "New rule set"}, h("label", {}, "Name", name), h("label", {}, "Days", days), chosen.node,
h("button", {type: "submit", class: "btn soft", ...named("Save set", "Save set: keep the chosen rules as one named rule set")}, icon("bi-collection"), "Save set"));
form.addEventListener("submit", async (event) => {
event.preventDefault();
await firewallPost("/api/firewall/sets", {name: name.value.trim(), days: Number(days.value), rules: [...chosen.selectedOptions].map((option) => option.value)}, "Rule set saved");
await firewallPost("/api/firewall/sets", {name: name.value.trim(), days: Number(days.value), rules: chosen.chosen()}, "Rule set saved");
});
const sets = firewall.data ? firewall.data.sets : [];
const rows = sets.map((set) => setRow(set));
@@ -339,7 +353,7 @@
const byAction = (one, two) => ACTION_ORDER.indexOf(one.filter) - ACTION_ORDER.indexOf(two.filter);
function sourceGroups() {
return [{id: HUB_SOURCE, label: "Hub rules", file: false, status: null, rows: signedRows()}, ...firewall.data.files.map((file) => ({id: file.path, label: file.path, file: true, status: fileStatus(file), rows: fileRows(file)}))];
return [{id: HUB_SOURCE, label: "Hub rules", file: false, status: null, rows: signedRows()}, ...SettingsFiles.listed(firewall.data.files, firewall.missing).shown.map((file) => ({id: file.path, label: file.path, file: true, status: fileStatus(file), rows: fileRows(file)}))];
}
function hitsCell(row) {
@@ -540,7 +554,19 @@
return h("section", {class: "card stack-tight fw-rules", "aria-label": "Firewall rules"}, h("h3", {}, "Firewall rules"),
h("p", {class: "muted"}, `Every rule in one table: the hub rules and the permissions and sandbox entries of the listed settings files as the host read them, one folded group per source. Hits count the asks of the last ${data.days} days a rule matches, with the matcher of the rule request dry run; allow, deny and sandbox entries never reach the ask ledger and show not seen. A settings change shows as a diff, is signed with your passkey and is written by the host, never by an agent.`),
data.error ? h("p", {class: "muted"}, data.error) : null,
filterChips(), ruleTable(), files.length ? addForm(files) : null);
h("div", {class: "row fw-filters"}, filterChips(), missingToggle(SettingsFiles.listed(files, false).missing)), ruleTable(), files.length ? addForm(files) : null);
}
function missingToggle(count) {
if (!count) {
return null;
}
const label = `${firewall.missing ? "hide" : "show"} ${count} missing`;
return h("button", {type: "button", class: "btn small ghost fw-missing", "aria-pressed": String(firewall.missing),
...named(label, `${label}: settings files whose folder does not exist on this host; a change cannot create them`), on: {click: () => {
firewall.missing = !firewall.missing;
drawFirewall();
}}}, icon(firewall.missing ? "bi-eye-slash" : "bi-eye"), label);
}
function diffLines(text) {
+1 -1
View File
@@ -186,5 +186,5 @@
const toolbar = agentsToolbar();
graphDom = {stage: stageBox, pulses: null, toolbar};
const body = view === "tree" ? spawnScreen() : view === "hierarchy" ? hierarchyScreen() : h("div", {class: "card stage-card", "data-panel": `agents/${view}`}, stageBox, view === "3d" ? null : legend());
return h("div", {class: "graph"}, h("div", {class: "card controls"}, viewSwitch("agents"), view === "3d" ? layoutTools("agents") : null, toolbar.bar), body);
return h("div", {class: "graph"}, boxHead("Agents", "", viewSwitch("agents"), view === "3d" ? layoutTools("agents") : null, toolbar.bar), body);
}
+44 -3
View File
@@ -1,4 +1,6 @@
const HOME_PATH = "home.pins";
const ZOOM_PATH = "home.zoom";
const ZOOM_KEYS = {"+": 1, "=": 1, "-": -1, "0": 0};
const HOME_FETCH = 3000;
const HOME_MESSAGE = 30000;
const HOME_MARKS = [['section[aria-label="Recently sent"]', "radio-log"]];
@@ -146,6 +148,12 @@
return row ? h("ol", {class: "task-list"}, taskItem(row, etaOf().get(row.task))) : null;
}
function homeBoard() {
const board = kanbanBoard(shownTasks());
homeView.heads.set("tasks/board", board.querySelector(".kanban-bar"));
return board;
}
function homeTaskList() {
const etas = etaOf();
return h("ol", {class: "task-list"}, Plan.sortRows(shownTasks(), taskView.sort, taskView.descending).map((row) => taskItem(row, etas.get(row.task))));
@@ -167,7 +175,7 @@
Panels.panel("artifacts/swimlane", "Artifacts: Swimlane", () => homeArt("swimlane"));
Panels.panel("artifacts/3d", "Artifacts: 3D", () => homeTree(() => home3d("artifacts")), "3d");
Panels.panel("tasks/list", "Tasks: list", homeTaskList);
Panels.panel("tasks/board", "Tasks: kanban", () => kanbanBoard(shownTasks()));
Panels.panel("tasks/board", "Tasks: kanban", homeBoard);
Panels.panel("tasks/rasci", "Tasks: RASCI", () => taskMatrix(shownTasks()));
Panels.panel("tasks/gantt", "Tasks: Gantt", () => ganttChart(shownTasks()));
Panels.panel("tasks/burn", "Tasks: burndown and burnup", () => burnChart(state.tasks, shownTasks()));
@@ -181,6 +189,7 @@
Panels.panel("agents/order", "Agents: priority", homeOrder);
Panels.panel("tasks/operator", "Tasks: Waits on Operator", homeInbox);
Panels.panel("tasks/match", "Tasks: Match", () => homeMatch(), "", [6, 8]);
Panels.panel("resources-accounts", "Resources: accounts", () => homeAccounts(), "", [12, 5]);
Panels.item("metric", (id, view) => metricTitle(view), (size, id, view) => homeMetric(id, view));
Panels.capture("resources-hardware", () => resourcePin("hardware"));
Panels.capture("resources-tokens", () => resourcePin("tokens"));
@@ -466,11 +475,40 @@
function homeKeys(event, key) {
const steps = {ArrowLeft: -1, ArrowUp: -1, ArrowRight: 1, ArrowDown: 1};
if (event.target !== event.currentTarget || !Object.hasOwn(steps, event.key) || event.altKey || event.ctrlKey || event.metaKey) {
if (event.target !== event.currentTarget || event.altKey || event.ctrlKey || event.metaKey) {
return;
}
if (Object.hasOwn(ZOOM_KEYS, event.key)) {
event.preventDefault();
event.stopPropagation();
homeZoomBy(key, ZOOM_KEYS[event.key]);
} else if (Object.hasOwn(steps, event.key)) {
event.preventDefault();
homeSave((pins) => Panels.moveKey(pins, key, steps[event.key]));
}
}
const homeZoom = (key) => ViewStore.get(ZOOM_PATH)[key] || Panels.ZOOM.base;
function homeZoomBy(key, step) {
ViewStore.update(ZOOM_PATH, (zooms) => Panels.zoomBy(zooms, key, step));
}
function homeWheel(event, key) {
if (!event.ctrlKey || !event.deltaY) {
return;
}
event.preventDefault();
homeSave((pins) => Panels.moveKey(pins, key, steps[event.key]));
homeZoomBy(key, event.deltaY < 0 ? 1 : -1);
}
function paintZoom(tile) {
const zoom = homeZoom(tile.dataset.pin);
const body = tile.querySelector(".home-body");
if (body.dataset.zoom !== String(zoom)) {
body.dataset.zoom = String(zoom);
body.style.setProperty("--zoom", String(zoom / 100));
}
}
function homeSizeKeys(event, key) {
@@ -501,6 +539,7 @@
grip.addEventListener("pointerdown", (event) => homeGrab(event, key, "move"));
handle.addEventListener("pointerdown", (event) => homeGrab(event, key, "size"));
handle.addEventListener("keydown", (event) => homeSizeKeys(event, key));
body.addEventListener("wheel", (event) => homeWheel(event, key), {passive: false});
homeView.tiles.set(key, tile);
return tile;
}
@@ -560,6 +599,7 @@
if (body.childNodes.length !== 1 || body.firstChild !== shown) {
body.replaceChildren(shown);
}
paintZoom(tile);
}
function drawHome() {
@@ -614,6 +654,7 @@
drawHome();
homeView.mark();
});
ViewStore.on(ZOOM_PATH, () => drawHome());
homeView.mark = Panels.decorate(document.body, {pinned: (kind, id) => Panels.has(homePins(), kind, id), press: homePress, marks: HOME_MARKS});
window.addEventListener("pointermove", homeDragMove);
window.addEventListener("pointerup", homeDragEnd);
+51 -9
View File
@@ -114,12 +114,32 @@
}
return submit([entryOf(item, "approve", item.recommended)], `Choice: ${shownPick(item.recommended)}`);
}
return submit([entryOf(item, "approve", "")], `${item.kind === "operator" ? "Run" : "Grant"}: ${short(item.title)}`);
return withGrantNotes(item, submit([entryOf(item, "approve", "")], `${item.kind === "operator" ? "Run" : "Grant"}: ${short(item.title)}`));
}
/**
* @param {Object} item the granted inbox item.
* @param {Promise<boolean>|boolean} granted whether its grant went through.
* @returns {Promise<boolean>} granted; once it holds, the item's line comments go to its requester as one post and
* are forgotten.
*/
async function withGrantNotes(item, granted) {
const done = await granted;
const notes = lineNotes(keyOf(item));
if (!done || !notes) {
return done;
}
if (!item.to) {
toast("Line comments kept", ["The card names no agent to post them to."], false);
} else if (await radioSend({to: item.to, text: `Granted: ${item.title}. Notes:\n${notes}`, upload: "", cls: "post", voice: ""})) {
setLineMarks(keyOf(item), []);
}
return done;
}
const chooseOne = (item, label) => (picking(item) ? collectPick(item, label) : submit([entryOf(item, "approve", label)], `Choice: ${shownPick(label)}`));
const answerPick = (item, label) => (picking(item) ? collectPick(item, label) : answerRow(item, label));
const grantSolo = (item) => (item.kind === "rule" ? acceptRule(item) : submit([entryOf(item, "approve", "")], `Grant: ${short(item.title)}`));
const grantSolo = (item) => (item.kind === "rule" ? acceptRule(item) : withGrantNotes(item, submit([entryOf(item, "approve", "")], `Grant: ${short(item.title)}`)));
const asked = (item) => item.kind === "operator" && item.check === "decision";
async function answerRow(item, answer) {
@@ -139,14 +159,18 @@
* @param {string} answer the picked label, or the typed text.
* @param {boolean} typed whether answer is typed text, which always denies with it as the reason.
*/
const answerAsk = (item, answer, typed) => (!typed && answer === ALLOW ? approveOne(item) : denyNow(item, "post", typed ? answer : "", item.to));
const answerAsk = (item, answer, typed) => (!typed && answer === ALLOW ? approveOne(item) : denyNow(item, lineNotes(keyOf(item)) ? "call" : "post", withNotes(item, typed ? answer : ""), item.to));
/**
* @param {Object} item an inbox item.
* @param {Function} after called before a picked answer is sent.
* @returns {HTMLElement|Array|null} the choiceDialog() of a decision, a decision row or a permission ask, with its recipient line for a row; null for every other item.
* @returns {HTMLElement|Array|null} the choiceDialog() of a decision or a decision row with named options, with its recipient line for a row; only
* that line for a Yes/No row and null for a permission ask or a Yes/No decision, which booleanActions() answers; null for every other item.
*/
const choiceOf = (item, after) => {
if (Answers.boolean(item)) {
return asked(item) ? answerTo(item) : null;
}
if (item.kind === "decision") {
return choiceDialog(item, {pick: (label) => { after(); chooseOne(item, label); }, toggled: new Set(), chosen: ui.selected.has(keyOf(item)) ? grantLabel(item) : "", locked: item.held, hint: signsFor(item), group: "", other: OTHER_PROMPT});
}
@@ -165,7 +189,8 @@
const answerTo = (item) => h("p", {class: "muted answer-to"}, item.agent ? ["Your answer goes to ", h("strong", {}, revealed(item.agent)), " as a passkey-signed call that wakes it at once, with the row id and your answer only."] : UNASSIGNED);
const deniable = (item) => item.deniable || item.kind === "review";
const denialOf = (item, reason) => ({...entryOf(item, "reject", ""), channel: "post", reason, to: item.to});
const withNotes = (item, reason) => [reason, lineNotes(keyOf(item))].filter(Boolean).join(LINE_JOIN).slice(0, DENY_REASON);
const denialOf = (item, reason) => ({...entryOf(item, "reject", ""), channel: lineNotes(keyOf(item)) ? "call" : "post", reason: withNotes(item, reason), to: item.to});
const pickable = (item) => !item.held && (collectable(item) || deniable(item));
const unsettled = (item) => item.reviews.filter((review) => review.status !== "approved");
@@ -203,7 +228,7 @@
item.kind === "operator" ? h("span", {class: "muted"}, revealed(`in ${item.directory}`)) : null,
item.kind === "ask" ? h("div", {class: "command"}, h("code", {}, revealed(item.command))) : null));
const confirm = h("button", {type: "button", class: deny ? "btn danger" : "btn primary"}, `${deny ? "Deny" : "Grant"} ${usable.length + alone.length}`);
const reason = deny ? h("textarea", {class: "field", maxlength: DENY_REASON, rows: 3, placeholder: "e.g. make the gate green first"}) : null;
const reason = deny ? h("textarea", {class: "field", maxlength: DENY_REASON, rows: 3, placeholder: "e.g. make the gate green first", "data-skills": ""}) : null;
confirm.addEventListener("click", async () => {
closeSheet();
for (const item of alone) {
@@ -211,8 +236,14 @@
return;
}
}
if (usable.length) {
await submit(usable.map((item) => (deny ? denialOf(item, reason.value) : entryOf(item, "approve", labels.get(keyOf(item))))), `${label}: ${usable.length} entries`);
if (usable.length && (await submit(usable.map((item) => (deny ? denialOf(item, reason.value) : entryOf(item, "approve", labels.get(keyOf(item))))), `${label}: ${usable.length} entries`))) {
for (const item of usable) {
if (deny && lineNotes(keyOf(item))) {
setLineMarks(keyOf(item), []);
} else if (!deny) {
await withGrantNotes(item, true);
}
}
}
});
openSheet(label, [h("p", {class: "muted"}, deny ? DENY_NOTE : grantNote(alone.length, usable.length)), h("ul", {class: "mini"}, rows), ...(deny ? [reasonChips(reason), h("label", {class: "deny-reason"}, "Reason (optional, every requester reads it)", reason)] : []),
@@ -286,6 +317,8 @@
return h("button", {type: "button", class: "btn small primary", ...named(`Approve ${waiting.length} and run`, why), disabled: stuck || ui.busy, on: {click: () => (collecting(item) ? collect(item) : bulk(withReviews([item]), "Approve and run", false))}}, icon("bi-play-fill"), `Approve ${waiting.length} and run`);
}
const blockedButton = (glyph, word, reason) => h("button", {type: "button", class: "btn small", disabled: true, "data-blocked": "", ...named(word, `${word}: not possible now. ${reason}`)}, icon(glyph), word);
function actionsFor(item) {
if (item.held) {
return [h("span", {class: "muted"}, "takes effect …")];
@@ -295,15 +328,23 @@
if (item.kind === "review") {
grant(iconBtn("bi-check-lg", "Grant", "btn small primary", () => approveOne(item)));
buttons.push(denySplit(item));
} else if (item.kind === "ask") {
grant(iconBtn("bi-check-lg", "Grant", "btn small primary", () => approveOne(item), "Grant: allow this one call"));
} else if (Answers.pair(item)) {
buttons.push(...yesNoButtons(item, (label) => (asked(item) ? answerPick(item, label) : chooseOne(item, label))));
} else if (item.kind === "decision" && item.recommended) {
grant(h("button", {type: "button", class: "btn small primary", ...named(revealed(`Recommendation: ${shownPick(item.recommended)}`)), on: {click: () => approveOne(item)}}, icon("bi-check-lg"), revealed(shownPick(item.recommended))));
} else if (item.kind === "operator" && item.runnable) {
grant(runButton(item));
} else if (item.kind === "operator" && item.blocked) {
buttons.push(blockedButton("bi-play-fill", "Run", item.blocked));
} else if (item.kind === "rule") {
grant(h("button", {type: "button", class: "btn small primary", ...named("Accept", "Accept: the passkey signs exactly this rule, then it applies"), on: {click: () => approveOne(item)}}, icon("bi-shield-check"), "Accept"));
}
if (item.deniable) {
buttons.push(denySplit(item));
} else if (item.kind === "operator" && item.blocked) {
buttons.push(blockedButton("bi-x-lg", "Deny", item.blocked));
}
if (item.job && !jobOpen(item.job)) {
buttons.push(iconBtn("bi-x-circle", "Close", "btn small ghost", () => dismissJob(item.job), "Close: hide the console; a done row disappears with it"));
@@ -341,7 +382,7 @@
const wait = waitOf(item);
const classes = ["item", "entry", `k-${item.kind}`, "waiting", isGreen(item) ? "green" : "", red ? "red" : "", item.held ? "held" : "", wait ? "pending" : "", 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, "aria-busy": wait ? "true" : null, title: wait || null},
return h("li", {class: classes, "data-index": index, "data-ref": keyOf(item), "data-to": item.to || null, "data-blocked": item.blocked ? "" : null, "aria-busy": wait ? "true" : null, title: item.blocked || wait || null},
box,
h("div", {class: "msg-meta"},
when(item.ts),
@@ -361,6 +402,7 @@
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,
item.blocked ? h("p", {class: "item-blocked"}, icon("bi-slash-circle"), item.blocked) : null,
diffBlocks(item),
item.job ? consoleOf(item.job) : null,
item.kind === "rule" ? ruleRequestBody(item) : null,
+50 -30
View File
@@ -47,7 +47,7 @@
function matchOrder(cards) {
const ids = new Set(cards.map((card) => card.id));
const kept = matchView.order.filter((id) => ids.has(id));
const fresh = cards.filter((card) => !kept.includes(card.id)).sort((a, b) => Number(a.stale) - Number(b.stale) || (a.created_ts || 0) - (b.created_ts || 0));
const fresh = cards.filter((card) => !kept.includes(card.id)).sort((a, b) => Number(Boolean(a.blocked)) - Number(Boolean(b.blocked)) || Number(a.stale) - Number(b.stale) || (a.created_ts || 0) - (b.created_ts || 0));
matchView.order = [...kept, ...fresh.map((card) => card.id)];
const byId = new Map(cards.map((card) => [card.id, card]));
return matchView.order.map((id) => byId.get(id));
@@ -98,8 +98,10 @@
}
const patched = (card) => card.kind === "commit" || card.kind === "ask" || Boolean(card.merge);
const pickOnly = (card) => card.kind === "decision" && card.entry === "decision";
const flies = (card) => !card.stale && card.kind !== "rule" && (card.kind !== "decision" || Boolean(card.recommended));
const pickOnly = (card) => card.kind === "decision" && card.entry === "decision" && !Answers.pair(card);
const needsPick = (card) => card.kind === "decision" && !card.recommended && !Answers.pair(card);
const acceptLabel = (card) => (card.kind !== "decision" ? "" : Answers.pair(card) ? Answers.pair(card).yes : card.recommended);
const flies = (card) => !card.blocked && !card.stale && card.kind !== "rule" && !needsPick(card);
function matchFileRows(card, file) {
const diffed = patched(card);
@@ -162,7 +164,7 @@
const article = row.closest(".match-card");
closeComment(article);
const file = row.closest(".match-file");
const words = h("textarea", {class: "field", rows: 2, "aria-label": "Comment", placeholder: "Comment on this line"});
const words = h("textarea", {class: "field", rows: 2, "aria-label": "Comment", placeholder: "Comment on this line", "data-skills": card.repo || ""});
const save = h("button", {type: "button", class: "btn small primary match-save", ...named("Save mark"), on: {click: () => {
if (!words.value.trim()) {
words.focus();
@@ -290,27 +292,16 @@
return choiceDialog({...card, id: card.ref}, {pick, toggled, chosen: kept ? kept.label : "", locked: false, hint: `picked now, sent to ${card.agent || "its agent"} at the release`, group: "match-options", other: OTHER_PROMPT});
}
/**
* @param {Object} card a permission ask card.
* @returns {HTMLElement} its choiceDialog(): Yes accepts, No rejects, typed text rejects with it as the feedback; all sent at the release.
*/
function matchAsk(card) {
const kept = matchView.decisions.get(cardKey(card));
const chosen = !kept ? "" : kept.verdict === "accept" ? ALLOW : kept.feedback || "No";
const pick = (answer, typed) => (!typed && answer === ALLOW ? acceptCard(card) : decide(card, "reject", typed ? answer : "", ""));
return choiceDialog(askDialog(card.ref), {pick, toggled: new Set(), chosen, locked: false, hint: `picked now, sent to ${card.agent || "its session"} at the release`, group: "match-options", other: TELL});
}
function matchPayload(card) {
if (card.kind === "decision") {
return h("section", {class: "match-payload"}, card.reason && card.reason !== "-" ? h("p", {class: "match-reason"}, revealed(card.reason)) : null, matchOptions(card));
return h("section", {class: "match-payload"}, card.reason && card.reason !== "-" ? h("p", {class: "match-reason"}, revealed(card.reason)) : null, Answers.pair(card) ? null : matchOptions(card));
}
if (card.kind === "rule") {
return h("section", {class: "match-payload"}, ruleRequestBody({...card, detail: card.reason}));
}
if (card.kind === "ask") {
return h("section", {class: "match-payload"}, h("pre", {class: "match-command"}, h("code", {}, revealed(card.command))), h("p", {class: "match-directory"}, revealed(card.directory)),
card.warnings.length ? h("p", {class: "match-warnings"}, card.warnings.map((warning) => pill(warning, "bad"))) : null, matchAsk(card));
card.warnings.length ? h("p", {class: "match-warnings"}, card.warnings.map((warning) => pill(warning, "bad"))) : null);
}
if (card.kind !== "command") {
return null;
@@ -339,11 +330,11 @@
function matchCard(card) {
const files = card.files || [];
const none = card.kind === "commit" ? "No diff shipped with this stage." : card.kind === "ask" ? "Its tool call changes no file." : card.merge ? (card.merge.error ? "No diff to show." : "The merge brings no change.") : "Its command names no file.";
const none = card.kind === "commit" ? (card.diff_error ? `No diff shipped with this stage. ${card.diff_error}` : "No diff shipped with this stage.") : card.kind === "ask" ? "Its tool call changes no file." : card.merge ? (card.merge.error ? "No diff to show." : "The merge brings no change.") : "Its command names no file.";
const list = files.length ? h("ol", {class: "match-files", "aria-label": `Files: ${files.length}`}, files.map((file, index) => fileBlock(card, file, index))) : card.kind === "decision" || card.kind === "rule" ? null : h("p", {class: "muted"}, none);
const body = h("div", {class: "match-body"}, matchPayload(card), list);
const body = h("div", {class: "match-body"}, card.blocked ? h("p", {class: "match-blocked"}, icon("bi-hourglass-split"), revealed(card.blocked)) : null, matchPayload(card), list);
body.addEventListener("scroll", () => openOnScroll(body, ".match-file"), {passive: true});
const article = h("article", {class: "card match-card front", "data-card": card.id, "data-kind": card.kind, "data-stale": String(Boolean(card.stale)), "aria-label": `${card.kind} card of ${card.agent || "an agent"}`},
const article = h("article", {class: "card match-card front", "data-card": card.id, "data-kind": card.kind, "data-stale": String(Boolean(card.stale)), ...(card.blocked ? {"data-blocked": "", title: card.blocked} : {}), "aria-label": `${card.kind} card of ${card.agent || "an agent"}`},
matchHead(card), body);
article.style.setProperty("--agent-hue", String(Faces.hash(card.agent) % 360));
paint(article, card.id);
@@ -354,7 +345,7 @@
function peekTab(card) {
const [kindName, kindTone] = MATCH_KINDS[card.kind] || [card.kind, "neutral"];
return h("button", {type: "button", class: "match-peek", "data-card": card.id, "data-stale": String(Boolean(card.stale)), ...named(`Show ${kindName.toLowerCase()} card: ${card.title}`), on: {click: () => {
return h("button", {type: "button", class: "match-peek", "data-card": card.id, "data-stale": String(Boolean(card.stale)), ...(card.blocked ? {"data-blocked": ""} : {}), ...named(`Show ${kindName.toLowerCase()} card: ${card.title}`, card.blocked ? `${card.title}: ${card.blocked}` : undefined), on: {click: () => {
matchView.order = [card.id, ...matchView.order.filter((id) => id !== card.id)];
drawMatch(true);
}}}, face(card.agent || "-", false), h("span", {class: "pill", "data-tone": kindTone}, kindName), card.stale ? h("span", {class: "pill", "data-tone": "bad"}, "stale") : null, h("span", {class: "match-peek-title"}, revealed(card.title)));
@@ -421,7 +412,20 @@
}));
}
/**
* @returns {boolean} whether the card can not act here; the toast then names its reason under the verdict.
*/
function refusedHere(card, verdict) {
if (card.blocked) {
toast(`${verdict}: not possible now`, [card.blocked], false);
}
return Boolean(card.blocked);
}
function acceptCard(card) {
if (refusedHere(card, "Accept")) {
return;
}
if (card.stale) {
toast("Accept: refused", [`The card is stale: ${card.stale_reason}. Add it again to decide it.`], false);
return;
@@ -435,25 +439,29 @@
}
return;
}
if (card.kind === "decision" && !card.recommended) {
if (needsPick(card)) {
toast("Accept: pick one of its options", ["The decision recommends none, so the card waits for your pick."], false);
return;
}
decide(card, "accept", "", card.kind === "decision" ? card.recommended : "");
decide(card, "accept", "", acceptLabel(card));
}
function rejectCard(card) {
if (refusedHere(card, "Reject")) {
return;
}
if (pickOnly(card)) {
toast("Reject: not possible", ["A choice is answered with one of its options."], false);
return;
}
const kept = matchView.decisions.get(cardKey(card));
const words = h("textarea", {class: "field match-feedback", rows: 6, maxlength: FEEDBACK_LIMIT, "aria-label": "Feedback"});
const words = h("textarea", {class: "field match-feedback", rows: 6, maxlength: FEEDBACK_LIMIT, "aria-label": "Feedback", "data-skills": card.repo || ""});
words.value = (kept && kept.verdict === "reject" ? kept.feedback : feedbackOf(card)).slice(0, FEEDBACK_LIMIT);
const confirm = h("button", {type: "button", class: "btn danger match-feedback-reject"}, icon("bi-x-lg"), "Reject");
const pair = card.kind === "decision" ? Answers.pair(card) : null;
confirm.addEventListener("click", () => {
closeSheet();
decide(card, "reject", words.value.trim(), "");
decide(card, "reject", words.value.trim(), pair ? Answers.declined(pair.no, words.value, OTHER_LIMIT) : "");
});
const note = `${card.agent || "The agent"} gets this text by radio call at the release; nothing is sent before.`;
openSheet(`Reject: ${card.title}`, [h("p", {class: "muted"}, note), reasonChips(words), words, h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), confirm)], false);
@@ -542,6 +550,9 @@
function matchEntry(card, decision) {
const kind = card.entry || (card.kind === "commit" ? "review" : "operator");
const entry = {kind, id: card.ref, verb: decision.verdict === "accept" ? "approve" : "reject", label: decision.verdict === "accept" ? decision.label || "" : "", sha256: kind === "operator" ? card.sha256 || "" : ""};
if (card.kind === "decision" && Answers.pair(card)) {
return {...entry, verb: "approve", label: decision.label};
}
if (decision.verdict === "reject") {
return {...entry, channel: "call", reason: decision.feedback, to: card.to || ""};
}
@@ -563,6 +574,13 @@
matchView.overview = false;
drawMatch(true);
await fetchMatch();
for (const [card, decision] of picked) {
const notes = decision.verdict === "accept" ? feedbackOf(card) : "";
if (notes && card.to) {
await radioSend({to: card.to, text: `Granted: ${card.title}. Notes:\n${notes}`, upload: "", cls: "post", voice: ""});
}
matchView.marks.delete(cardKey(card));
}
}
}
@@ -631,7 +649,7 @@
if (matchView.drag) {
matchView.drag.end();
}
const bar = h("div", {class: "card controls task-toolbar", role: "toolbar", "aria-label": "Match"}, h("strong", {}, icon("bi-stack"), "Match"), count, h("span", {class: "spacer"}), decisions, peeks,
const bar = boxHead("Match", "task-toolbar", h("strong", {class: "box-title"}, icon("bi-stack"), "Match"), count, h("span", {class: "spacer"}), decisions, peeks,
iconBtn("bi-list-check", "Tasks", "btn small soft", () => go("tasks", null), "Tasks: back to the task list"), h("span", {"data-star-slot": ""}));
fetchMatch();
return h("div", {class: "graph tasks match", "data-panel": "tasks/match"}, bar, stack);
@@ -706,9 +724,11 @@
matchView.front = front;
const act = (cls, iconName, word, hint, disabled, run) => h("button", {type: "button", class: `match-act ${cls}`, disabled, ...named(word, hint), on: {click: run}},
h("span", {class: "match-act-face", "aria-hidden": "true"}, icon(iconName)), h("span", {class: "match-act-label"}, word));
const hint = front.stale ? `Accept: refused while the card is stale (${front.stale_reason})` : front.kind === "rule" ? "Accept: opens its row, where the passkey signs exactly this rule" : front.kind === "decision" ? (front.recommended ? `Accept: ${shownPick(front.recommended)} (right arrow, swipe right)` : "Accept: pick one of its options") : "Accept (right arrow, swipe right)";
const accept = act("match-accept", "bi-check-lg", "Accept", revealed(hint), Boolean(front.stale) || (front.kind === "decision" && !front.recommended), () => acceptCard(front));
const reject = act("match-reject", "bi-x-lg", "Reject", pickOnly(front) ? "Reject: a choice is answered with one of its options" : "Reject with feedback (left arrow, swipe left)", pickOnly(front), () => rejectCard(front));
const hint = front.blocked ? `Accept: not possible now. ${front.blocked}` : front.stale ? `Accept: refused while the card is stale (${front.stale_reason})` : front.kind === "rule" ? "Accept: opens its row, where the passkey signs exactly this rule" : front.kind === "decision" ? (needsPick(front) ? "Accept: pick one of its options" : `Accept: ${shownPick(acceptLabel(front))} (right arrow, swipe right)`) : "Accept (right arrow, swipe right)";
const accept = act("match-accept", "bi-check-lg", "Accept", revealed(hint), Boolean(front.blocked || front.stale) || needsPick(front), () => acceptCard(front));
const declining = front.kind === "decision" && Answers.pair(front) ? `Reject: ${shownPick(Answers.pair(front).no)}, with an optional comment on what to do instead (left arrow, swipe left)` : "Reject with feedback (left arrow, swipe left)";
const rejectHint = front.blocked ? `Reject: not possible now. ${front.blocked}` : pickOnly(front) ? "Reject: a choice is answered with one of its options" : declining;
const reject = act("match-reject", "bi-x-lg", "Reject", revealed(rejectHint), Boolean(front.blocked) || pickOnly(front), () => rejectCard(front));
const later = act("match-later", "bi-arrow-up", "Later", "Later: to the back of the stack (up arrow, swipe up)", !rest.length, () => laterCard(front));
const peeks = rest.length && peeksShown() ? h("div", {class: "match-peeks", role: "group", "aria-label": `${rest.length} more cards`}, rest.map(peekTab)) : null;
const behind = rest.slice(0, MATCH_PEEKS).map((card, index) => {
@@ -721,6 +741,6 @@
const shown = matchCard(front);
shown.dataset.fresh = String(!before || before.dataset.card !== front.id);
draggable(shown, front);
keepTyping(dom.stack, () => dom.stack.replaceChildren(h("div", {class: "match-deck"}, behind, shown), h("div", {class: "match-actions"}, reject, later, accept), peeks));
keepTyping(dom.stack, () => dom.stack.replaceChildren(h("div", {class: "match-deck"}, behind, shown), h("div", {class: "match-actions"}, reject, later, accept), ...(peeks ? [peeks] : [])));
shown.querySelector(".match-body").scrollTop = scrolled;
}
+40 -15
View File
@@ -34,15 +34,18 @@
/**
* @param {HTMLInputElement|HTMLTextAreaElement} field the text field the transcript lands in.
* @param {boolean} auto whether the shared component placed the button right after the field and keeps it there.
* @returns {HTMLButtonElement} the microphone button of the field.
* @returns {HTMLButtonElement} the microphone button of the field, made once and kept.
*/
function micButton(field, auto) {
function micButton(field) {
const kept = micButtons.get(field);
if (kept) {
return kept;
}
if (!field.id) {
micCount += 1;
field.id = `mic-field-${micCount}`;
}
const button = h("button", {type: "button", class: auto ? "btn small ghost icon-only mic mic-auto" : "btn small ghost icon-only mic", "aria-controls": field.id}, icon("bi-mic"));
const button = h("button", {type: "button", class: "mic", "aria-controls": field.id}, icon("bi-mic"));
micButtons.set(field, button);
micFields.set(button, field);
field.dataset.mic = "on";
@@ -51,21 +54,43 @@
return button;
}
const micFramed = (field) => Boolean(field.parentElement && field.parentElement.classList.contains("mic-frame"));
/**
* @param {HTMLInputElement|HTMLTextAreaElement} field the text field; it moves into the frame.
* @param {Node[]} extras what belongs to a textarea besides its mic, on the footer's left (Record, a count); [] for none.
* @returns {HTMLElement} one frame around field and mic: for a one-line field the mic as the field's last segment, for a
* textarea a footer row below it whose last child is the mic.
*/
function micFrame(field, extras) {
const button = micButton(field);
if (field.tagName === "TEXTAREA") {
return h("div", {class: "mic-frame mic-area"}, field, h("div", {class: "mic-foot"}, extras, h("span", {class: "spacer"}), button));
}
return h("span", {class: "mic-frame mic-line"}, field, button);
}
function micWrap(field) {
const focused = document.activeElement === field;
const [start, end] = [field.selectionStart, field.selectionEnd];
const [parent, next] = [field.parentNode, field.nextSibling];
parent.insertBefore(micFrame(field, []), next);
if (focused) {
field.focus({preventScroll: true});
field.setSelectionRange(start, end);
}
}
function micSweep() {
for (const field of document.querySelectorAll(Voice.FIELDS)) {
const button = micButtons.get(field);
if (field.readOnly || (button && !button.classList.contains("mic-auto"))) {
continue;
}
if (!button) {
field.after(micButton(field, true));
} else if (button.previousElementSibling !== field) {
field.after(button);
if (!field.readOnly && !micFramed(field) && field.parentNode) {
micWrap(field);
}
}
for (const button of document.querySelectorAll("button.mic-auto")) {
if (!micFields.get(button).isConnected) {
button.remove();
for (const frame of document.querySelectorAll(".mic-frame")) {
const button = frame.querySelector(":scope > button.mic, :scope > .mic-foot > button.mic");
if (!button || micFields.get(button).parentElement !== frame) {
frame.remove();
}
}
}
+1 -1
View File
@@ -146,7 +146,7 @@
runPalette(palette.index);
}
});
box.replaceChildren(h("div", {class: "palette-box", role: "dialog", "aria-label": "Commands"}, h("div", {class: "palette-row"}, palette.input, micButton(palette.input, false)), palette.list));
box.replaceChildren(h("div", {class: "palette-box", role: "dialog", "aria-label": "Commands"}, h("div", {class: "palette-row"}, micFrame(palette.input, [])), palette.list));
box.hidden = false;
drawPalette();
palette.input.focus();
+3 -3
View File
@@ -296,8 +296,8 @@
}
function speakCard() {
const {form, recipient, text, channel, clear} = composerForm();
const part = {recipient, text, channel, clear, names: ""};
const {form, recipient, text, channel, mayday} = composerForm();
const part = {recipient, text, channel, mayday, 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;
@@ -307,7 +307,7 @@
const names = agentNames();
const sig = JSON.stringify(names);
for (const part of liveParts("speaks")) {
part.clear.hidden = !state.silence;
drawMayday(part.mayday);
if (sig !== part.names) {
part.names = sig;
const chosen = part.recipient.value;
+33 -11
View File
@@ -9,6 +9,7 @@
unknown: ["#bi-question-circle", (mark) => `${mark.name} unknown: no reading`, 0],
};
const RESOURCE_BURN = {done: "Done", scope: "Scope"};
const RESOURCE_PICKS = [["hardware", "Hardware"], ["tokens", "Tokens"], ["combined", "Combined"], ["accounts", "Accounts"]];
const resourceView = {data: null, dom: null, busy: false, key: "", at: 0, timer: 0, series: {}};
const resourceKey = () => JSON.stringify([ui.preset, ui.asOf]);
const resourcesStale = () => resourceKey() !== resourceView.key || nowSeconds() - resourceView.at >= RESOURCE.stale;
@@ -21,12 +22,22 @@
return h("button", {type: "button", class: "btn small soft res-switch", "data-switch": key, "aria-pressed": "false", ...named(label, hint), on: {click: () => ViewStore.set(path, next(ViewStore.get(path)))}}, icon(name), h("span", {}, label));
}
function resourcePicks() {
const boxes = RESOURCE_PICKS.map(([kind, label]) => {
const box = h("input", {type: "checkbox", "data-pick": kind, "aria-label": label, on: {change: () => ViewStore.update("resources.panels", (list) => [...list.filter((name) => name !== kind), ...(box.checked ? [kind] : [])])}});
return {kind, box, row: h("label", {class: "menu-item res-pick"}, box, h("span", {}, label))};
});
const menu = h("details", {class: "menu res-panels-menu"}, h("summary", {...named("Panels", "Panels: choose which panels Resources shows; the last one stays on")}, icon("bi-grid"), h("span", {}, "Panels"), caret()),
h("div", {class: "menu-box end", role: "group", "aria-label": "Panels"}, boxes.map((entry) => entry.row)));
return {menu, boxes};
}
function resourcesScreen() {
const count = h("span", {class: "count", title: "Samples", "aria-label": "Samples"}, "0");
const switches = {
tokens: resourceSwitch("tokens", (mode) => (mode === "accumulated" ? "interval" : "accumulated"), "bi-graph-up-arrow", "Accumulated", "Accumulated: per-agent running sums of the tokens instead of the tokens per hour"),
combined: resourceSwitch("combined", (on) => !on, "bi-layers", "Combined", "Combined: hardware in %, tokens and the burnup in one chart"),
};
const picks = resourcePicks();
const panels = RESOURCE_PANELS.map(([kind, name, label]) => {
const legend = h("div", {class: "res-legend"});
const plot = h("div", {class: "res-plot"});
@@ -34,7 +45,8 @@
h("div", {class: "res-head", "data-star-slot": ""}, h("span", {class: "res-title", title: label, "aria-label": label}, icon(name)), legend), plot);
return {kind, label, legend, plot, panel};
});
resourceView.dom = {count, switches, panels};
const accounts = accountsPanel();
resourceView.dom = {count, switches, picks, panels, accounts};
if (!resourceView.timer) {
resourceView.timer = window.setInterval(pollResources, RESOURCE.poll);
window.addEventListener("resize", drawResources);
@@ -43,11 +55,15 @@
window.setTimeout(() => {
drawResources();
fetchResources();
fetchAccounts();
}, 0);
const reload = iconBtn("bi-arrow-clockwise", "Reload", "btn small soft", fetchResources, "Reload: read the sampler files again");
const reload = iconBtn("bi-arrow-clockwise", "Reload", "btn small soft", () => {
fetchResources();
fetchAccounts();
}, "Reload: read the sampler files and the accounts again");
return h("div", {class: "graph resources"},
h("div", {class: "card controls"}, h("div", {class: "toolbar", role: "toolbar", "aria-label": "Resources"}, reload, switches.tokens, switches.combined, count)),
h("div", {class: "res-panels"}, panels.map((entry) => entry.panel)));
boxHead("Resources", "", h("div", {class: "toolbar"}, reload, switches.tokens, picks.menu, count)),
h("div", {class: "res-panels"}, panels.map((entry) => entry.panel), accounts.panel));
}
function pollResources() {
@@ -305,7 +321,7 @@
function metricParts(data, view) {
const span = {from: data.since, to: Math.max(data.until, data.since + 60)};
const parts = resourceParts(data, {tokens: view.tokens, hidden: [], combinedHidden: [], combined: view.chart === "combined"}, span);
const parts = resourceParts(data, {tokens: view.tokens, hidden: [], combinedHidden: [], panels: [view.chart]}, span);
const series = RESOURCE_SERIES[view.chart](parts);
return {span, parts, series, hidden: new Set(view.shown === null ? [] : series.map((line) => line.id).filter((id) => !view.shown.includes(id)))};
}
@@ -321,7 +337,7 @@
const {series, hidden} = metricParts(resourceView.data, view);
const ids = new Set(series.map((line) => line.id));
ViewStore.update(view.chart === "combined" ? "resources.combinedHidden" : "resources.hidden", (list) => [...list.filter((id) => !ids.has(id)), ...hidden]);
ViewStore.set("resources.combined", view.chart === "combined");
ViewStore.update("resources.panels", (list) => (list.includes(view.chart) ? list : [...list, view.chart]));
if (view.chart !== "hardware") {
ViewStore.set("resources.tokens", view.tokens);
}
@@ -336,7 +352,7 @@
mode: view.tokens,
hidden: new Set(view.hidden),
combinedHidden: new Set(view.combinedHidden),
burn: view.combined ? burnSeries(span) : [],
burn: view.panels.includes("combined") ? burnSeries(span) : [],
marks: [
...Resources.waits(data.samples).map((mark) => ({...mark, kind: "wait"})),
...Resources.blocked(data.samples).map((mark) => ({...mark, kind: "blocked"})),
@@ -354,10 +370,16 @@
}
const view = ViewStore.get("resources");
dom.switches.tokens.setAttribute("aria-pressed", String(view.tokens === "accumulated"));
dom.switches.combined.setAttribute("aria-pressed", String(view.combined));
for (const entry of dom.panels) {
entry.panel.hidden = (entry.kind === "combined") !== view.combined;
for (const {kind, box} of dom.picks.boxes) {
box.checked = view.panels.includes(kind);
box.disabled = box.checked && view.panels.length === 1;
box.title = box.disabled ? "The last panel stays on" : "";
}
for (const entry of dom.panels) {
entry.panel.hidden = !view.panels.includes(entry.kind);
}
dom.accounts.panel.hidden = !view.panels.includes("accounts");
drawAccounts();
if (data === null) {
return;
}
+35 -9
View File
@@ -39,14 +39,17 @@
return;
}
const item = state.inbox.find((entry) => entry.kind === "review" && entry.id === review.id);
const ref = item ? keyOf(item) : null;
const list = fileList(review.id);
const treeNav = h("nav", {class: "card tree", "aria-label": "Changed files"}, treePane(list));
const diff = h("section", {class: "card diff-pane", "aria-label": "Diff"}, diffPane(list));
const diff = h("section", {class: "card diff-pane", "aria-label": "Diff"}, diffPane(list, ref));
const notes = h("div", {class: "review-notes"}, ref ? feedbackList(ref) : null);
const id = ui.review;
const head = h("article", {class: "card"},
h("div", {class: "card-head"}, h("div", {}, h("p", {class: "muted"}, "submitted ", when(review.created_ts))), h("div", {class: "who"}, status(review.status || "pending"), review.gate ? pill(review.gate === "pass" ? "Gate green" : "Gate red", review.gate === "pass" ? "ok" : "bad") : null)),
meta([["Repo", review.worktree], ["Branch", review.branch], ["Tree", (review.tree || "").slice(0, 12), review.tree], ["Score", review.score]]),
review.notes ? h("pre", {class: "notes"}, revealedLines(review.notes)) : null,
notes,
h("div", {class: "actions"},
h("a", {class: "btn ghost icon-only", href: `/reviews/${encodeURIComponent(review.id)}/page`, target: "_blank", rel: "noopener noreferrer", ...named("Open full page", "Open full page (new tab)")}, icon("bi-box-arrow-up-right")),
h("span", {class: "spacer"}),
@@ -54,9 +57,26 @@
node.addEventListener("click", closeSheet);
return node;
}) : null));
openSheet(review.title, [head, h("div", {class: "split"}, treeNav, diff)], true);
openSheet(review.title, [head, h("div", {class: "split", "data-ref": ref, "data-to": item && item.to ? item.to : null}, treeNav, diff)], true);
ui.review = id;
reviewDom = {tree: treeNav, diff};
reviewDom = {tree: treeNav, diff, notes, ref};
}
function repaintReview() {
const stack = reviewDom && reviewDom.ref ? reviewDom.diff.querySelector(".review-stack") : null;
const list = stack ? files.get(ui.review) : null;
if (!Array.isArray(list)) {
return;
}
const top = stack.scrollTop;
const opened = [...stack.querySelectorAll(REVIEW_FILE)].map((file) => file.open);
stack.replaceChildren(...list.map((file, index) => {
const node = reviewFile(file, index, reviewDom.ref);
node.open = opened[index];
return node;
}));
stack.scrollTop = top;
reviewDom.notes.replaceChildren(...[feedbackList(reviewDom.ref)].filter(Boolean));
}
function nest(entries) {
@@ -149,21 +169,27 @@
if (line.kind === "hunk" || line.kind === "more") {
return h("tr", {class: line.kind}, h("td", {colspan: 3}), h("td", {class: "code"}, line.text));
}
return h("tr", {class: line.kind}, h("td", {class: "num"}, line.old), h("td", {class: "num"}, line.new), h("td", {class: "sign"}, SIGNS[line.kind] || " "), h("td", {class: "code"}, line.text));
return h("tr", {class: line.kind, "data-line": line.new || line.old || null}, h("td", {class: "num"}, line.old), h("td", {class: "num"}, line.new), h("td", {class: "sign"}, SIGNS[line.kind] || " "), h("td", {class: "code"}, line.text));
}
function diffPane(list) {
function diffPane(list, ref) {
if (!Array.isArray(list) || !list.length) {
return h("p", {class: "muted pad"}, list === "loading" ? "Loading changes …" : "No diff available.");
}
const stack = h("div", {class: "review-stack"}, list.map((file, index) => reviewFile(file, index)));
const stack = h("div", {class: "review-stack"}, list.map((file, index) => reviewFile(file, index, ref)));
stack.addEventListener("scroll", () => followScroll(stack), {passive: true});
return stack;
}
function reviewFile(file, index) {
/**
* @param {Object} file a file of the review's file list.
* @param {number} index its place in that list.
* @param {string|null} ref the keyOf() of the review's inbox item, whose line comments its rows show; null when it
* waits on nobody.
*/
function reviewFile(file, index, ref) {
const [letter, tone] = FILE_STATUS[file.status] || ["?", "neutral"];
return h("details", {class: "review-file", "data-index": index, open: index === ui.file},
return h("details", {class: "review-file", "data-index": index, "data-path": ref ? file.path : null, open: index === ui.file},
h("summary", {class: "diff-head"},
h("span", {class: "letter", "data-tone": tone}, letter),
h("code", {class: "path"}, file.old ? `${file.old} → ${file.path}` : file.path),
@@ -171,5 +197,5 @@
h("span", {class: "spacer"}),
stat(file)),
file.detail ? h("p", {class: "muted pad"}, file.detail) : null,
file.lines.length ? h("div", {class: "diff-wide"}, h("table", {class: "diff"}, h("tbody", {}, file.lines.map(diffRow)))) : null);
file.lines.length ? h("div", {class: "diff-wide"}, h("table", {class: "diff"}, h("tbody", {}, ref ? withLineMarks(ref, file.path, file.lines.map(diffRow)) : file.lines.map(diffRow)))) : null);
}
+142
View File
@@ -0,0 +1,142 @@
const SLASH_LIMIT = 8;
const SLASH_FRESH = 60000;
const SLASH_FIELDS = "textarea[data-skills], input[data-skills]";
const SLASH_TOKEN = /(^|\s)\/([A-Za-z0-9:_.-]*)$/;
const slash = {skills: [], fetched: 0, loading: null, bound: new WeakSet(), box: null, field: null, shown: [], active: 0, token: null};
/**
* @param {Array<{name: string, description: string, source: string}>} skills the rows /api/skills serves.
* @param {string} prefix what follows the "/", case ignored.
* @param {string} repo the repository the field's agent or card works in, "" for none.
* @returns {Array} at most SLASH_LIMIT rows, one per name: names that start with prefix before names that hold it,
* then the repository's own skills, then by name.
*/
function slashRank(skills, prefix, repo) {
const typed = prefix.toLowerCase();
const hits = skills.map((skill) => ({skill, at: skill.name.toLowerCase().indexOf(typed)})).filter((hit) => hit.at >= 0);
hits.sort((a, b) => Number(a.at !== 0) - Number(b.at !== 0) || Number(b.skill.source === repo) - Number(a.skill.source === repo) || a.skill.name.localeCompare(b.skill.name));
const seen = new Set();
return hits.map((hit) => hit.skill).filter((skill) => !seen.has(skill.name) && Boolean(seen.add(skill.name))).slice(0, SLASH_LIMIT);
}
/**
* @param {string} text the field's value.
* @param {number} caret where the caret stands.
* @returns {Object|null} {start, prefix}: the "/" word the caret ends: a "/" at the start or after
* whitespace, then skill name characters only; null inside a word or a path.
*/
function slashToken(text, caret) {
const found = SLASH_TOKEN.exec(text.slice(0, caret));
return found ? {start: caret - found[2].length - 1, prefix: found[2]} : null;
}
/**
* @returns {Object} {value, caret}: text with the token up to caret replaced by "/<name> ".
*/
function slashInsert(text, token, caret, name) {
const head = `${text.slice(0, token.start)}/${name} `;
return {value: head + text.slice(caret), caret: head.length};
}
function slashLoad() {
if (!slash.loading && Date.now() - slash.fetched > SLASH_FRESH) {
slash.loading = fetch("/api/skills", {cache: "no-store"}).then((response) => (response.ok ? response.json() : {skills: []})).then((data) => {
slash.skills = Array.isArray(data.skills) ? data.skills : [];
slash.fetched = Date.now();
}).catch(() => null).finally(() => {
slash.loading = null;
if (slash.field) {
slashShow(slash.field);
}
});
}
}
function slashClose() {
if (slash.box) {
slash.box.remove();
}
Object.assign(slash, {box: null, field: null, shown: [], active: 0, token: null});
}
function slashPick(field, skill) {
const next = slashInsert(field.value, slash.token, field.selectionStart, skill.name);
field.value = next.value;
field.setSelectionRange(next.caret, next.caret);
field.dispatchEvent(new Event("input", {bubbles: true}));
slashClose();
field.focus();
}
function slashPaint() {
slash.box.replaceChildren(...slash.shown.map((skill, index) => {
const option = h("div", {role: "option", class: "slash-option", id: `slash-option-${index}`, "aria-selected": String(index === slash.active), title: skill.source},
h("strong", {}, `/${skill.name}`), h("span", {class: "muted"}, skill.description));
option.addEventListener("pointerdown", (event) => {
event.preventDefault();
slashPick(slash.field, skill);
});
return option;
}));
slash.field.setAttribute("aria-activedescendant", `slash-option-${slash.active}`);
}
function slashShow(field) {
const token = field.selectionStart === field.selectionEnd ? slashToken(field.value, field.selectionStart) : null;
slashLoad();
const shown = token ? slashRank(slash.skills, token.prefix, field.dataset.skills) : [];
if (!shown.length) {
slashClose();
slash.field = token && slash.loading ? field : null;
return;
}
if (!slash.box || slash.field !== field) {
slashClose();
slash.box = h("div", {class: "slash-list", role: "listbox", "aria-label": "Skills"});
document.body.append(slash.box);
}
const box = field.getBoundingClientRect();
Object.assign(slash, {field, shown, token, active: Math.min(slash.active, shown.length - 1)});
slash.box.style.left = `${Math.max(8, Math.min(box.left, window.innerWidth - 8 - Math.min(448, window.innerWidth - 16)))}px`;
slash.box.style.top = `${box.bottom + 4}px`;
slashPaint();
}
function slashKeys(event, field) {
if (!slash.box || slash.field !== field) {
return;
}
const moves = {ArrowDown: 1, ArrowUp: -1};
if (Object.hasOwn(moves, event.key)) {
slash.active = (slash.active + moves[event.key] + slash.shown.length) % slash.shown.length;
slashPaint();
} else if (event.key === "Enter" || event.key === "Tab") {
slashPick(field, slash.shown[slash.active]);
} else if (event.key === "Escape") {
slashClose();
} else {
return;
}
event.preventDefault();
event.stopPropagation();
}
/**
* @param {HTMLElement} field a text field whose text reaches an agent; data-skills names the repository of its agent or card.
*/
function slashBind(field) {
if (slash.bound.has(field)) {
return;
}
slash.bound.add(field);
field.setAttribute("aria-autocomplete", "list");
field.addEventListener("input", () => slashShow(field));
field.addEventListener("keydown", (event) => slashKeys(event, field));
field.addEventListener("blur", () => window.setTimeout(() => slash.field === field && slashClose(), 0));
}
function slashWatch() {
const sweep = () => document.querySelectorAll(SLASH_FIELDS).forEach(slashBind);
sweep();
new MutationObserver(sweep).observe(document.body, {childList: true, subtree: true});
}
+5 -1
View File
@@ -141,12 +141,16 @@
const renamed = entry.now && entry.now !== entry.agent ? h("span", {title: `now: ${entry.now}`}, person(entry.agent)) : person(entry.agent);
const who = entry.agent ? [face(entry.agent, false), renamed] : entry.session ? h("strong", {title: entry.session}, entry.session.slice(0, 8)) : null;
const headline = entry.kind === "transcript" || entry.kind === "ask" || entry.kind === "operator" ? null : h("span", {class: "headline"}, Receipts.headline(entry));
return h("li", {class: `entry k-${entry.kind}${entry.waiting ? " waiting" : ""}${alarm ? " alarm" : ""}`, "data-ref": item ? keyOf(item) : null, "data-item": `message:${entry.ts}/${entry.id}`, "data-to": item && item.to ? item.to : null},
const blocked = (item && item.blocked) || (entry.kind === "operator" && entry.ref.blocked) || "";
return h("li", {class: `entry k-${entry.kind}${entry.waiting ? " waiting" : ""}${alarm ? " alarm" : ""}`, "data-ref": item ? keyOf(item) : null, "data-item": `message:${entry.ts}/${entry.id}`, "data-to": item && item.to ? item.to : null,
"data-blocked": blocked ? "" : null, title: blocked || null},
h("div", {class: "msg-meta"}, when(entry.ts), kindPill(entry), extras(entry)),
h("div", {},
h("div", {class: "route", "data-star-slot": ""}, who, entry.sub ? h("button", {type: "button", class: "linkish muted", on: {click: () => focusSub(entry.session, entry.sub)}}, `› Subagent ${entry.sub.slice(0, 12)}`) : null, entry.kind === "ask" ? h("strong", {}, entry.title) : null, headline),
entry.kind === "decision" && choice ? choice : [body(entry), choice],
entry.kind === "radio" ? readerRow(entry.ref) : null,
blocked ? h("p", {class: "item-blocked"}, icon("bi-slash-circle"), blocked) : null,
item && item.job ? consoleOf(item.job) : null,
item ? diffBlocks(item) : null,
item ? feedbackList(keyOf(item)) : null,
item ? h("div", {class: "line-actions"}, actionsFor(item)) : null));
+25 -4
View File
@@ -167,14 +167,33 @@
}}});
const stage = !inbox && view === "3d" ? h("div", {class: "stage"}) : null;
const body = inbox ? inboxScreen() : stage ? h("div", {class: "card stage-card tasks-body", "data-panel": "tasks/3d"}, layoutTools("tasks"), stage) : h("div", {class: "tasks-body", "data-panel": `tasks/${view}`});
taskView.dom = {chips, count, body, inbox, view, stage};
const slot = h("span", {class: "box-slot"});
taskView.dom = {chips, count, body, inbox, view, stage, slot};
taskView.sig = "";
taskView.plan = null;
taskView.bulk = null;
const bar = h("div", {class: "card controls task-toolbar", role: "toolbar", "aria-label": "Tasks"}, taskViewSwitch(inbox), search, count, inbox ? null : planTools(view), choiceMenu());
const bar = boxHead("Tasks", "task-toolbar", taskViewSwitch(inbox), search, count, inbox ? null : planTools(view), slot, choiceMenu());
return h("div", {class: "graph tasks"}, bar, chips, body);
}
const operatorItems = () => state.inbox.filter((item) => item.kind === "operator" && !item.settled);
/**
* @returns {HTMLElement|null} the open operator rows, greyed: the list and board only show them, Waits on Operator,
* Match and the Stream run, answer or deny them; null without any.
*/
function operatorSection() {
const items = operatorItems();
if (!items.length) {
return null;
}
const why = (item) => `Only shown here: Waits on Operator, Match and the Stream act on it.${item.blocked ? ` ${item.blocked}` : ""}`;
return h("section", {class: "operator-rows", "aria-label": "Waits on Operator"},
h("h3", {class: "group-title"}, "Waits on Operator", counter(items.length), h("span", {class: "spacer"}), btn("Open", "btn small ghost", () => chooseTaskFilter("operator"))),
h("ol", {class: "operator-list"}, items.map((item) => h("li", {"data-operator": item.id, "data-blocked": "", "aria-disabled": "true", title: why(item)},
pill(item.check === "decision" ? "Decision" : ITEM_LABELS.operator, item.check === "decision" ? KIND_TONES.decision : KIND_TONES.operator), h("code", {}, revealed(item.title)), h("span", {class: "muted"}, revealed(item.id))))));
}
function shownTasks() {
const q = taskView.q.trim().toLowerCase();
const [, , , test] = TASK_FILTERS.find(([id]) => id === taskView.filter);
@@ -191,7 +210,7 @@
stage3d("tasks", dom.stage);
}
const q = taskView.q.trim().toLowerCase();
const sig = JSON.stringify([state.tasks, state.jobs, state.task_edges, state.queue_line, Kanban.queueSig(state.queue_jobs), settings.estimation, settings.trend, taskView.filter, taskView.sort, taskView.descending, taskView.forecast, taskView.scope, q, waitingCount(), Math.floor(nowSeconds() / 60)]);
const sig = JSON.stringify([state.tasks, operatorItems().map((item) => [item.id, item.title, item.blocked]), state.jobs, state.task_edges, state.queue_line, Kanban.queueSig(state.queue_jobs), settings.estimation, settings.trend, taskView.filter, taskView.sort, taskView.descending, taskView.forecast, taskView.scope, q, waitingCount(), Math.floor(nowSeconds() / 60)]);
if (sig === taskView.sig) {
return;
}
@@ -224,5 +243,7 @@
gantt: ganttChart,
burn: (found) => burnChart(rows, found),
};
dom.body.replaceChildren(shown.length || dom.view === "burn" ? views[dom.view](shown) : emptyState("No task", "No entry matches this filter."));
dom.body.replaceChildren(shown.length || dom.view === "burn" ? views[dom.view](shown) : emptyState("No task", "No entry matches this filter."), ...(dom.view === "list" || dom.view === "board" ? [operatorSection()].filter(Boolean) : []));
const bar = dom.body.querySelector(".kanban-bar");
dom.slot.replaceChildren(...(bar ? [bar] : []));
}
+15 -1
View File
@@ -9,6 +9,7 @@ const Panels = (() => {
const ESCAPED = /_([0-9a-f]+)_/g;
const PANEL = "panel";
const SIZES = {panel: [6, 4], item: [4, 3]};
const ZOOM = {min: 50, max: 200, step: 10, base: 100};
const HOSTS = "[data-panel], [data-item]";
const TOO_LONG = "the id runs past 200 characters";
const XHTML = "http://www.w3.org/1999/xhtml";
@@ -172,6 +173,19 @@ const Panels = (() => {
const moveKey = (pins, key, step) => move(pins, indexOf(pins, key), step);
const resizeKey = (pins, key, w, h) => resize(pins, indexOf(pins, key), w, h);
/**
* @param zooms - the view store's home.zoom: pin key to percent; a pin without one shows at ZOOM.base.
* @param key - the tile's pin key.
* @param step - +1 zooms in, -1 out, 0 resets.
* @returns the new map: the tile at ZOOM.step percent more or less, held in ZOOM.min to ZOOM.max, left out at the base.
*/
function zoomBy(zooms, key, step) {
const now = Object.hasOwn(zooms, key) ? zooms[key] : ZOOM.base;
const next = step === 0 ? ZOOM.base : Math.min(ZOOM.max, Math.max(ZOOM.min, now + step * ZOOM.step));
const rest = Object.fromEntries(Object.entries(zooms).filter(([name]) => name !== key));
return next === ZOOM.base ? rest : {...rest, [key]: next};
}
function resizeBy(pins, key, dw, dh) {
const pin = pins[indexOf(pins, key)];
return pin ? resize(pins, indexOf(pins, key), pin.w + dw, pin.h + dh) : pins;
@@ -363,7 +377,7 @@ const Panels = (() => {
return {
MAX, SPAN, PANEL, ID, HOSTS, keyOf, token, raw, digest, valid, validLayout, clean, panel, item, capture, lookup, targetOf, has, add, remove, firstOfGroup,
place, move, resize, placeKey, moveKey, resizeKey, resizeBy, stretch, memory, store, decorate, keepFocus,
place, move, resize, placeKey, moveKey, resizeKey, resizeBy, stretch, ZOOM, zoomBy, memory, store, decorate, keepFocus,
};
})();
if (typeof module === "object" && module.exports) {
+38 -1
View File
@@ -258,7 +258,44 @@ const Resources = (() => {
return unit ? `${(value / unit[0]).toFixed(1)}${unit[1]}` : String(Math.round(value));
}
return {IDLE, SATURATED, CALM, BLOCKED, GAP, HOUR, COUNTS, ZONES, lines, hardware, segments, spans, waits, blocked, hung, asleep, unknown, stack, accumulate, burnup, compact};
/**
* @param moment - {day, time}: day 0 for Sunday to 6 for Saturday, time HH:MM, both local.
* @param now - epoch milliseconds.
* @returns the epoch milliseconds of the latest local moment at or before now; days step by the calendar, so a DST
* change keeps the wall clock time.
*/
function lastMoment(moment, now) {
const [hours, minutes] = moment.time.split(":").map(Number);
const at = new Date(now);
at.setHours(hours, minutes, 0, 0);
at.setDate(at.getDate() - ((at.getDay() - moment.day + 7) % 7));
if (at.getTime() > now) {
at.setDate(at.getDate() - 7);
}
return at.getTime();
}
function nextMoment(moment, now) {
const at = new Date(lastMoment(moment, now));
at.setDate(at.getDate() + 7);
return at.getTime();
}
/**
* @param entry - one account's usage from /api/accounts: {total, hours: [[t, tokens]]}, t in epoch seconds.
* @param reset - the account's weekly reset {day, time}, or null for the unassigned tokens.
* @param now - epoch milliseconds.
* @returns {since, today, total}: tokens of the hours from the last reset (null without a reset), from local
* midnight, and of all rows; an hour counts once its start is at or after the bound.
*/
function accountUsage(entry, reset, now) {
const midnight = new Date(now);
midnight.setHours(0, 0, 0, 0);
const from = (bound) => entry.hours.filter(([t]) => t * 1000 >= bound).reduce((sum, [, tokens]) => sum + tokens, 0);
return {since: reset ? from(lastMoment(reset, now)) : null, today: from(midnight.getTime()), total: entry.total};
}
return {IDLE, SATURATED, CALM, BLOCKED, GAP, HOUR, COUNTS, ZONES, lines, hardware, segments, spans, waits, blocked, hung, asleep, unknown, stack, accumulate, burnup, compact, lastMoment, nextMoment, accountUsage};
})();
if (typeof module === "object" && module.exports) {
module.exports = Resources;
+21
View File
@@ -0,0 +1,21 @@
const SettingsFiles = (() => {
const rank = (file) => (file.folder === false ? 2 : file.error ? 0 : 1);
/**
* @param files - /api/firewall files: path, folder and error each.
* @param showMissing - true lists the files whose folder is missing too.
* @returns {shown, missing}: shown the files to list, those with an error first, then by path, files without their folder
* last; missing the count of files without their folder.
*/
function listed(files, showMissing) {
const shown = files.filter((file) => showMissing || file.folder !== false);
shown.sort((a, b) => rank(a) - rank(b) || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
return {shown, missing: files.filter((file) => file.folder === false).length};
}
return {listed};
})();
if (typeof module === "object" && module.exports) {
module.exports = SettingsFiles;
}
+1
View File
@@ -26,4 +26,5 @@
.feedback-list { display: grid; gap: 4px; margin: var(--sp-1) 0 0; padding: 0; list-style: none; }
.feedback-list li { display: flex; align-items: baseline; gap: 6px; padding: 4px 8px; border-radius: 8px; background: var(--info-soft); font-size: var(--fs-sm); }
.feedback-list .text { flex: 1; min-width: 0; overflow-wrap: anywhere; white-space: pre-wrap; }
.feedback-list li.line-mark { align-items: center; background: var(--accent-soft); }
.feedback-float { position: fixed; z-index: 40; padding: 2px; border-radius: 10px; background: var(--glass-card); box-shadow: var(--shadow); }
+17 -5
View File
@@ -1,6 +1,17 @@
.stack-tight { display: grid; gap: 10px; min-width: 0; }
.fw-form { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 200px), 1fr)); gap: 10px; align-items: end; }
.fw-form label { display: grid; gap: 4px; min-width: 0; color: var(--muted); font-size: var(--fs-sm); }
.fw-form { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 200px), 1fr)); gap: 10px; align-items: start; }
.fw-form > button { align-self: end; justify-self: start; }
.fw-form label, .fw-chips-field { display: grid; gap: 4px; min-width: 0; color: var(--muted); font-size: var(--fs-sm); }
.fw-chips-field { grid-column: 1 / -1; }
.fw-chips-field > p { margin: 0; }
.check-chips { margin: 0; }
.fw-form label.check-chip { display: inline-flex; color: var(--text); font-size: var(--fs-sm); }
.check-chip input { margin: 0; accent-color: var(--accent); }
.check-chip .avatar { width: 20px; height: 20px; }
.check-chip:has(input:checked) { border-color: transparent; background: var(--accent-soft); color: var(--accent); }
.check-chip:has(input:focus-visible) { outline: 2px solid var(--accent); outline-offset: 2px; }
.fw-filters { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.fw-filters > .chips { margin-bottom: 0; }
.fw-form .field { width: 100%; min-width: 0; }
.fw-path { overflow-wrap: anywhere; }
.fw-patterns code { overflow-wrap: anywhere; }
@@ -20,9 +31,10 @@
.fw-diff .add { color: var(--ok); }
.fw-diff .del { color: var(--bad); }
.rule-row select.field { width: auto; max-width: 100%; min-width: 0; }
.controls > .segmented { justify-self: start; max-width: 100%; }
.controls > .segmented button { display: inline-flex; align-items: center; gap: 6px; }
.controls [role="tabpanel"][hidden], .apply-bar[hidden] { display: none; }
.fw-controls .box-head > .segmented { max-width: 100%; }
.fw-controls .box-head > .segmented button { display: inline-flex; align-items: center; gap: 6px; }
.fw-controls [role="tabpanel"][hidden], .apply-bar[hidden] { display: none; }
.fw-controls [role="tabpanel"] { grid-template-columns: minmax(0, 1fr); }
.tool-groups { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 280px), 1fr)); gap: 12px; align-items: start; }
.tool-group { display: grid; gap: 6px; min-width: 0; padding: 10px 12px; border: 1px solid var(--line); border-radius: 12px; background: var(--sunken); }
.tool-group h4 { margin: 0; }
+2
View File
@@ -11,12 +11,14 @@
.home-head { display: flex; flex: none; align-items: center; gap: 6px; padding: 4px 6px 4px 4px; border-bottom: 1px solid var(--line); }
.home-title { flex: 1; min-width: 0; margin: 0; overflow: hidden; font-size: var(--fs-sm); text-overflow: ellipsis; white-space: nowrap; }
.home-body { flex: 1; min-height: 0; padding: var(--sp-2); overflow: auto; }
.home-body > * { zoom: var(--zoom, 1); }
.home-body svg.chart { display: block; width: 100%; height: auto; max-height: 100%; }
.home-body .stage, .home-body .graph3d { height: 100%; min-height: 0; }
.home-grip { cursor: grab; touch-action: none; }
.home-open[hidden] { display: none; }
.home-slot { display: flex; flex: none; align-items: center; gap: 6px; min-width: 0; font-size: var(--fs-sm); }
.home-slot > .muted { white-space: nowrap; }
.home-slot.kanban-bar { flex: 0 1 auto; flex-wrap: nowrap; overflow-x: auto; }
.home-tile[data-w="1"] .home-head { gap: 2px; padding-inline: 2px; }
.home-tile[data-w="1"] .home-head .icon-only { min-width: 24px; padding-inline: 4px; }
.home-resize { position: absolute; right: 2px; bottom: 2px; z-index: 3; cursor: nwse-resize; touch-action: none; }
+7 -6
View File
@@ -6,12 +6,13 @@
.match-peeks { display: flex; flex-wrap: wrap; gap: var(--sp-1); min-width: 0; }
.match-peek { display: inline-flex; align-items: center; gap: 6px; max-width: 100%; min-width: 0; padding: 4px 10px 4px 4px; border: 1px solid var(--line); border-radius: 999px; background: var(--panel); color: inherit; font: inherit; font-size: var(--fs-sm); cursor: pointer; }
.match-peek[data-stale="true"] { border-color: var(--bad); }
.match-peek[data-blocked], .match-card.front[data-blocked] { filter: grayscale(1); opacity: 0.62; }
.match-blocked { display: flex; align-items: center; gap: 6px; margin: 0 0 var(--sp-2); color: var(--muted); font-size: var(--fs-sm); }
.match-peek .match-peek-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
.match-deck { position: relative; display: grid; grid-template-rows: minmax(0, 1fr); min-height: 0; padding-top: 14px; overflow-x: clip; }
.match-behind { position: absolute; inset: calc(14px - var(--depth) * 7px) calc(var(--depth) * 12px) auto; height: 40px; border: 1px solid var(--line); border-radius: 22px; background: var(--panel); opacity: calc(1 - var(--depth) * 0.3); transform: rotate(calc((var(--depth) * 2 - 3) * 1deg)); }
.match-card.front { position: relative; display: grid; grid-template-rows: auto minmax(min(50%, 12rem), 1fr); min-height: 0; padding: 0; overflow: hidden auto; border-radius: 22px; box-shadow: 0 14px 34px -16px rgb(0 0 0 / 0.45); }
.match-card.front::before { content: ""; position: absolute; inset: 0 0 auto; z-index: 1; height: 6px; background: linear-gradient(90deg, hsl(var(--card-hue, 210) 75% 58%), hsl(var(--card-hue-2, 280) 75% 58%)); }
.match-card[data-stale="true"]::before { background: var(--bad); }
.match-card.front { --bar: linear-gradient(90deg, hsl(var(--card-hue, 210) 75% 58%), hsl(var(--card-hue-2, 280) 75% 58%)); position: relative; display: grid; grid-template-rows: auto minmax(min(50%, 12rem), 1fr); min-height: 0; padding: 0; overflow: hidden auto; border-top-width: 0; border-radius: 22px; background: var(--bar) top / 100% 6px no-repeat, var(--glass-card); box-shadow: 0 14px 34px -16px rgb(0 0 0 / 0.45); }
.match-card[data-stale="true"] { --bar: linear-gradient(var(--bad), var(--bad)); }
.match-card.front[data-fresh="true"] { animation: match-in 0.32s cubic-bezier(0.34, 1.56, 0.64, 1); }
.match-card.front[data-fresh="true"] .match-who .avatar { animation: match-pop 0.5s cubic-bezier(0.34, 1.56, 0.64, 1); }
.match-card.front[data-fly="accept"] { animation: match-fly-right 0.26s ease-in forwards; }
@@ -29,7 +30,7 @@
.match-head { position: relative; isolation: isolate; display: grid; justify-items: center; gap: 6px; padding: var(--sp-3); border-bottom: 1px solid var(--line); text-align: center;
--ink: hsl(var(--card-hue, 210) 55% 48% / 0.16);
background: radial-gradient(120% 90% at 0% 0%, hsl(var(--card-hue, 210) 85% 62% / 0.3), transparent 60%), radial-gradient(110% 90% at 100% 10%, hsl(var(--card-hue-2, 280) 85% 62% / 0.26), transparent 62%), linear-gradient(180deg, hsl(var(--card-hue, 210) 80% 60% / 0.1), transparent 85%); }
.match-head::before { content: ""; position: absolute; inset: 0; z-index: -1; pointer-events: none; mask-image: linear-gradient(180deg, #000 15%, transparent 95%); }
.match-head::before { content: ""; position: absolute; inset: 0; z-index: -1; pointer-events: none; mask-image: linear-gradient(180deg, transparent 6px, #000 6px, #000 15%, transparent 95%); }
.match-card[data-pattern="dots"] .match-head::before { background: radial-gradient(var(--ink) 1.2px, transparent 1.7px) 0 0 / 14px 14px; }
.match-card[data-pattern="stripes"] .match-head::before { background: repeating-linear-gradient(135deg, var(--ink) 0 2px, transparent 2px 12px); }
.match-card[data-pattern="waves"] .match-head::before { background: radial-gradient(circle at 50% 100%, transparent 7px, var(--ink) 7.5px 9px, transparent 9.5px) 0 0 / 24px 12px; }
@@ -63,8 +64,8 @@
.match-file .diff-scroll { max-height: none; overflow: auto hidden; }
.match-file .diff-head .note { display: inline-flex; align-items: center; gap: 4px; color: var(--warn); font-size: var(--fs-xs); }
.match-marks { min-width: 20px; padding: 0 6px; border-radius: 999px; background: var(--accent); color: var(--on-accent); font-size: var(--fs-xs); text-align: center; }
.match-file tr.marked td.code { box-shadow: inset 3px 0 0 var(--accent); }
.match-file tr.match-mark td, .match-file tr.match-comment td { padding: 4px 10px; background: var(--info-soft); font-family: var(--sans); white-space: normal; }
table.diff tr.marked td.code { box-shadow: inset 3px 0 0 var(--accent); }
table.diff tr.match-mark td, table.diff tr.match-comment td { padding: 4px 10px; background: var(--info-soft); font-family: var(--sans); white-space: normal; }
.match-mark-text { margin-left: 6px; }
.match-comment-box { display: grid; gap: 6px; }
.match-comment-box .actions { display: flex; justify-content: flex-end; gap: 6px; }
@@ -6,6 +6,24 @@ body.fit .graph.resources > .res-panels { flex: 1; }
.res-title { display: inline-flex; color: var(--text); font-size: var(--fs-md); }
.res-legend { display: flex; flex: 1; min-width: 0; font-variant-numeric: tabular-nums; }
.res-switch[aria-pressed="true"] { background: var(--accent-soft); color: var(--accent); }
.res-panels-menu { position: relative; }
.res-panels-menu > summary { padding: 4px 10px; }
.res-panels-menu .menu-box { gap: 2px; min-width: 11rem; padding: 6px; }
.res-pick { display: flex; align-items: center; gap: 8px; padding: 4px 6px; border-radius: 8px; cursor: pointer; }
.res-pick:has(input:disabled) { cursor: not-allowed; opacity: 0.7; }
.res-accounts { flex: 0 1 auto; min-height: 0; overflow: visible; }
.acc-title { color: var(--text); font-size: var(--fs-sm); font-weight: 620; }
.acc-scroll { max-width: 100%; overflow-x: auto; }
.acc-table { width: 100%; border-collapse: collapse; font-size: var(--fs-sm); font-variant-numeric: tabular-nums; }
.acc-table th, .acc-table td { padding: 4px 8px; border-bottom: 1px solid var(--line); text-align: left; white-space: nowrap; }
.acc-table th { color: var(--muted); font-size: var(--fs-xs); font-weight: 650; }
.acc-table tr[data-active] td { background: var(--accent-soft); }
.acc-table .pill { margin-left: 6px; }
.acc-unassigned td { color: var(--muted); }
.acc-form { display: grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); gap: var(--sp-2) var(--sp-3); }
.acc-field { display: grid; gap: 4px; font-size: var(--fs-sm); }
.acc-pair { display: flex; gap: 6px; }
.acc-pair > * { flex: 1; min-width: 0; }
.res-plot { position: relative; flex: 1; min-height: 0; }
.res-plot > svg { position: absolute; inset: 0; width: 100%; height: 100%; }
svg .band.idle { fill: var(--ok-soft); }
+7
View File
@@ -97,3 +97,10 @@ svg .forecast-label { fill: var(--ok); font-size: var(--fs-2xs); font-weight: 65
.burn-forecast { display: inline-flex; align-items: center; gap: 6px; }
svg .node.a-worktree.open circle { stroke: var(--warn); stroke-width: 2.6; stroke-dasharray: 3 2; }
svg .edge.flow { stroke-dasharray: 2 5; }
.inbox-list > li[data-blocked], .feed > li[data-blocked], .operator-list > li { filter: grayscale(1); opacity: 0.72; }
.item-blocked { display: flex; align-items: flex-start; gap: 6px; margin: 4px 0 0; color: var(--muted); font-size: var(--fs-sm); }
.operator-rows { display: grid; gap: 6px; margin-top: var(--sp-3); }
.operator-rows > h3 { display: flex; align-items: center; gap: 8px; margin: 0; }
.operator-list { display: grid; gap: 4px; margin: 0; padding: 0; list-style: none; }
.operator-list > li { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; padding: 6px 10px; border: 1px solid var(--line); border-radius: 10px; cursor: not-allowed; }
.operator-list code { min-width: 0; overflow-wrap: anywhere; }
+29 -16
View File
@@ -73,19 +73,28 @@ body.fit .spot-host { flex: none; }
.radio-card-head { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); min-width: 0; min-height: 30px; }
.radio-card-head .group-title { margin-inline-end: var(--sp-2); }
.composer { display: grid; gap: var(--sp-2); min-width: 0; }
.composer-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 180px), 1fr)); gap: var(--sp-2) var(--sp-3); }
.composer-grid label { display: grid; grid-template-columns: 4.5em minmax(0, 1fr); align-items: center; gap: var(--sp-2); min-width: 0; color: var(--muted); font-size: var(--fs-sm); }
.composer-grid .field { width: 100%; min-width: 0; }
.composer textarea { min-height: 64px; }
.radio-card.radio-speak { border-radius: 14px; }
.composer-grid { display: flex; min-width: 0; overflow: hidden; border: 1px solid var(--line); border-radius: 10px; background: var(--glass-card); }
.composer-grid label { display: flex; flex: 1 1 0; align-items: center; gap: 6px; min-width: 0; padding-inline-start: 12px; color: var(--muted); font-size: var(--fs-sm); }
.composer-grid label + label { border-inline-start: 1px solid var(--line); }
.composer-grid .field { flex: 1 1 auto; width: 100%; min-width: 0; border: 0; border-radius: 0; background: transparent; }
.composer textarea { min-height: 64px; border-radius: 10px; }
.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 .actions { flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 0; }
.composer .mayday-toggle { border-radius: 999px; }
.composer .mayday-toggle[aria-pressed="true"] { background: var(--bad); color: #fff; }
.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-split > .ptt { border-start-start-radius: 999px; border-end-start-radius: 999px; 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; border-start-end-radius: 999px; border-end-end-radius: 999px; list-style: none; }
.ptt-menu > summary.ptt-more::-webkit-details-marker { display: none; }
.radio-cancel[hidden] { display: none; }
.mayday-confirm { display: flex; flex-wrap: wrap; align-items: center; gap: 6px var(--sp-2); padding: 6px 10px; border-radius: 10px; background: color-mix(in srgb, var(--bad) 14%, transparent); }
.mayday-confirm > p { flex: 1 1 14em; margin: 0; font-size: var(--fs-sm); }
.mayday-confirm > .actions { margin: 0 0 0 auto; }
.composer-status { min-width: 0; overflow-wrap: anywhere; }
.slash-list { position: fixed; z-index: 80; display: grid; width: min(28rem, 100vw - 16px); max-height: 18rem; overflow: auto; padding: 4px; border: 1px solid var(--line); border-radius: 10px; background: var(--glass-card); box-shadow: var(--shadow); }
.slash-option { display: grid; gap: 2px; padding: 6px 8px; border-radius: 8px; cursor: pointer; }
.slash-option[aria-selected="true"] { background: color-mix(in srgb, var(--accent) 18%, transparent); }
.slash-option > .muted { overflow: hidden; font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; }
.voice-note { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); }
.voice-replay { max-width: 100%; height: 34px; }
.voice-note .voice-play { display: none; }
@@ -139,7 +148,8 @@ body.fit .spot-host { flex: none; }
.chip-select { min-width: 0; }
.chip-select .field { max-width: 160px; padding: 3px 8px; border-radius: 999px; font-size: var(--fs-sm); }
.chip-select[data-active="true"] .field { border-color: transparent; background: var(--accent-soft); color: var(--accent); }
.radio-logbox input[type="search"] { flex: 1 1 0; min-width: 5rem; padding: 4px 10px; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--panel); }
.radio-logbox > .radio-card-head > .mic-line { flex: 1 1 0; width: auto; min-width: 5rem; }
.radio-logbox input[type="search"] { padding: 4px 10px; }
.radio-logbox { flex: 1 1 auto; min-height: 0; container: history / inline-size; }
.radio-log { display: grid; flex: 1 1 0; align-content: start; gap: 4px; height: 0; min-height: clamp(6.5rem, 30vh - 7rem, 24rem); margin: 0; padding: 0 2px 0 0; overflow: hidden auto; overscroll-behavior: contain; list-style: none; scrollbar-width: thin; scroll-margin-top: var(--head); }
.radio-log, .radio-device, .radio-speak, .shell > main { scrollbar-color: color-mix(in srgb, var(--muted) 45%, transparent) transparent; }
@@ -211,10 +221,11 @@ body.fit .spot-host { flex: none; }
.radio-spot .radio-column { grid-area: 2 / 2; gap: var(--sp-2); }
.radio-spot .radio-speak { flex: none; }
.radio-spot .radio-log { min-height: 4.25rem; }
.radio-spot .composer { grid-template-columns: auto minmax(0, 1fr); }
.radio-spot .composer { grid-template-columns: minmax(0, 1fr) fit-content(50%); }
.radio-spot .composer > * { grid-column: 1 / -1; }
.radio-spot .composer > .voice-note:not([hidden]) { grid-column: 1; }
.radio-spot .composer > .voice-note:not([hidden]) + .actions { grid-column: 2; }
.radio-spot .composer > .mic-area { grid-area: 2 / 1 / 4 / 2; }
.radio-spot .composer > .voice-note:not([hidden]) { grid-area: 2 / 2; align-self: start; }
.radio-spot .composer > .actions { grid-area: 3 / 2; align-self: end; }
.radio-spot .radio-face { grid-template-columns: auto minmax(0, max-content) minmax(0, 1fr) auto; }
.radio-spot .radio-display { display: grid; grid-template-columns: subgrid; }
.radio-spot .radio-caption { z-index: 1; grid-area: 1 / 2 / 2 / 4; gap: 4px; min-height: 0; padding: 0 4px; background-color: var(--sunken); background-image: linear-gradient(var(--ok-soft), var(--ok-soft)); }
@@ -225,7 +236,7 @@ body.fit .spot-host { flex: none; }
}
@media (min-width: 80rem) and (45rem <= height <= 66rem), (min-width: 61rem) and (46.5rem <= height <= 66rem), (min-width: 48rem) and (61rem <= height <= 66rem), (min-width: 48rem) and (width < 56rem) and (min-height: 61rem) {
body.fit .shell:has(> .spot-host > .radio-spot:not([hidden])) { padding-bottom: var(--sp-4); }
body.fit .spot-host:has(> .radio-spot:not([hidden])) + main { padding-block: var(--sp-3); }
body.fit .spot-host:has(> .radio-spot:not([hidden])) + main { --main-top: var(--sp-3); padding-block: var(--sp-3); }
.radio-spot:not([hidden]) { gap: 4px var(--sp-3); margin-bottom: 4px; padding-block: 4px; }
.radio-spot .radio-column { gap: 4px; }
.radio-spot .radio-card { gap: 4px; padding: 4px var(--sp-2); }
@@ -250,7 +261,9 @@ body.fit .spot-host { flex: none; }
.radio-spot .radio-speak .composer-grid { order: 1; flex: 1 1 0; }
.radio-spot .radio-speak .composer-grid .field { padding-block: 2px; }
.radio-spot .radio-speak .star { margin-inline-start: 0; }
.radio-spot .radio-speak textarea { order: 4; flex: 1 1 7rem; height: 32px; min-height: 32px; }
.radio-spot .radio-speak .mic-area { order: 4; flex: 1 1 7rem; }
.radio-spot .radio-speak .mic-area > textarea { height: 32px; min-height: 32px; }
.radio-spot .radio-speak .mic-foot { min-height: 0; padding-block: 0; }
.radio-spot .radio-speak .composer-hint { display: none; }
.radio-spot .radio-speak .actions > * { order: 5; }
.radio-spot .radio-speak .composer-status { flex: 1 1 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -272,4 +285,4 @@ body.fit .spot-host { flex: none; }
.ctx-item:is(:hover, :focus) { background: var(--accent-soft); color: var(--accent); outline: none; }
.ctx-item .ctx-label { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.ctx-item .muted { flex: 0 1 auto; max-width: 45%; overflow: hidden; font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; }
.controls > .toolbar { justify-content: flex-end; margin-inline-start: auto; }
.box-head > .toolbar { justify-content: flex-end; margin-inline-start: auto; }