feat(orchestrator): resources view with legend chips and a server-side view store (007)
The Resources tab draws one hardware chart and one tokens chart with an accumulated switch, plus a combined overlay of hardware, tokens and the burnup, every series switched by a legend chip and all shown by default. The hub keeps every toggle in a validated view store: PATCH /api/view takes a set and the expected old values and answers 409 on a stale expectation, update() re-runs a change on the stored value, list paths change only through update(), and a page shown again from the back-forward cache fetches the stored view anew. 🎯 Fix: 93 % 💥 Break: 4 % 💸 Cost: 100 % ⏱️ Time: 100 % 🛡️ Security: 100 % 🏆 Score: 89 🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3418738993
commit
c128fa4000
15 files changed
+1794
-102
No files matched your search
@@ -45,6 +45,7 @@ OFFICE_STATE = re.compile(r"/api/offices/([0-9a-f]{16})")
|
||||
TASKS_ROUTE = "/api/tasks"
|
||||
GATES_ROUTE = "/api/gates"
|
||||
TOKEN_ROUTE = "/api/cleanup/token"
|
||||
VIEW_ROUTE = "/api/view"
|
||||
VENDOR_ROUTE = re.compile(r"/vendor/([a-z0-9.-]{1,64})")
|
||||
SCRIPT_TYPE = "text/javascript; charset=utf-8"
|
||||
FONT_TYPE = "font/woff2"
|
||||
@@ -118,6 +119,8 @@ class Handler(Exchange):
|
||||
self.answer(hub.repositories, HTTPStatus.OK)
|
||||
elif path == "/api/resources":
|
||||
self.answer(lambda: sampled(hub.kept / RESOURCES, hub.span(self.query(), time.time())), HTTPStatus.OK)
|
||||
elif path == VIEW_ROUTE:
|
||||
self.answer(hub.view_store.get, HTTPStatus.OK)
|
||||
elif path == "/api/subagents":
|
||||
self.answer(lambda: hub.subagents(self.query()), HTTPStatus.OK)
|
||||
elif path == "/api/runner/jobs":
|
||||
@@ -263,6 +266,21 @@ class Handler(Exchange):
|
||||
if receive is not None:
|
||||
receive(self.rfile.read(length))
|
||||
|
||||
def do_PATCH(self) -> None:
|
||||
path = urlsplit(self.path).path
|
||||
host = self.host()
|
||||
if host is None:
|
||||
self.send_text(HTTPStatus.FORBIDDEN, "forbidden host")
|
||||
elif path != VIEW_ROUTE:
|
||||
self.send_text(HTTPStatus.NOT_FOUND, "not found")
|
||||
elif not self.guarded(host):
|
||||
self.send_text(HTTPStatus.FORBIDDEN, "forbidden: same-origin PATCH with the X-Kvb-Orchestrator header only")
|
||||
else:
|
||||
length = self.body_length(BODY_LIMIT)
|
||||
if length is not None:
|
||||
body = self.rfile.read(length)
|
||||
self.answer(lambda: self.server.hub.view_store.patch(body), HTTPStatus.OK)
|
||||
|
||||
def index(self) -> None:
|
||||
nonce = secrets.token_urlsafe(18)
|
||||
page, csp = self.server.hub.render(nonce)
|
||||
|
||||
@@ -40,6 +40,7 @@ from .timeline import Timeline
|
||||
from .transcripts import Transcripts
|
||||
from .tree import TREE_HEARTBEAT, Tree
|
||||
from .view import View
|
||||
from .viewstore import ViewStore
|
||||
from .voicenotes import VoiceNotes
|
||||
|
||||
|
||||
@@ -103,6 +104,7 @@ class Hub(Mcp, Reviewing, Asking, Messaging, Choosing, Approving, Denying, Reque
|
||||
touched: Touched
|
||||
voice_notes: VoiceNotes
|
||||
replay: Path
|
||||
view_store: ViewStore
|
||||
|
||||
def hosts(self) -> tuple[str, str]:
|
||||
return f"127.0.0.1:{self.public_port}", f"localhost:{self.public_port}"
|
||||
@@ -127,6 +129,7 @@ def open_hub(council: Path, pages: Path, public_port: int, state: Path, host_sta
|
||||
speech=speech,
|
||||
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"),
|
||||
rules=Ledger(state / "rules.json"),
|
||||
jobs=Ledger(state / "jobs.json"),
|
||||
marks=Marks(state / "marks.json"),
|
||||
|
||||
@@ -210,5 +210,5 @@ class View:
|
||||
def render(self, nonce: str) -> tuple[str, str]:
|
||||
now = time.time()
|
||||
state = self.state(now - RADIO_WINDOW, now, now, 0)
|
||||
page = self.templates.get_template("index.html.j2").render(nonce=nonce, state=state, icons=self.icons)
|
||||
page = self.templates.get_template("index.html.j2").render(nonce=nonce, state=state, view=self.view_store.get(), icons=self.icons)
|
||||
return page, INDEX_CSP.format(nonce, " ".join(["'self'", *state["media"]]))
|
||||
@@ -0,0 +1,168 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
import re
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from .errors import Conflict, ToolError
|
||||
from .fields import decode
|
||||
from .records import read_json, write_atomic
|
||||
from .settings import flag, section
|
||||
|
||||
VIEW_LIMIT = 64 << 10
|
||||
CHANGE_LIMIT = 2 * VIEW_LIMIT + (1 << 10)
|
||||
VIEW = {
|
||||
"resources": {"hidden": [], "tokens": "interval", "combined": False, "combinedHidden": []},
|
||||
"burn": {"overlays": []},
|
||||
"home": {"pins": []},
|
||||
}
|
||||
VIEW_PATH = re.compile(r"[A-Za-z]{1,32}(?:\.[A-Za-z]{1,32})?")
|
||||
SERIES_ID = re.compile(r"[A-Za-z0-9:_./-]{1,200}")
|
||||
PIN_KIND = re.compile(r"[A-Za-z0-9:_./-]{1,32}")
|
||||
IDS_LIMIT = 500
|
||||
TOKEN_MODES = ("interval", "accumulated")
|
||||
OVERLAYS = ("fix", "break", "tokens", "velocity", "security", "score")
|
||||
PINS_LIMIT = 64
|
||||
SPAN = (1, 12)
|
||||
|
||||
|
||||
def series_ids(value: object, name: str) -> list[str]:
|
||||
if not isinstance(value, list) or len(value) > IDS_LIMIT or not all(isinstance(item, str) and SERIES_ID.fullmatch(item) for item in value):
|
||||
raise ToolError(f"{name} must list at most {IDS_LIMIT} ids of 1 to 200 characters from A-Z, a-z, 0-9 and :_./-")
|
||||
if len(set(value)) != len(value):
|
||||
raise ToolError(f"{name} must not repeat an id")
|
||||
return list(value)
|
||||
|
||||
|
||||
def span(value: object, name: str) -> int:
|
||||
low, high = SPAN
|
||||
if isinstance(value, bool) or not isinstance(value, int) or not low <= value <= high:
|
||||
raise ToolError(f"{name} must be a whole number from {low} to {high}")
|
||||
return value
|
||||
|
||||
|
||||
def pin_entry(raw: object, index: int) -> dict:
|
||||
name = f"home.pins[{index}]"
|
||||
entry = section(raw, name, ("kind", "id", "w", "h"))
|
||||
if not isinstance(entry["kind"], str) or not PIN_KIND.fullmatch(entry["kind"]):
|
||||
raise ToolError(f"{name}.kind must be 1 to 32 characters from A-Z, a-z, 0-9 and :_./-")
|
||||
if not isinstance(entry["id"], str) or not SERIES_ID.fullmatch(entry["id"]):
|
||||
raise ToolError(f"{name}.id must be 1 to 200 characters from A-Z, a-z, 0-9 and :_./-")
|
||||
return {"kind": entry["kind"], "id": entry["id"], "w": span(entry["w"], f"{name}.w"), "h": span(entry["h"], f"{name}.h")}
|
||||
|
||||
|
||||
def pins(value: object) -> list[dict]:
|
||||
if not isinstance(value, list) or len(value) > PINS_LIMIT:
|
||||
raise ToolError(f"home.pins must be a list of at most {PINS_LIMIT} pins")
|
||||
found = [pin_entry(raw, index) for index, raw in enumerate(value)]
|
||||
if len({(pin["kind"], pin["id"]) for pin in found}) != len(found):
|
||||
raise ToolError("home.pins must not pin the same kind and id twice")
|
||||
return found
|
||||
|
||||
|
||||
def valid_view(raw: object) -> dict:
|
||||
"""Args:
|
||||
raw: the whole view document as the page sent it.
|
||||
|
||||
Returns:
|
||||
The document with every key of VIEW and nothing else; any other
|
||||
key, a missing one or a malformed value raises ToolError.
|
||||
"""
|
||||
data = section(raw, "view", tuple(VIEW))
|
||||
resources = section(data["resources"], "resources", tuple(VIEW["resources"]))
|
||||
burn = section(data["burn"], "burn", tuple(VIEW["burn"]))
|
||||
home = section(data["home"], "home", tuple(VIEW["home"]))
|
||||
if not isinstance(resources["tokens"], str) or resources["tokens"] not in TOKEN_MODES:
|
||||
raise ToolError(f"resources.tokens must be one of {', '.join(TOKEN_MODES)}")
|
||||
overlays = burn["overlays"]
|
||||
if not isinstance(overlays, list) or not all(isinstance(item, str) and item in OVERLAYS for item in overlays) or len(set(overlays)) != len(overlays):
|
||||
raise ToolError(f"burn.overlays must list distinct metrics of {', '.join(OVERLAYS)}")
|
||||
return {
|
||||
"resources": {
|
||||
"hidden": series_ids(resources["hidden"], "resources.hidden"),
|
||||
"tokens": resources["tokens"],
|
||||
"combined": flag(resources["combined"], "resources.combined"),
|
||||
"combinedHidden": series_ids(resources["combinedHidden"], "resources.combinedHidden"),
|
||||
},
|
||||
"burn": {"overlays": list(overlays)},
|
||||
"home": {"pins": pins(home["pins"])},
|
||||
}
|
||||
|
||||
|
||||
def slot(view: dict, path: object) -> tuple[dict, str]:
|
||||
"""Args:
|
||||
view: a document of the shape of VIEW.
|
||||
path: a section or section.key of VIEW, such as resources.hidden.
|
||||
|
||||
Returns:
|
||||
The object holding the path's value and its key there.
|
||||
"""
|
||||
if not isinstance(path, str) or not VIEW_PATH.fullmatch(path):
|
||||
raise ToolError("a view path must be a section or section.key, such as resources.hidden")
|
||||
keys = path.split(".")
|
||||
shape, node = VIEW, view
|
||||
for key in keys[:-1]:
|
||||
if key not in shape:
|
||||
raise ToolError(f"unknown view path {path}")
|
||||
shape, node = shape[key], node[key]
|
||||
if keys[-1] not in shape:
|
||||
raise ToolError(f"unknown view path {path}")
|
||||
return node, keys[-1]
|
||||
|
||||
|
||||
def value_at(view: dict, path: object) -> object:
|
||||
node, key = slot(view, path)
|
||||
return node[key]
|
||||
|
||||
|
||||
class ViewStore:
|
||||
def __init__(self, file: Path) -> None:
|
||||
self.file = file
|
||||
self.lock = threading.Lock()
|
||||
try:
|
||||
self.current = valid_view(read_json(file))
|
||||
except ToolError:
|
||||
self.current = copy.deepcopy(VIEW)
|
||||
|
||||
def get(self) -> dict:
|
||||
with self.lock:
|
||||
return copy.deepcopy(self.current)
|
||||
|
||||
def patch(self, body: bytes) -> dict:
|
||||
"""Args:
|
||||
body: {"set": {path: value}, "expect": {path: value}} as JSON, at
|
||||
most CHANGE_LIMIT bytes, so that a document at VIEW_LIMIT can
|
||||
still send both values of a path; expect names the same paths
|
||||
with the values the page last saw stored there, and every
|
||||
other path keeps its stored value.
|
||||
|
||||
Returns:
|
||||
The whole stored document. A path whose stored value differs
|
||||
from its expected one raises Conflict with {"view", "paths"}: the
|
||||
stored document and those paths. A refused change, or one that
|
||||
would grow the document past VIEW_LIMIT bytes, leaves the file
|
||||
and the served document as they were.
|
||||
"""
|
||||
if len(body) > CHANGE_LIMIT:
|
||||
raise ToolError(f"a view change must not exceed {CHANGE_LIMIT} bytes")
|
||||
change = section(decode(body), "change", ("set", "expect"))
|
||||
values, expected = change["set"], change["expect"]
|
||||
if not isinstance(values, dict) or not values or not isinstance(expected, dict) or set(expected) != set(values):
|
||||
raise ToolError("set must map at least one view path to its new value and expect the same paths to their stored values")
|
||||
with self.lock:
|
||||
moved = [path for path in values if value_at(self.current, path) != expected[path]]
|
||||
if moved:
|
||||
raise Conflict({"view": copy.deepcopy(self.current), "paths": moved})
|
||||
draft = copy.deepcopy(self.current)
|
||||
for path, value in values.items():
|
||||
node, key = slot(draft, path)
|
||||
node[key] = value
|
||||
view = valid_view(draft)
|
||||
data = json.dumps(view, separators=(",", ":")).encode("utf-8")
|
||||
if len(data) > VIEW_LIMIT:
|
||||
raise ToolError(f"the view document must not exceed {VIEW_LIMIT} bytes")
|
||||
write_atomic(self.file, data)
|
||||
self.current = view
|
||||
return copy.deepcopy(view)
|
||||
@@ -408,6 +408,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
||||
|
||||
{% include "style-resources.css" %}
|
||||
|
||||
{% include "style-legend-chips.css" %}
|
||||
|
||||
{% include "style-inbox.css" %}
|
||||
|
||||
{% include "style-ui.css" %}
|
||||
@@ -455,6 +457,7 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
||||
<div class="sky-panel" id="sky-panel" role="group" aria-label="View of the sky" hidden></div>
|
||||
<div class="bubbles" id="bubbles" aria-hidden="true" hidden><div class="bubble-bar"></div></div>
|
||||
<script nonce="{{ nonce }}" id="state" type="application/json">{{ state | tojson }}</script>
|
||||
<script nonce="{{ nonce }}" id="view" type="application/json">{{ view | tojson }}</script>
|
||||
<script nonce="{{ nonce }}">
|
||||
{% include "ambience.js" %}
|
||||
</script>
|
||||
@@ -465,6 +468,10 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
||||
|
||||
{% include "diffs.js" %}
|
||||
|
||||
{% include "view-store.js" %}
|
||||
|
||||
{% include "legend-chips.js" %}
|
||||
|
||||
{% include "resources.js" %}
|
||||
|
||||
{% include "nav.js" %}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
const LegendChips = (() => {
|
||||
"use strict";
|
||||
const KEEP = 100;
|
||||
const MODES = {
|
||||
hidden: {pressed: (list, id) => !list.includes(id), words: ["shown, press to hide", "hidden, press to show"], group: "Series: press a chip to hide or show it"},
|
||||
shown: {pressed: (list, id) => list.includes(id), words: ["on, press to switch it off", "off, press to switch it on"], group: "Overlays: press a chip to switch it on or off"},
|
||||
};
|
||||
|
||||
/**
|
||||
* @param list - the series ids the view-store key holds.
|
||||
* @param id - the series to place.
|
||||
* @param wanted - true when the list must hold id, false when it must not.
|
||||
* @returns the list holding id once, appended when missing, or the list without id.
|
||||
*/
|
||||
function placed(list, id, wanted) {
|
||||
if (!wanted) {
|
||||
return list.filter((item) => item !== id);
|
||||
}
|
||||
return list.includes(id) ? list : [...list, id];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list - the hidden series ids, oldest first.
|
||||
* @param present - the ids of the series whose chips the page shows now for the same view-store key.
|
||||
* @returns the list with its oldest ids of series no longer shown dropped until at most KEEP ids remain, or
|
||||
* until only shown ones are left.
|
||||
*/
|
||||
function pruned(list, present) {
|
||||
let surplus = list.length - KEEP;
|
||||
return list.filter((item) => present.has(item) || surplus-- <= 0);
|
||||
}
|
||||
|
||||
function shownChips(path) {
|
||||
return new Set([...document.querySelectorAll(".legend-chip")].filter((node) => node.getAttribute("data-path") === path).map((node) => node.getAttribute("data-chip")));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param series - [{id, label, tone}]: one chip per series; label is its text, tone the classes that colour its swatch.
|
||||
* @param path - the section.key of the view store that holds a list of series ids.
|
||||
* @param mode - "hidden" when the list names the series switched off (all on by default; old ids of series gone
|
||||
* from the page are pruned beyond KEEP), "shown" when it names the series switched on (all off by default).
|
||||
* @returns a group with one toggle button per series, pressed while the series is on; a press fixes at once
|
||||
* whether the list must hold its id, the opposite of what this page shows, and applies that through
|
||||
* ViewStore.update, so a retry on a list another browser changed keeps that choice; the caller redraws from
|
||||
* ViewStore.on.
|
||||
*/
|
||||
function render(series, path, mode) {
|
||||
if (!Object.hasOwn(MODES, mode)) {
|
||||
throw new Error(`a legend chip mode must be hidden or shown, not ${mode}`);
|
||||
}
|
||||
const {pressed, words, group: label} = MODES[mode];
|
||||
const hint = (text, on) => `${text}: ${words[on ? 0 : 1]}`;
|
||||
const listed = ViewStore.get(path);
|
||||
const group = document.createElement("div");
|
||||
group.className = "legend-chips";
|
||||
group.setAttribute("role", "group");
|
||||
group.setAttribute("aria-label", label);
|
||||
for (const entry of series) {
|
||||
const on = pressed(listed, entry.id);
|
||||
const chip = document.createElement("button");
|
||||
chip.type = "button";
|
||||
chip.className = `legend-chip ${entry.tone}`.trim();
|
||||
chip.setAttribute("data-chip", entry.id);
|
||||
chip.setAttribute("data-path", path);
|
||||
chip.setAttribute("aria-pressed", String(on));
|
||||
chip.setAttribute("title", hint(entry.label, on));
|
||||
chip.textContent = entry.label;
|
||||
chip.addEventListener("click", () => {
|
||||
const present = shownChips(path);
|
||||
const wanted = !ViewStore.get(path).includes(entry.id);
|
||||
ViewStore.update(path, (list) => (mode === "hidden" ? pruned(placed(list, entry.id, wanted), present) : placed(list, entry.id, wanted)));
|
||||
const now = pressed(ViewStore.get(path), entry.id);
|
||||
chip.setAttribute("aria-pressed", String(now));
|
||||
chip.setAttribute("title", hint(entry.label, now));
|
||||
});
|
||||
group.append(chip);
|
||||
}
|
||||
return group;
|
||||
}
|
||||
|
||||
return {KEEP, render, placed, pruned};
|
||||
})();
|
||||
if (typeof module === "object" && module.exports) {
|
||||
module.exports = LegendChips;
|
||||
}
|
||||
@@ -1,29 +1,41 @@
|
||||
const RESOURCE = {left: 46, right: 10, top: 6, bottom: 6, axis: 18, poll: 5000, stale: 60, tones: 6, hour: 3600, narrow: 600};
|
||||
const RESOURCE_PANELS = [["disks", "bi-hdd-stack", "Disks"], ["host", "bi-cpu", "CPU, RAM and swap"], ["gpu", "bi-gpu-card", "GPU and VRAM"], ["tokens", "bi-coin", "Tokens per agent"]];
|
||||
const RESOURCE = {left: 46, right: 10, wide: 50, top: 6, bottom: 6, axis: 18, poll: 5000, stale: 60, tones: 6, narrow: 600};
|
||||
const RESOURCE_PANELS = [["hardware", "bi-cpu", "Hardware: disks, CPU, RAM, swap, GPU and VRAM"], ["tokens", "bi-coin", "Tokens per agent"], ["combined", "bi-layers", "Hardware, tokens and burnup"]];
|
||||
const RESOURCE_ZONES = {idle: "Idle: below 30 %", saturated: "Saturated: above 90 %"};
|
||||
const RESOURCE_MARKS = {
|
||||
wait: ["#bi-hourglass-split", (mark) => `${mark.peak} jobs waited while CPU and RAM stayed under 50 %`],
|
||||
asleep: ["#bi-moon", (mark) => `${mark.name} asleep`],
|
||||
unknown: ["#bi-question-circle", (mark) => `${mark.name} unknown: no reading`],
|
||||
};
|
||||
const RESOURCE_BURN = {done: "Done", scope: "Scope"};
|
||||
const resourceView = {data: null, dom: null, busy: false, key: "", at: 0, timer: 0};
|
||||
const resourceKey = () => JSON.stringify([ui.preset, ui.from, ui.to, ui.asOf]);
|
||||
const compactCount = (value) => (value >= 1e6 ? `${fixed(value / 1e6)}M` : value >= 1e3 ? `${fixed(value / 1e3)}k` : String(Math.round(value)));
|
||||
const resourceLabel = (line) => (line.kind === "vram" ? `${line.name} VRAM` : line.name);
|
||||
const percentOf = (value) => `${value} %`;
|
||||
|
||||
function resourceSwitch(key, next, name, label, hint) {
|
||||
const path = `resources.${key}`;
|
||||
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 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 panels = RESOURCE_PANELS.map(([kind, name, label]) => {
|
||||
const legend = h("div", {class: "res-legend"});
|
||||
const plot = h("div", {class: "res-plot"});
|
||||
const panel = h("section", {class: `card res-panel res-${kind}`, "data-panel": kind, "aria-label": label},
|
||||
const panel = h("section", {class: `card res-panel res-${kind}`, "data-panel": `resources-${kind}`, "aria-label": label, hidden: kind === "combined"},
|
||||
h("div", {class: "res-head"}, h("span", {class: "res-title", title: label, "aria-label": label}, icon(name)), legend), plot);
|
||||
return {kind, label, legend, plot, panel};
|
||||
});
|
||||
resourceView.dom = {count, panels};
|
||||
resourceView.dom = {count, switches, panels};
|
||||
if (!resourceView.timer) {
|
||||
resourceView.timer = window.setInterval(pollResources, RESOURCE.poll);
|
||||
window.addEventListener("resize", drawResources);
|
||||
ViewStore.on("resources", drawResources);
|
||||
}
|
||||
window.setTimeout(() => {
|
||||
drawResources();
|
||||
@@ -31,7 +43,7 @@
|
||||
}, 0);
|
||||
const reload = iconBtn("bi-arrow-clockwise", "Reload", "btn small soft", fetchResources, "Reload: read the sampler files again");
|
||||
return h("div", {class: "graph resources"},
|
||||
h("div", {class: "card controls"}, h("div", {class: "toolbar", role: "toolbar", "aria-label": "Resources"}, reload, count)),
|
||||
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)));
|
||||
}
|
||||
|
||||
@@ -64,11 +76,12 @@
|
||||
drawResources();
|
||||
}
|
||||
|
||||
function resourceFrame(entry, span, size) {
|
||||
const axis = entry.kind === "tokens";
|
||||
function resourceFrame(entry, span, size, dual) {
|
||||
const axis = entry.kind !== "hardware";
|
||||
const right = size.width - (dual ? RESOURCE.wide : RESOURCE.right);
|
||||
const bottom = size.height - (axis ? RESOURCE.axis : RESOURCE.bottom);
|
||||
const x = (t) => RESOURCE.left + ((t - span.from) / (span.to - span.from)) * (size.width - RESOURCE.left - RESOURCE.right);
|
||||
const svg = s("svg", {class: `chart res-chart res-${entry.kind}`, "data-panel": entry.kind, "data-from": span.from, "data-to": span.to, viewBox: `0 0 ${size.width} ${size.height}`, role: "img", "aria-label": entry.label});
|
||||
const x = (t) => RESOURCE.left + ((Math.min(Math.max(t, span.from), span.to) - span.from) / (span.to - span.from)) * (right - RESOURCE.left);
|
||||
const svg = s("svg", {class: `chart res-chart res-${entry.kind}`, "data-chart": entry.kind, "data-from": span.from, "data-to": span.to, viewBox: `0 0 ${size.width} ${size.height}`, role: "img", "aria-label": entry.label});
|
||||
const ticks = size.width < RESOURCE.narrow ? 2 : 4;
|
||||
for (let index = 0; index <= ticks; index += 1) {
|
||||
const t = span.from + ((span.to - span.from) * index) / ticks;
|
||||
@@ -77,19 +90,25 @@
|
||||
svg.append(s("text", {class: "axis", x: fixed(x(t)), y: size.height - 4, "text-anchor": index === 0 ? "start" : index === ticks ? "end" : "middle"}, (span.to - span.from > DAY ? absolute : clock).format(stampOf(t))));
|
||||
}
|
||||
}
|
||||
return {svg, x, top: RESOURCE.top, bottom, right: size.width - RESOURCE.right};
|
||||
return {svg, x, top: RESOURCE.top, bottom, right};
|
||||
}
|
||||
|
||||
function resourceScale(frame, values, label) {
|
||||
function resourceScale(frame, values, label, side) {
|
||||
const y = (value) => frame.top + (1 - value / values[values.length - 1]) * (frame.bottom - frame.top);
|
||||
const left = side === "left";
|
||||
for (const value of values) {
|
||||
frame.svg.append(s("line", {class: "grid", x1: RESOURCE.left, x2: fixed(frame.right), y1: fixed(y(value)), y2: fixed(y(value))}));
|
||||
frame.svg.append(s("text", {class: "axis", x: RESOURCE.left - 6, y: fixed(y(value)), dy: "0.35em", "text-anchor": "end"}, label(value)));
|
||||
if (left) {
|
||||
frame.svg.append(s("line", {class: "grid", x1: RESOURCE.left, x2: fixed(frame.right), y1: fixed(y(value)), y2: fixed(y(value))}));
|
||||
}
|
||||
frame.svg.append(s("text", {class: `axis ${side}`, "data-axis": side, x: left ? RESOURCE.left - 6 : fixed(frame.right + 6), y: fixed(y(value)), dy: "0.35em", "text-anchor": left ? "end" : "start"}, label(value)));
|
||||
}
|
||||
return y;
|
||||
}
|
||||
|
||||
function resourceMarks(frame, marks, span) {
|
||||
function resourceBackdrop(frame, y, marks, span) {
|
||||
for (const zone of Resources.ZONES) {
|
||||
frame.svg.append(s("rect", {class: `band ${zone.kind}`, "data-zone": zone.kind, x: RESOURCE.left, width: fixed(frame.right - RESOURCE.left), y: fixed(y(zone.to)), height: fixed(y(zone.from) - y(zone.to))}, s("title", {}, RESOURCE_ZONES[zone.kind])));
|
||||
}
|
||||
for (const mark of marks) {
|
||||
const left = frame.x(Math.max(mark.from, span.from));
|
||||
const right = frame.x(Math.min(mark.to, span.to));
|
||||
@@ -102,73 +121,165 @@
|
||||
}
|
||||
}
|
||||
|
||||
function resourcePercent(entry, list, marks, span, size) {
|
||||
const frame = resourceFrame(entry, span, size);
|
||||
const y = resourceScale(frame, [0, 50, 100], (value) => `${value} %`);
|
||||
for (const zone of Resources.ZONES) {
|
||||
frame.svg.append(s("rect", {class: `band ${zone.kind}`, "data-zone": zone.kind, x: RESOURCE.left, width: fixed(frame.right - RESOURCE.left), y: fixed(y(zone.to)), height: fixed(y(zone.from) - y(zone.to))}, s("title", {}, RESOURCE_ZONES[zone.kind])));
|
||||
}
|
||||
resourceMarks(frame, marks, span);
|
||||
const tones = new Map();
|
||||
const legend = [];
|
||||
function resourceLines(frame, y, list) {
|
||||
for (const line of list) {
|
||||
if (!tones.has(line.name)) {
|
||||
tones.set(line.name, tones.size % RESOURCE.tones);
|
||||
}
|
||||
const tone = `res-c${tones.get(line.name)} k-${line.kind}`;
|
||||
const last = [...line.points].reverse().find(([, value]) => value !== null);
|
||||
const words = `${resourceLabel(line)} ${dash(last === undefined ? null : last[1])} %`;
|
||||
for (const part of Resources.segments(line.points)) {
|
||||
const d = part.map(([t, value], index) => `${index ? "L" : "M"}${fixed(frame.x(t))},${fixed(y(Math.min(Math.max(value, 0), 100)))}`).join(" ");
|
||||
frame.svg.append(s("path", {class: `res-line ${tone}`, "data-series": line.name, "data-kind": line.kind, "data-points": part.length, d: part.length === 1 ? `${d} h1` : d}, s("title", {}, words)));
|
||||
frame.svg.append(s("path", {class: `res-line ${line.tone}`, "data-id": line.id, "data-series": line.name, "data-kind": line.kind, "data-points": part.length, d: part.length === 1 ? `${d} h1` : d}, s("title", {}, line.label)));
|
||||
}
|
||||
legend.push(h("span", {class: `res-key ${tone}`, "data-series": line.name, "data-kind": line.kind}, words));
|
||||
}
|
||||
return {svg: frame.svg, legend};
|
||||
}
|
||||
|
||||
function resourceTokens(entry, stack, span, size) {
|
||||
const frame = resourceFrame(entry, span, size);
|
||||
const y = resourceScale(frame, [0, Math.max(stack.top, 1)], compactCount);
|
||||
const tones = new Map(stack.agents.map((agent, index) => [agent, index % RESOURCE.tones]));
|
||||
for (const bar of stack.bars) {
|
||||
function resourceSteps(frame, y, points) {
|
||||
return points.map(([t, value], index) => (index ? `H${fixed(frame.x(t))} V${fixed(y(value))}` : `M${fixed(frame.x(t))},${fixed(y(value))}`)).join(" ");
|
||||
}
|
||||
|
||||
function tokenPlot(rows, mode) {
|
||||
if (mode === "accumulated") {
|
||||
const sums = Resources.accumulate(rows);
|
||||
return {mode, top: Math.max(sums.top, 1), sums};
|
||||
}
|
||||
const stack = Resources.stack(rows);
|
||||
return {mode, top: Math.max(stack.top, 1), stack};
|
||||
}
|
||||
|
||||
function tokenMarks(frame, y, plot, tones, span, faint) {
|
||||
if (plot.mode === "accumulated") {
|
||||
for (const line of plot.sums.lines) {
|
||||
const last = line.points[line.points.length - 1][1];
|
||||
frame.svg.append(s("path", {class: `res-sum res-c${tones.get(line.agent)}`, "data-agent": line.agent, "data-last": last, "data-points": JSON.stringify(line.points.map(([, value]) => value)), d: resourceSteps(frame, y, line.points)},
|
||||
s("title", {}, `${line.agent}: ${last} tokens summed up in the window`)));
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const bar of plot.stack.bars) {
|
||||
const left = frame.x(Math.max(bar.t, span.from));
|
||||
const right = frame.x(Math.min(bar.t + RESOURCE.hour, span.to));
|
||||
const right = frame.x(Math.min(bar.t + Resources.HOUR, span.to));
|
||||
if (right <= left) {
|
||||
continue;
|
||||
}
|
||||
for (const part of bar.parts) {
|
||||
const words = `${part.agent} · ${absolute.format(stampOf(bar.t))}: ${part.total} tokens (input ${part.input}, output ${part.output}, cache read ${part.cache_read}, cache write ${part.cache_write}) · ${part.models.join(", ")}`;
|
||||
frame.svg.append(s("rect", {class: `res-bar res-c${tones.get(part.agent)}`, "data-agent": part.agent, "data-t": bar.t, "data-total": part.total, x: fixed(left), width: fixed(Math.max(right - left - 1, 1)), y: fixed(y(part.to)), height: fixed(Math.max(y(part.from) - y(part.to), 0.5))}, s("title", {}, words)));
|
||||
frame.svg.append(s("rect", {class: `res-bar res-c${tones.get(part.agent)}${faint ? " faint" : ""}`, "data-agent": part.agent, "data-t": bar.t, "data-total": part.total, x: fixed(left), width: fixed(Math.max(right - left - 1, 1)), y: fixed(y(part.to)), height: fixed(Math.max(y(part.from) - y(part.to), 0.5))}, s("title", {}, words)));
|
||||
}
|
||||
}
|
||||
const legend = stack.agents.map((agent) => h("span", {class: `res-key res-c${tones.get(agent)}`, "data-series": agent}, `${agent} ${compactCount(stack.totals[agent])}`));
|
||||
return {svg: frame.svg, legend};
|
||||
}
|
||||
|
||||
function hardwareSeries(samples) {
|
||||
const tones = new Map();
|
||||
return Resources.hardware(samples).map((line) => {
|
||||
if (!tones.has(line.name)) {
|
||||
tones.set(line.name, tones.size % RESOURCE.tones);
|
||||
}
|
||||
const last = [...line.points].reverse().find(([, value]) => value !== null);
|
||||
return {...line, id: ViewStore.id(line.kind, line.name), label: `${resourceLabel(line)} ${dash(last === undefined ? null : last[1])} %`, tone: `res-c${tones.get(line.name)} k-${line.kind}`};
|
||||
});
|
||||
}
|
||||
|
||||
function agentSeries(tokens) {
|
||||
const full = Resources.stack(tokens);
|
||||
const tones = new Map(full.agents.map((agent, index) => [agent, index % RESOURCE.tones]));
|
||||
const list = full.agents.map((agent) => ({id: ViewStore.id("agent", agent), agent, label: `${agent} ${compactCount(full.totals[agent])}`, tone: `res-c${tones.get(agent)}`}));
|
||||
return {list, tones};
|
||||
}
|
||||
|
||||
function burnSeries(span) {
|
||||
const picked = Plan.scoped(state.tasks, "filter", {filtered: state.tasks, since: span.from, until: span.to, now: state.now, holders: {}});
|
||||
const scaled = Resources.burnup(Plan.burn(picked.rows, {estimation: settings.estimation, from: span.from, to: span.to}).points);
|
||||
return Object.entries(RESOURCE_BURN).map(([name, word]) => {
|
||||
const points = scaled[name];
|
||||
const last = points.length ? points[points.length - 1][1] : 0;
|
||||
return {id: ViewStore.id("burn", name), name, points, label: `${word} ${Math.round(last)} %`, tone: `res-burn k-${name}`, top: scaled.top};
|
||||
});
|
||||
}
|
||||
|
||||
function shownRows(tokens, agents, hidden) {
|
||||
const gone = new Set(agents.list.filter((entry) => hidden.has(entry.id)).map((entry) => entry.agent));
|
||||
return tokens.filter((row) => !gone.has(row.agent));
|
||||
}
|
||||
|
||||
function hardwareChart(entry, parts, span, size) {
|
||||
const frame = resourceFrame(entry, span, size, false);
|
||||
const y = resourceScale(frame, [0, 50, 100], percentOf, "left");
|
||||
resourceBackdrop(frame, y, parts.marks, span);
|
||||
resourceLines(frame, y, parts.hardware.filter((line) => !parts.hidden.has(line.id)));
|
||||
return {svg: frame.svg, series: parts.hardware, path: "resources.hidden"};
|
||||
}
|
||||
|
||||
function tokensChart(entry, parts, span, size) {
|
||||
const frame = resourceFrame(entry, span, size, false);
|
||||
const plot = tokenPlot(shownRows(parts.tokens, parts.agents, parts.hidden), parts.mode);
|
||||
const y = resourceScale(frame, [0, plot.top], compactCount, "left");
|
||||
tokenMarks(frame, y, plot, parts.agents.tones, span, false);
|
||||
return {svg: frame.svg, series: parts.agents.list, path: "resources.hidden"};
|
||||
}
|
||||
|
||||
function combinedChart(entry, parts, span, size) {
|
||||
const frame = resourceFrame(entry, span, size, true);
|
||||
const y = resourceScale(frame, [0, 50, 100], percentOf, "left");
|
||||
resourceBackdrop(frame, y, parts.marks, span);
|
||||
const plot = tokenPlot(shownRows(parts.tokens, parts.agents, parts.combinedHidden), parts.mode);
|
||||
tokenMarks(frame, resourceScale(frame, [0, plot.top], compactCount, "right"), plot, parts.agents.tones, span, true);
|
||||
resourceLines(frame, y, parts.hardware.filter((line) => !parts.combinedHidden.has(line.id)));
|
||||
for (const line of parts.burn.filter((item) => !parts.combinedHidden.has(item.id) && item.points.length)) {
|
||||
frame.svg.append(s("path", {class: line.tone, "data-id": line.id, "data-series": line.name, "data-last": line.points[line.points.length - 1][1], "data-top": line.top, d: resourceSteps(frame, y, line.points)}, s("title", {}, `${line.label} of the largest scope in the window (${line.top})`)));
|
||||
}
|
||||
return {svg: frame.svg, series: [...parts.hardware, ...parts.agents.list, ...parts.burn], path: "resources.combinedHidden"};
|
||||
}
|
||||
|
||||
const RESOURCE_CHARTS = {hardware: hardwareChart, tokens: tokensChart, combined: combinedChart};
|
||||
|
||||
function resourceParts(data, view, span) {
|
||||
return {
|
||||
hardware: hardwareSeries(data.samples),
|
||||
agents: agentSeries(data.tokens),
|
||||
tokens: data.tokens,
|
||||
mode: view.tokens,
|
||||
hidden: new Set(view.hidden),
|
||||
combinedHidden: new Set(view.combinedHidden),
|
||||
burn: view.combined ? burnSeries(span) : [],
|
||||
marks: [
|
||||
...Resources.waits(data.samples).map((mark) => ({...mark, kind: "wait"})),
|
||||
...["asleep", "unknown"].flatMap((kind) => Resources[kind](data.samples).flatMap((gpu) => gpu.spans.map((mark) => ({...mark, kind, name: gpu.name})))),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function drawResources() {
|
||||
const dom = resourceView.dom;
|
||||
const data = resourceView.data;
|
||||
if (!dom || !dom.count.isConnected || data === null) {
|
||||
if (!dom || !dom.count.isConnected) {
|
||||
return;
|
||||
}
|
||||
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;
|
||||
}
|
||||
if (data === null) {
|
||||
return;
|
||||
}
|
||||
const active = document.activeElement;
|
||||
const focused = active && typeof active.getAttribute === "function" ? active.getAttribute("data-chip") : null;
|
||||
const span = {from: data.since, to: Math.max(data.until, data.since + 60)};
|
||||
const lines = Resources.lines(data.samples);
|
||||
const marks = {
|
||||
disks: [],
|
||||
host: Resources.waits(data.samples).map((mark) => ({...mark, kind: "wait"})),
|
||||
gpu: ["asleep", "unknown"].flatMap((kind) => Resources[kind](data.samples).flatMap((gpu) => gpu.spans.map((mark) => ({...mark, kind, name: gpu.name})))),
|
||||
};
|
||||
const parts = resourceParts(data, view, span);
|
||||
dom.count.textContent = String(data.samples.length);
|
||||
for (const entry of dom.panels) {
|
||||
const box = entry.plot.getBoundingClientRect();
|
||||
const size = {width: Math.round(box.width), height: Math.round(box.height)};
|
||||
if (size.width < RESOURCE.left + RESOURCE.right + 10 || size.height < RESOURCE.axis + 10) {
|
||||
if (entry.panel.hidden) {
|
||||
entry.plot.replaceChildren();
|
||||
entry.legend.replaceChildren();
|
||||
continue;
|
||||
}
|
||||
const drawn = entry.kind === "tokens" ? resourceTokens(entry, Resources.stack(data.tokens), span, size) : resourcePercent(entry, lines[entry.kind], marks[entry.kind], span, size);
|
||||
entry.plot.replaceChildren(drawn.svg);
|
||||
entry.legend.replaceChildren(...drawn.legend);
|
||||
const box = entry.plot.getBoundingClientRect();
|
||||
const size = {width: Math.round(box.width), height: Math.round(box.height)};
|
||||
const drawn = RESOURCE_CHARTS[entry.kind](entry, parts, span, size);
|
||||
const small = size.width < RESOURCE.left + RESOURCE.wide + 10 || size.height < RESOURCE.axis + 10;
|
||||
entry.plot.replaceChildren(...(small ? [] : [drawn.svg]));
|
||||
entry.legend.replaceChildren(LegendChips.render(drawn.series, drawn.path, "hidden"));
|
||||
const chip = focused === null ? null : [...entry.legend.querySelectorAll("[data-chip]")].find((node) => node.getAttribute("data-chip") === focused);
|
||||
if (chip) {
|
||||
chip.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ const Resources = (() => {
|
||||
const CALM = 50;
|
||||
const GAP = 1800;
|
||||
const STEP = 60;
|
||||
const HOUR = 3600;
|
||||
const COUNTS = ["input", "output", "cache_read", "cache_write"];
|
||||
const ZONES = [{kind: "idle", from: 0, to: IDLE}, {kind: "saturated", from: SATURATED, to: 100}];
|
||||
const finite = (value) => typeof value === "number" && Number.isFinite(value);
|
||||
@@ -34,6 +35,15 @@ const Resources = (() => {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param samples - sampler rows.
|
||||
* @returns every percent line of lines() on one axis: the disks, then CPU, RAM and swap, then each GPU and its VRAM.
|
||||
*/
|
||||
function hardware(samples) {
|
||||
const found = lines(samples);
|
||||
return [...found.disks, ...found.host, ...found.gpu];
|
||||
}
|
||||
|
||||
function segments(points) {
|
||||
const found = [];
|
||||
let current = [];
|
||||
@@ -137,7 +147,38 @@ const Resources = (() => {
|
||||
return {agents, totals: Object.fromEntries(totals), bars, top: Math.max(0, ...bars.map((bar) => bar.total))};
|
||||
}
|
||||
|
||||
return {IDLE, SATURATED, CALM, GAP, COUNTS, ZONES, lines, segments, spans, waits, asleep, unknown, stack};
|
||||
/**
|
||||
* @param tokens - token rows as stack() takes them.
|
||||
* @returns {agents, lines: [{agent, points: [[t, sum]]}], top}: per agent its running sum, 0 at the first hour's
|
||||
* start and then at the end of every hour any agent spent in, so a line never decreases; top is the largest sum.
|
||||
*/
|
||||
function accumulate(tokens) {
|
||||
const {agents, bars} = stack(tokens);
|
||||
const sums = new Map(agents.map((agent) => [agent, 0]));
|
||||
const found = new Map(agents.map((agent) => [agent, bars.length ? [[bars[0].t, 0]] : []]));
|
||||
for (const bar of bars) {
|
||||
for (const part of bar.parts) {
|
||||
sums.set(part.agent, sums.get(part.agent) + part.total);
|
||||
}
|
||||
for (const agent of agents) {
|
||||
found.get(agent).push([bar.t + HOUR, sums.get(agent)]);
|
||||
}
|
||||
}
|
||||
return {agents, lines: agents.map((agent) => ({agent, points: found.get(agent)})), top: Math.max(0, ...sums.values())};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param points - Plan.burn() points of the window.
|
||||
* @returns {top, done, scope}: the largest scope in the window and the done and scope series as [t, percent of
|
||||
* that scope]; both stay 0 while the scope is empty.
|
||||
*/
|
||||
function burnup(points) {
|
||||
const top = Math.max(0, ...points.map((point) => point.scope));
|
||||
const percent = (value) => (top > 0 ? (100 * value) / top : 0);
|
||||
return {top, done: points.map((point) => [point.t, percent(point.done)]), scope: points.map((point) => [point.t, percent(point.scope)])};
|
||||
}
|
||||
|
||||
return {IDLE, SATURATED, CALM, GAP, HOUR, COUNTS, ZONES, lines, hardware, segments, spans, waits, asleep, unknown, stack, accumulate, burnup};
|
||||
})();
|
||||
if (typeof module === "object" && module.exports) {
|
||||
module.exports = Resources;
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
.legend-chips { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 6px; min-width: 0; }
|
||||
.legend-chip { display: inline-flex; align-items: center; gap: 5px; max-width: 260px; padding: 1px 8px; overflow: hidden; border: 1px solid var(--line); border-radius: 999px; background: transparent; color: var(--text); font: inherit; font-size: var(--fs-xs); font-variant-numeric: tabular-nums; line-height: 18px; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; }
|
||||
.legend-chip::before { content: ""; flex: none; width: 12px; height: 3px; border-radius: 2px; background: var(--c, var(--muted)); }
|
||||
.legend-chip.k-vram::before, .legend-chip.k-scope::before { background: repeating-linear-gradient(90deg, var(--c) 0 4px, transparent 4px 6px); }
|
||||
.legend-chip:hover { border-color: var(--line-strong); }
|
||||
.legend-chip:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||
.legend-chip[aria-pressed="false"] { color: var(--muted); text-decoration: line-through; opacity: 0.5; }
|
||||
@@ -1,27 +1,32 @@
|
||||
body.fit .graph.resources > .res-panels { flex: 1; }
|
||||
.res-panels { display: flex; flex-direction: column; gap: 8px; min-height: 0; }
|
||||
.res-panel { display: flex; flex: 1 1 0; flex-direction: column; gap: 2px; min-height: 72px; padding: 6px 10px; overflow: hidden; }
|
||||
.res-head { display: flex; align-items: center; gap: 4px 12px; min-width: 0; overflow: hidden; color: var(--muted); font-size: var(--fs-xs); white-space: nowrap; }
|
||||
.res-panel[hidden] { display: none; }
|
||||
.res-head { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 12px; min-width: 0; color: var(--muted); font-size: var(--fs-xs); }
|
||||
.res-title { display: inline-flex; color: var(--text); font-size: var(--fs-md); }
|
||||
.res-legend { display: flex; gap: 4px 12px; min-width: 0; overflow: hidden; font-variant-numeric: tabular-nums; }
|
||||
.res-key { display: inline-flex; align-items: center; gap: 5px; }
|
||||
.res-key::before { content: ""; width: 12px; height: 3px; border-radius: 2px; background: var(--c); }
|
||||
.res-key.k-vram::before { background: repeating-linear-gradient(90deg, var(--c) 0 4px, transparent 4px 6px); }
|
||||
.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-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); }
|
||||
svg .band.saturated { fill: var(--bad-soft); }
|
||||
svg .res-line { fill: none; stroke: var(--c); stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
|
||||
svg .res-line.k-vram { stroke-dasharray: 5 3; }
|
||||
svg .res-sum { fill: none; stroke: var(--c); stroke-width: 2; stroke-linejoin: round; }
|
||||
svg .res-burn { fill: none; stroke: var(--c); stroke-width: 2.4; stroke-linejoin: round; }
|
||||
svg .res-burn.k-scope { stroke-dasharray: 7 4; }
|
||||
svg .res-mark.wait { fill: var(--warn-soft); stroke: var(--warn); stroke-dasharray: 3 3; }
|
||||
svg .res-mark.asleep { fill: var(--neutral-soft); }
|
||||
svg .res-mark.unknown { fill: var(--neutral-soft); stroke: var(--muted); stroke-dasharray: 2 3; }
|
||||
svg .res-icon.wait { fill: var(--warn); }
|
||||
svg .res-icon.asleep, svg .res-icon.unknown { fill: var(--muted); }
|
||||
svg .res-bar { fill: var(--c); }
|
||||
svg .res-bar.faint { opacity: 0.35; }
|
||||
.res-c0 { --c: var(--info); }
|
||||
.res-c1 { --c: var(--ok); }
|
||||
.res-c2 { --c: var(--accent); }
|
||||
.res-c3 { --c: var(--warn); }
|
||||
.res-c4 { --c: var(--violet); }
|
||||
.res-c5 { --c: var(--bad); }
|
||||
.res-burn.k-done { --c: var(--ok); }
|
||||
.res-burn.k-scope { --c: var(--text); }
|
||||
@@ -0,0 +1,259 @@
|
||||
const ViewStore = (() => {
|
||||
"use strict";
|
||||
const ROUTE = "/api/view";
|
||||
const DELAY = 250;
|
||||
const TRIES = 3;
|
||||
const ID_LIMIT = 200;
|
||||
const HASHED = 8;
|
||||
const ESCAPE = /[^A-Za-z0-9./-]/gu;
|
||||
const LEAF = /^[A-Za-z]{1,32}\.[A-Za-z]{1,32}$/u;
|
||||
const HEADERS = {"X-Kvb-Orchestrator": "1", "Content-Type": "application/json"};
|
||||
const store = {doc: null, saved: null, flight: new Map(), pending: new Map(), listeners: [], timer: 0, chain: Promise.resolve(), waiting: [], error: "", leaving: false};
|
||||
const clone = (value) => JSON.parse(JSON.stringify(value));
|
||||
const related = (one, other) => one === "" || other === "" || one === other || one.startsWith(`${other}.`) || other.startsWith(`${one}.`);
|
||||
|
||||
function slot(path, doc) {
|
||||
const keys = String(path).split(".");
|
||||
let parent = null;
|
||||
let node = doc;
|
||||
for (const key of keys) {
|
||||
if (node === null || typeof node !== "object" || Array.isArray(node) || !Object.hasOwn(node, key)) {
|
||||
throw new Error(`unknown view path ${path}`);
|
||||
}
|
||||
parent = node;
|
||||
node = node[key];
|
||||
}
|
||||
return {parent, key: keys[keys.length - 1], value: node};
|
||||
}
|
||||
|
||||
const fold = (changes, base) => changes.reduce((value, change) => clone(change(clone(value))), base);
|
||||
|
||||
function rebuild() {
|
||||
const next = clone(store.saved);
|
||||
for (const [path, entry] of store.flight) {
|
||||
const found = slot(path, next);
|
||||
found.parent[found.key] = clone(entry.value);
|
||||
}
|
||||
for (const [path, changes] of store.pending) {
|
||||
const found = slot(path, next);
|
||||
found.parent[found.key] = fold(changes, found.value);
|
||||
}
|
||||
store.doc = next;
|
||||
}
|
||||
|
||||
function notify(path) {
|
||||
for (const entry of [...store.listeners]) {
|
||||
if (related(entry.path, path)) {
|
||||
entry.callback(get(entry.path));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param doc - the whole view document the hub served.
|
||||
*/
|
||||
function start(doc) {
|
||||
store.saved = clone(doc);
|
||||
store.flight = new Map();
|
||||
store.pending = new Map();
|
||||
rebuild();
|
||||
notify("");
|
||||
}
|
||||
|
||||
function current() {
|
||||
if (store.doc === null) {
|
||||
start(JSON.parse(document.getElementById("view").textContent));
|
||||
}
|
||||
return store.doc;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param path - a dotted key of the view document, such as resources.hidden.
|
||||
* @returns a copy of its value as this page shows it, its own unsent changes included.
|
||||
*/
|
||||
const get = (path) => clone(slot(path, current()).value);
|
||||
|
||||
function adopt(doc) {
|
||||
store.saved = clone(doc);
|
||||
rebuild();
|
||||
notify("");
|
||||
}
|
||||
|
||||
async function send(body, keepalive) {
|
||||
try {
|
||||
const response = await fetch(ROUTE, {method: "PATCH", headers: HEADERS, body: JSON.stringify(body), cache: "no-store", keepalive});
|
||||
if (response.ok || response.status === 409) {
|
||||
return {status: response.ok ? 200 : 409, data: await response.json()};
|
||||
}
|
||||
return {status: response.status, error: (await response.text()).trim() || String(response.status)};
|
||||
} catch (error) {
|
||||
return {status: 0, error: String(error && error.message ? error.message : error)};
|
||||
}
|
||||
}
|
||||
|
||||
function takeOff() {
|
||||
const body = {set: {}, expect: {}};
|
||||
for (const [path, changes] of store.pending) {
|
||||
const base = slot(path, store.saved).value;
|
||||
const value = fold(changes, base);
|
||||
store.flight.set(path, {changes, value});
|
||||
body.set[path] = value;
|
||||
body.expect[path] = base;
|
||||
}
|
||||
store.pending = new Map();
|
||||
return body;
|
||||
}
|
||||
|
||||
function land() {
|
||||
const back = new Map([...store.flight].map(([path, entry]) => [path, [...entry.changes, ...(store.pending.get(path) || [])]]));
|
||||
store.flight = new Map();
|
||||
for (const [path, changes] of store.pending) {
|
||||
if (!back.has(path)) {
|
||||
back.set(path, changes);
|
||||
}
|
||||
}
|
||||
store.pending = back;
|
||||
}
|
||||
|
||||
async function flush() {
|
||||
const waiting = store.waiting.splice(0);
|
||||
let stored = true;
|
||||
for (let attempt = 1; store.pending.size; attempt += 1) {
|
||||
const answer = await send(takeOff(), false);
|
||||
if (answer.status === 200) {
|
||||
store.flight = new Map();
|
||||
store.error = "";
|
||||
adopt(answer.data);
|
||||
break;
|
||||
}
|
||||
if (answer.status === 409 && attempt < TRIES) {
|
||||
land();
|
||||
adopt(answer.data.view);
|
||||
continue;
|
||||
}
|
||||
store.error = answer.status === 409 ? `another browser kept changing ${answer.data.paths.join(", ")}; try again` : answer.error;
|
||||
store.flight = new Map();
|
||||
adopt(answer.status === 409 ? answer.data.view : store.saved);
|
||||
stored = false;
|
||||
break;
|
||||
}
|
||||
waiting.forEach((resolve) => resolve(stored));
|
||||
}
|
||||
|
||||
function leave() {
|
||||
clearTimeout(store.timer);
|
||||
store.timer = 0;
|
||||
if (!store.pending.size) {
|
||||
return;
|
||||
}
|
||||
const body = {set: {}, expect: {}};
|
||||
for (const [path, changes] of store.pending) {
|
||||
const base = store.flight.has(path) ? store.flight.get(path).value : slot(path, store.saved).value;
|
||||
body.set[path] = fold(changes, base);
|
||||
body.expect[path] = base;
|
||||
}
|
||||
store.pending = new Map();
|
||||
const waiting = store.waiting.splice(0);
|
||||
send(body, true).then((answer) => {
|
||||
if (answer.status === 200) {
|
||||
adopt(answer.data);
|
||||
}
|
||||
waiting.forEach((resolve) => resolve(answer.status === 200));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param path - a section.key of the view document, such as home.pins.
|
||||
* @param change - a function from the key's current value to its new one; when another browser changed the key
|
||||
* meanwhile, the hub refuses the write and the page runs change again on the stored value, up to three times.
|
||||
* @returns a promise of true once the hub stored the change, false when it refused it; the page then shows the
|
||||
* stored value again and error() says why.
|
||||
*/
|
||||
function update(path, change) {
|
||||
if (!LEAF.test(String(path))) {
|
||||
throw new Error(`a view path to change must be section.key, not ${path}`);
|
||||
}
|
||||
slot(path, current());
|
||||
store.pending.set(path, [...(store.pending.get(path) || []), change]);
|
||||
rebuild();
|
||||
notify(path);
|
||||
if (!store.leaving && typeof addEventListener === "function") {
|
||||
store.leaving = true;
|
||||
addEventListener("pagehide", leave);
|
||||
}
|
||||
clearTimeout(store.timer);
|
||||
store.timer = setTimeout(() => {
|
||||
store.timer = 0;
|
||||
store.chain = store.chain.then(flush);
|
||||
}, DELAY);
|
||||
return new Promise((resolve) => store.waiting.push(resolve));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param path - a section.key of the view document that holds a scalar; a list path throws, it changes through
|
||||
* update() only.
|
||||
* @param value - its new value, replacing whatever another browser stored there.
|
||||
* @returns the promise update() returns.
|
||||
*/
|
||||
function set(path, value) {
|
||||
if (Array.isArray(slot(path, current()).value)) {
|
||||
throw new Error(`a list view path changes through update(), not set(): ${path}`);
|
||||
}
|
||||
return update(path, () => clone(value));
|
||||
}
|
||||
|
||||
async function restore(event) {
|
||||
if (!event.persisted) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch(ROUTE, {method: "GET", cache: "no-store"});
|
||||
if (response.ok) {
|
||||
adopt(await response.json());
|
||||
}
|
||||
} catch (error) {
|
||||
store.error = String(error && error.message ? error.message : error);
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof addEventListener === "function") {
|
||||
addEventListener("pageshow", restore);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param path - a dotted key of the view document.
|
||||
* @param callback - called with the key's new value whenever it, a key inside it or one around it changes.
|
||||
* @returns a function that stops the calls.
|
||||
*/
|
||||
function on(path, callback) {
|
||||
slot(path, current());
|
||||
const entry = {path: String(path), callback};
|
||||
store.listeners.push(entry);
|
||||
return () => {
|
||||
store.listeners = store.listeners.filter((item) => item !== entry);
|
||||
};
|
||||
}
|
||||
|
||||
function hash(text) {
|
||||
let value = 0x811c9dc5;
|
||||
for (const char of text) {
|
||||
value = Math.imul(value ^ char.codePointAt(0), 0x01000193) >>> 0;
|
||||
}
|
||||
return value.toString(16).padStart(HASHED, "0");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param parts - the names that make one series, such as its kind and its name.
|
||||
* @returns an id of the view document's grammar: every part with each character outside A-Z, a-z, 0-9 and ./-
|
||||
* written as _<hex>_, joined by ":", and cut to 200 characters with a hash of the whole when longer.
|
||||
*/
|
||||
function id(...parts) {
|
||||
const text = parts.map((part) => String(part).replace(ESCAPE, (char) => `_${char.codePointAt(0).toString(16)}_`)).join(":");
|
||||
return text.length <= ID_LIMIT ? text : `${text.slice(0, ID_LIMIT - HASHED - 1)}:${hash(text)}`;
|
||||
}
|
||||
|
||||
return {ROUTE, DELAY, TRIES, start, get, set, update, on, id, error: () => store.error};
|
||||
})();
|
||||
if (typeof module === "object" && module.exports) {
|
||||
module.exports = ViewStore;
|
||||
}
|
||||
Reference in new issue
Block a user