feat(orchestrator): time range and replay move into the rates panel (015)
The navbar time menu goes; the rates panel holds the presets, a two-handle span slider over the hub's history, replay and Live, and the custom From/To range. A custom range becomes a window length plus an end point, so live windows keep their length. The rates chip lists every metric, and the panel wraps instead of spilling at 390 px. Unit and e2e (Chromium, Firefox, 1920/1366/390) cover the window, the slider and the requests. 🎯 Fix: 94 % 💥 Break: 4 % 💸 Tokens: 100 % ⏱️ Velocity: 100 % 🛡️ Security: 100 % 🏆 Score: 90 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
09e3f6dabe
commit
cc6ea7c230
20 files changed
+462
-416
No files matched your search
@@ -1,6 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
|
||||
@@ -17,11 +16,10 @@ GAUGES = ("cpu", "ram", "vram", "swap", "disk")
|
||||
METRICS = (*COUNTS, *GAUGES)
|
||||
HOST = ("cpu", "ram", "swap")
|
||||
TOKEN_FIELDS = ("input", "output", "cache_read", "cache_write")
|
||||
FINEST = {"tokens": HOUR}
|
||||
FINEST = {"tasks": 0, "commits": 0, "krs": 0, "tokens": HOUR}
|
||||
INTERVAL = 60
|
||||
DONE = "done"
|
||||
DIGITS = 4
|
||||
TOTAL = "total"
|
||||
|
||||
NUMBERS = (int, float)
|
||||
LIMIT = 1e18
|
||||
@@ -99,87 +97,32 @@ def share(piece: Piece, begin: float, now: float) -> float:
|
||||
return amount * inside / (end - start) if inside > 0 else 0.0
|
||||
|
||||
|
||||
def sums(pieces: list[Piece], now: float, finest: float) -> dict[str, float | None]:
|
||||
def counted(pieces: list[Piece], window: tuple[float, float], first: float | None, finest: float) -> dict[str, dict]:
|
||||
"""Args:
|
||||
pieces: (start, end, amount) per event; start None for one without
|
||||
a time, end equal to start for an instant.
|
||||
now: the end of every window.
|
||||
finest: the shortest window the pieces resolve; a shorter one holds
|
||||
no event of its own.
|
||||
pieces: (start, end, amount) per event of one kind; start None for
|
||||
one without a time, end equal to start for an instant.
|
||||
window: (begin, end) the rates cover, in epoch seconds.
|
||||
first: the first time the records of the kind hold, None without any.
|
||||
finest: the shortest span the kind's pieces resolve.
|
||||
|
||||
Returns:
|
||||
Per period the amount inside its window, None below finest; total
|
||||
holds every piece.
|
||||
Per period {value, approx, covered}: covered the seconds of the
|
||||
window from first on; total the amount inside the window, every
|
||||
other period that amount per its seconds of covered; value None
|
||||
where no record covers the window; approx where the window is
|
||||
shorter than finest, and for every period but total where it starts
|
||||
before first.
|
||||
"""
|
||||
found: dict[str, float | None] = {}
|
||||
for name, seconds in PERIODS:
|
||||
if seconds is None:
|
||||
found[name] = sum(piece[2] for piece in pieces)
|
||||
else:
|
||||
found[name] = None if seconds < finest else sum(share(piece, now - seconds, now) for piece in pieces)
|
||||
return found
|
||||
|
||||
|
||||
def lengths(now: float, since: float | None) -> dict[str, float | None]:
|
||||
total = now - since if since is not None and now > since else None
|
||||
return {name: total if seconds is None else float(seconds) for name, seconds in PERIODS}
|
||||
|
||||
|
||||
def held(now: float, since: float | None, begins: float | None) -> dict[str, float | None]:
|
||||
"""Args:
|
||||
now: the end of every window.
|
||||
since: the first time any record holds.
|
||||
begins: the first time the records of one kind hold, None when they
|
||||
reach back as far as any record.
|
||||
|
||||
Returns:
|
||||
Per period the seconds now - begins where other records reach
|
||||
further back into its window than this kind's, else None.
|
||||
"""
|
||||
if since is None or begins is None:
|
||||
return dict.fromkeys(PERIOD_NAMES)
|
||||
return {name: now - begins if begins > (since if seconds is None else max(now - seconds, since)) else None for name, seconds in PERIODS}
|
||||
|
||||
|
||||
def estimate(own: dict[str, float | None], length: dict[str, float | None], partial: dict[str, float | None], index: int) -> tuple[float, str | None]:
|
||||
"""Returns:
|
||||
(value, source) of the period at index in PERIODS: its own amount
|
||||
when partial holds no seconds for it and it holds any or is total;
|
||||
its own amount scaled from the partial seconds to the part of its
|
||||
window any record covers when it holds any, source total; else the
|
||||
shortest longer window that holds any, scaled to the period's length
|
||||
(at most its whole amount), source that window, or total when
|
||||
partial holds seconds for that window and those scale it; 0 without
|
||||
any.
|
||||
"""
|
||||
name, seconds = PERIODS[index]
|
||||
value = own[name]
|
||||
if partial[name] is None and (value or seconds is None):
|
||||
return value or 0.0, None
|
||||
if value and partial[name]:
|
||||
return value * min(length[name], length[TOTAL]) / partial[name], TOTAL
|
||||
for other, _ in PERIODS[index + 1:]:
|
||||
if own[other] and length[other]:
|
||||
covered = partial[other] or length[other]
|
||||
return own[other] * min(1.0, (seconds or covered) / covered), TOTAL if partial[other] else other
|
||||
return 0.0, None
|
||||
|
||||
|
||||
def extrapolated(own: dict[str, float | None], length: dict[str, float | None], partial: dict[str, float | None]) -> dict[str, dict]:
|
||||
"""Args:
|
||||
own: sums() of one kind.
|
||||
length: lengths() of the windows.
|
||||
partial: held() of the kind.
|
||||
|
||||
Returns:
|
||||
Per period {value, approx, source} of estimate(); approx whenever it
|
||||
names a source.
|
||||
"""
|
||||
found = {}
|
||||
for index, name in enumerate(PERIOD_NAMES):
|
||||
value, source = estimate(own, length, partial, index)
|
||||
found[name] = {"value": precise(value), "approx": source is not None, "source": source}
|
||||
return found
|
||||
begin, end = window
|
||||
covered = end - max(begin, first) if first is not None else 0.0
|
||||
if covered <= 0:
|
||||
return {name: {"value": None, "approx": False, "covered": None} for name in PERIOD_NAMES}
|
||||
amount = sum(share(piece, begin, end) for piece in pieces)
|
||||
short, early = end - begin < finest, begin < first
|
||||
return {
|
||||
name: {"value": precise(amount if seconds is None else amount * seconds / covered), "approx": short or (early and seconds is not None), "covered": covered}
|
||||
for name, seconds in PERIODS
|
||||
}
|
||||
|
||||
|
||||
def precise(value: float) -> float:
|
||||
@@ -207,10 +150,6 @@ def blank() -> dict:
|
||||
return {**{key: [0.0, 0.0] for key in HOST}, "vram": [0.0, 0.0, 0.0], "disks": {}}
|
||||
|
||||
|
||||
def copied(tally: dict) -> dict:
|
||||
return {**{key: list(tally[key]) for key in (*HOST, "vram")}, "disks": {mount: list(cell) for mount, cell in tally["disks"].items()}}
|
||||
|
||||
|
||||
def add_vram(cell: list[float], gpus: object, weight: float) -> None:
|
||||
used = total = 0.0
|
||||
for gpu in gpus if type(gpus) is list else ():
|
||||
@@ -258,30 +197,16 @@ def add(tally: dict, row: dict, part: float) -> None:
|
||||
add_disks(tally["disks"], row.get("disks"), weight)
|
||||
|
||||
|
||||
def tallies(items: list[Placed], begins: list[float]) -> list[dict]:
|
||||
"""Args:
|
||||
items: placed() of every sample row, newest first.
|
||||
begins: the start of every window, latest first; every window ends
|
||||
at the newest row or later.
|
||||
|
||||
Returns:
|
||||
Per window the add() of every row inside it, a row whose bucket
|
||||
straddles its start by the share inside, in one pass over items.
|
||||
def tally(items: list[Placed], window: tuple[float, float]) -> dict:
|
||||
"""Returns:
|
||||
The add() of every placed() row inside the window, a row whose
|
||||
bucket straddles either end by its share inside.
|
||||
"""
|
||||
widest = max((item[1] for item in items), default=0.0)
|
||||
running, index, found = blank(), 0, []
|
||||
for begin in begins:
|
||||
while index < len(items) and items[index][0] >= begin:
|
||||
add(running, items[index][2], 1.0)
|
||||
index += 1
|
||||
tally = copied(running)
|
||||
cursor = index
|
||||
while cursor < len(items) and items[cursor][0] > begin - widest:
|
||||
t, width, row = items[cursor]
|
||||
if t + width > begin:
|
||||
add(tally, row, (t + width - begin) / width)
|
||||
cursor += 1
|
||||
found.append(tally)
|
||||
found = blank()
|
||||
for t, width, row in items:
|
||||
part = share((t, t + width, 1.0), *window)
|
||||
if part:
|
||||
add(found, row, part)
|
||||
return found
|
||||
|
||||
|
||||
@@ -311,40 +236,38 @@ def gauges(tally: dict) -> dict[str, dict]:
|
||||
found = {key: {"value": rounded(mean(tally[key], 1), 1)} for key in HOST}
|
||||
found["vram"] = {"value": rounded(mean(tally["vram"], 1), 1), "used": rounded(mean(tally["vram"], 2), 0)}
|
||||
found["disk"] = fullest(tally["disks"])
|
||||
return {key: {**entry, "approx": False, "source": None} for key, entry in found.items()}
|
||||
return {key: {**entry, "approx": False} for key, entry in found.items()}
|
||||
|
||||
|
||||
def rated(council: Path, kept: Path, now: float) -> dict:
|
||||
def rated(council: Path, kept: Path, now: float, window: tuple[float, float]) -> dict:
|
||||
"""Args:
|
||||
council: the council directory holding the register and the score
|
||||
journal, read through scores.journal().
|
||||
kept: the directory holding the host sampler's resources folder.
|
||||
now: the end of every window in epoch seconds.
|
||||
now: the present in epoch seconds; the current token hour ends here.
|
||||
window: (begin, end) the rates cover, end at most now.
|
||||
|
||||
Returns:
|
||||
{"now", "since", "periods", "rates"}: since the first time any record
|
||||
holds; periods [{name, seconds}], total without seconds; rates per
|
||||
period per metric {value, approx, source}: the done tasks, the
|
||||
commits, the key results met and the tokens inside the window ending
|
||||
now, extrapolated() where it holds none or, for tokens, where it
|
||||
reaches back before the first token row, and the gauges() of the
|
||||
samples inside it; total spans every record.
|
||||
{"now", "since", "from", "to", "periods", "rates"}: since the first
|
||||
time any record holds; periods [{name, seconds}], total without
|
||||
seconds; rates per period per metric: counted() of the done tasks,
|
||||
the commits, the key results met and the tokens, each kind covered
|
||||
from since on, tokens from their first row, and the gauges() of the
|
||||
samples inside the window, the same in every period.
|
||||
"""
|
||||
tasks = read_register(council / REGISTER)
|
||||
folder = kept / RESOURCES
|
||||
items = sorted(filter(None, map(placed, rows_between(folder / SAMPLES, 0, now, 0))), key=lambda item: item[0], reverse=True)
|
||||
counted = {
|
||||
items = list(filter(None, map(placed, rows_between(folder / SAMPLES, 0, now, 0))))
|
||||
pieces = {
|
||||
"tasks": points(task_times(tasks)),
|
||||
"commits": points(commit_times(journal(council))),
|
||||
"krs": points(kr_times(tasks)),
|
||||
"tokens": token_pieces(rows_between(folder / TOKENS, 0, now, HOUR), now),
|
||||
}
|
||||
starts = {kind: [piece[0] for piece in pieces if piece[0] is not None] for kind, pieces in counted.items()}
|
||||
times = [*(t for found in starts.values() for t in found), *(item[0] for item in items)]
|
||||
since = min(times) if times else None
|
||||
length = lengths(now, since)
|
||||
begins = {"tokens": min(starts["tokens"], default=None)}
|
||||
counts = {kind: extrapolated(sums(pieces, now, FINEST.get(kind, 0)), length, held(now, since, begins.get(kind))) for kind, pieces in counted.items()}
|
||||
measured = tallies(items, [-math.inf if seconds is None else now - seconds for _, seconds in PERIODS])
|
||||
shown = {name: {**{kind: counts[kind][name] for kind in COUNTS}, **gauges(tally)} for name, tally in zip(PERIOD_NAMES, measured, strict=True)}
|
||||
return {"now": now, "since": since, "periods": [{"name": name, "seconds": seconds} for name, seconds in PERIODS], "rates": shown}
|
||||
starts = {kind: [piece[0] for piece in found if piece[0] is not None] for kind, found in pieces.items()}
|
||||
since = min([*(t for found in starts.values() for t in found), *(item[0] for item in items)], default=None)
|
||||
firsts = {**dict.fromkeys(COUNTS, since), "tokens": min(starts["tokens"], default=None)}
|
||||
counts = {kind: counted(found, window, firsts[kind], FINEST[kind]) for kind, found in pieces.items()}
|
||||
measured = gauges(tally(items, window))
|
||||
shown = {name: {**{kind: counts[kind][name] for kind in COUNTS}, **measured} for name in PERIOD_NAMES}
|
||||
return {"now": now, "since": since, "from": window[0], "to": window[1], "periods": [{"name": name, "seconds": seconds} for name, seconds in PERIODS], "rates": shown}
|
||||
@@ -50,7 +50,7 @@ SETTINGS = {
|
||||
"bubbles": False,
|
||||
"rates": {"period": "hour", "metrics": ["tasks", "tokens", "cpu"]},
|
||||
}
|
||||
RATE_CHIP = (2, 3)
|
||||
RATE_CHIP = (2, 9)
|
||||
SPACE_AXES = ("none", "time", "spawn")
|
||||
SPACE_LIMITS = {
|
||||
"graph": {"yaw": (-180.0, 180.0), "pitch": (-90.0, 90.0), "zoom": (0.25, 4.0), "pan_x": (-2000.0, 2000.0), "pan_y": (-2000.0, 2000.0)},
|
||||
|
||||
@@ -466,7 +466,6 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
||||
<div class="navbar">
|
||||
<nav class="tabs" id="tabs" aria-label="Navigation"></nav>
|
||||
<span class="spacer"></span>
|
||||
<details class="menu" id="time"></details>
|
||||
<span class="updated" id="updated" aria-live="polite"></span>
|
||||
<div class="rates" id="rates"></div>
|
||||
</div>
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
syncBubbles();
|
||||
syncMusic();
|
||||
syncRadio();
|
||||
timeBar();
|
||||
ratesBar();
|
||||
notifyLabel();
|
||||
announce();
|
||||
measure();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
const ACTIVE_BEAT = 900;
|
||||
const DAY = 86400;
|
||||
const HUMAN = "Operator";
|
||||
const PRESETS = [[3600, "1 h"], [21600, "6 h"], [DAY, "24 h"], [7 * DAY, "7 d"], [0, "all"], [-1, "custom"]];
|
||||
const PRESETS = [[3600, "1 h"], [21600, "6 h"], [DAY, "24 h"], [7 * DAY, "7 d"], [0, "all"]];
|
||||
const PARTS = [["user", "User"], ["assistant", "Assistant"], ["tool_call", "Tool call"], ["tool_result", "Tool result"], ["system", "System"]];
|
||||
const PART_TONES = {user: "info", assistant: "ok", tool_call: "violet", tool_result: "teal", system: "neutral"};
|
||||
const KIND_TONES = {radio: "teal", review: "info", ask: "warn", decision: "violet", operator: "bad", register: "neutral", rename: "info", cron: "teal", rule: "ok", approval: "ok", run: "info", transcript: "neutral"};
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
const counter = (value) => h("span", {class: "count"}, String(value));
|
||||
const meta = (pairs) => h("dl", {class: "meta"}, pairs.map(([label, value, title]) => h("div", {}, h("dt", {}, label), h("dd", {}, h("code", {title: title ? revealed(title) : null}, revealed(dash(value)))))));
|
||||
const emptyState = (title, text) => h("div", {class: "empty"}, h("div", {class: "empty-mark", "aria-hidden": "true"}), h("h2", {}, title), h("p", {}, text));
|
||||
const live = () => ui.preset !== -1 && ui.asOf === null;
|
||||
const live = () => ui.asOf === null;
|
||||
const alarmRows = () => state.radio.filter((row) => (row.class === "mayday" || row.class === "pan-pan") && row.ts >= state.alarm_since).reverse();
|
||||
const keyOf = (item) => `${item.kind}:${item.id}`;
|
||||
const visibleInbox = () => state.inbox.filter((item) => ui.snoozed || !item.until);
|
||||
|
||||
@@ -23,9 +23,6 @@
|
||||
}
|
||||
|
||||
function windowKey() {
|
||||
if (ui.preset === -1) {
|
||||
return `custom:${ui.from}:${ui.to}`;
|
||||
}
|
||||
return `${ui.preset}:${ui.asOf === null ? "live" : ui.asOf}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
const RATES = {poll: 60, fewest: 2, most: 3};
|
||||
const RATES = {poll: 60, fewest: 2, most: 9};
|
||||
const RATE_PERIODS = [
|
||||
["minute", "min", "per minute"],
|
||||
["hour", "h", "per hour"],
|
||||
@@ -6,7 +6,7 @@
|
||||
["week", "wk", "per week"],
|
||||
["month", "mo", "per month of 30 days"],
|
||||
["year", "yr", "per year of 365 days"],
|
||||
["total", "all", "in total since records begin"],
|
||||
["total", "all", "in the whole window"],
|
||||
];
|
||||
const RATE_METRICS = [
|
||||
["tasks", "bi-check2-square", "Tasks done", "count"],
|
||||
@@ -20,7 +20,7 @@
|
||||
["disk", "bi-hdd", "Disk", "disk"],
|
||||
];
|
||||
const BYTE_UNITS = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"];
|
||||
const rateView = {data: null, dom: null, busy: false, at: -Infinity};
|
||||
const rateView = {data: null, dom: null, ticket: 0, at: -Infinity};
|
||||
const periodOf = (id) => RATE_PERIODS.find(([name]) => name === id) || RATE_PERIODS[1];
|
||||
const metricOf = (id) => RATE_METRICS.find(([name]) => name === id);
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
* @param entry - one metric of one period from /api/rates, or null before the first answer.
|
||||
* @param kind - the metric's kind: count, percent, vram or disk.
|
||||
* @param short - the period's short name a count is per, "" for none.
|
||||
* @returns the cell text: ≈ before an extrapolated count, n/a for a gauge without a sample.
|
||||
* @returns the cell text: ≈ before an estimated count, n/a without a record or sample in the window.
|
||||
*/
|
||||
function rateText(entry, kind, short) {
|
||||
if (!entry) {
|
||||
@@ -65,10 +65,11 @@
|
||||
return `${label} ${per}: loading`;
|
||||
}
|
||||
if (entry.value === null) {
|
||||
return `${label} ${per}: n/a, no sample in this window`;
|
||||
return `${label} ${per}: n/a, ${kind === "count" ? "no record of this kind reaches into the window" : "no sample in the window"}`;
|
||||
}
|
||||
const source = entry.source === "total" ? "all records of this kind" : `the last ${entry.source}`;
|
||||
const scaled = entry.approx ? `; ≈ none in this window or its records begin later, scaled from ${source}` : "";
|
||||
const length = rateView.data.to - rateView.data.from;
|
||||
const covered = entry.covered !== null && entry.covered < length - 1;
|
||||
const scaled = !entry.approx ? "" : covered ? `; ≈ its records cover only the last ${spanName(entry.covered)} of the window, so the rate divides by that part` : "; ≈ the window is shorter than the hour tokens are counted in";
|
||||
const where = id === "disk" ? ` on ${entry.mount}, ${bytesText(entry.used)} of ${bytesText(entry.total)}` : "";
|
||||
const mean = kind === "count" ? "" : " on average";
|
||||
return `${label} ${per}: ${rateText(entry, kind, "")}${mean}${where}${scaled}`;
|
||||
@@ -76,18 +77,19 @@
|
||||
|
||||
function ratesBar() {
|
||||
const host = document.getElementById("rates");
|
||||
const period = h("select", {class: "field rates-period", ...named("Rate period", "Rate period: the window the chip counts over"), on: {change: (event) => chooseRates({...settings.rates, period: event.target.value})}},
|
||||
RATE_PERIODS.map(([id, short, per]) => h("option", {value: id, title: per}, short)));
|
||||
const chip = h("summary", {class: "rates-chip"});
|
||||
const units = h("div", {class: "segmented rates-units", role: "group", "aria-label": "Rate unit"},
|
||||
RATE_PERIODS.map(([id, short, per]) => h("button", {type: "button", "data-period": id, title: per, on: {click: () => chooseRates({...settings.rates, period: id})}}, short)));
|
||||
const body = h("tbody", {});
|
||||
const head = h("tr", {}, h("th", {scope: "col"}, "Metric"), h("th", {scope: "col", title: "Shown in the chip"}, "Chip"), RATE_PERIODS.map(([id, short, per]) => h("th", {scope: "col", "data-period": id, title: per}, short)));
|
||||
const box = h("div", {class: "menu-box end rates-box", role: "group", "aria-label": "Rates per period"},
|
||||
h("h3", {}, "Rates per period"),
|
||||
h("h3", {}, "Rates per period"), ...timeSection(), h("h3", {}, "Unit"), units,
|
||||
h("div", {class: "rates-scroll"}, h("table", {class: "rates-table"}, h("thead", {}, head), body)),
|
||||
h("p", {class: "muted"}, `≈ means an estimate: none in the window, so the shortest longer window that holds any, scaled down, or a window reaching back before the records of its kind begin, scaled from those records. n/a means no sample in the window. Total counts since records begin; the gauges average over the window. The chip shows ${RATES.fewest} to ${RATES.most} metrics.`));
|
||||
h("p", {class: "muted"}, `Every column rates the chosen window: a count is its sum per unit, all the sum itself; a gauge averages over the window. ≈ means the records of a kind begin inside the window, so the rate divides by the part they cover, or the window is shorter than the hour tokens are counted in. n/a means no record or sample in the window. The chip shows ${RATES.fewest} to ${RATES.most} metrics.`));
|
||||
const menu = h("details", {class: "menu rates-menu"}, chip, box);
|
||||
host.replaceChildren(period, menu);
|
||||
rateView.dom = {period, chip, body, menu};
|
||||
host.replaceChildren(menu);
|
||||
rateView.dom = {chip, units, body, menu};
|
||||
window.addEventListener("resize", () => fitChip(chip));
|
||||
}
|
||||
|
||||
function rateCell(metric, period, chosen) {
|
||||
@@ -105,6 +107,23 @@
|
||||
return h("tr", {"data-metric": id}, h("th", {scope: "row"}, icon(name), ` ${label}`), h("td", {}, pick), RATE_PERIODS.map((period) => rateCell(metric, period, chosen)));
|
||||
}
|
||||
|
||||
function fitChip(chip) {
|
||||
const shown = [...chip.querySelectorAll(".rate")];
|
||||
const more = chip.querySelector(".rate-more");
|
||||
if (!more) {
|
||||
return;
|
||||
}
|
||||
shown.forEach((node) => {
|
||||
node.hidden = false;
|
||||
});
|
||||
more.hidden = true;
|
||||
for (let kept = shown.length; kept > 1 && chip.scrollWidth > chip.clientWidth; kept -= 1) {
|
||||
shown[kept - 1].hidden = true;
|
||||
more.hidden = false;
|
||||
more.textContent = `+${shown.length - kept + 1}`;
|
||||
}
|
||||
}
|
||||
|
||||
function drawRates() {
|
||||
const dom = rateView.dom;
|
||||
if (!dom) {
|
||||
@@ -114,11 +133,16 @@
|
||||
const period = periodOf(chosen.period);
|
||||
const short = period[0] === "total" ? "" : period[1];
|
||||
const entries = chosen.metrics.map((id) => [metricOf(id), rateView.data ? rateView.data.rates[period[0]][id] : null]);
|
||||
dom.period.value = period[0];
|
||||
dom.chip.replaceChildren(...entries.map(([metric, entry]) => h("span", {class: "rate", "data-metric": metric[0], "data-approx": String(Boolean(entry && entry.approx)), title: rateHint(entry, metric, period)},
|
||||
icon(metric[1]), h("span", {class: "rate-value"}, rateText(entry, metric[3], metric[3] === "count" ? short : "")))), caret());
|
||||
dom.chip.setAttribute("aria-label", `Rates ${period[2]}: ${entries.map(([metric, entry]) => `${metric[2]} ${rateText(entry, metric[3], "")}`).join(", ")}`);
|
||||
dom.chip.title = "Rates: every metric per period";
|
||||
for (const button of dom.units.children) {
|
||||
button.setAttribute("aria-pressed", String(button.dataset.period === period[0]));
|
||||
}
|
||||
dom.chip.replaceChildren(h("span", {class: "rate-window"}, `${windowName()} · ${short ? `/${short}` : "all"}`),
|
||||
...entries.map(([metric, entry]) => h("span", {class: "rate", "data-metric": metric[0], "data-approx": String(Boolean(entry && entry.approx)), title: rateHint(entry, metric, period)},
|
||||
icon(metric[1]), h("span", {class: "rate-value"}, rateText(entry, metric[3], metric[3] === "count" ? short : "")))),
|
||||
h("span", {class: "rate-more", hidden: true}), caret());
|
||||
dom.chip.setAttribute("aria-label", `Rates ${period[2]} over ${windowName()}: ${entries.map(([metric, entry]) => `${metric[2]} ${rateText(entry, metric[3], "")}`).join(", ")}`);
|
||||
dom.chip.title = "Rates per period: time range, replay, unit and every metric";
|
||||
fitChip(dom.chip);
|
||||
const focused = document.activeElement instanceof Element ? document.activeElement.closest("#rates tr[data-metric]") : null;
|
||||
dom.body.replaceChildren(...RATE_METRICS.map((metric) => rateRow(metric, chosen)));
|
||||
const again = focused ? dom.body.querySelector(`tr[data-metric="${focused.dataset.metric}"] input`) : null;
|
||||
@@ -134,26 +158,22 @@
|
||||
}
|
||||
|
||||
async function fetchRates() {
|
||||
rateView.busy = true;
|
||||
rateView.ticket += 1;
|
||||
const ticket = rateView.ticket;
|
||||
rateView.at = nowSeconds();
|
||||
try {
|
||||
const response = await fetch("/api/rates", {cache: "no-store"});
|
||||
if (response.ok) {
|
||||
const response = await fetch(`/api/rates?${windowQuery()}`, {cache: "no-store"});
|
||||
if (response.ok && ticket === rateView.ticket) {
|
||||
rateView.data = await response.json();
|
||||
}
|
||||
} catch {
|
||||
ui.offline = true;
|
||||
}
|
||||
rateView.at = nowSeconds();
|
||||
rateView.busy = false;
|
||||
drawRates();
|
||||
}
|
||||
|
||||
function pollRates() {
|
||||
if (!rateView.dom) {
|
||||
ratesBar();
|
||||
drawRates();
|
||||
}
|
||||
if (!document.hidden && !rateView.busy && nowSeconds() - rateView.at >= RATES.poll) {
|
||||
if (!document.hidden && nowSeconds() - rateView.at >= RATES.poll) {
|
||||
fetchRates();
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
};
|
||||
const RESOURCE_BURN = {done: "Done", scope: "Scope"};
|
||||
const resourceView = {data: null, dom: null, busy: false, key: "", at: 0, timer: 0, series: {}};
|
||||
const resourceKey = () => JSON.stringify([ui.preset, ui.from, ui.to, ui.asOf]);
|
||||
const resourceKey = () => JSON.stringify([ui.preset, ui.asOf]);
|
||||
const resourcesStale = () => resourceKey() !== resourceView.key || nowSeconds() - resourceView.at >= RESOURCE.stale;
|
||||
const compactCount = Resources.compact;
|
||||
const resourceLabel = (line) => (line.kind === "vram" ? `${line.name} VRAM` : line.name);
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
|
||||
let state = JSON.parse(document.getElementById("state").textContent);
|
||||
const KINDS = Object.entries(state.kinds);
|
||||
const ui = {screen: "stream", views: {agents: "orbit", artifacts: "tree", tasks: "list"}, preset: DAY, from: null, to: null, asOf: null, playing: false, busy: false, offline: false, agent: null, order: null, spot: false, nightOff: new Set(), cursor: 0, selected: new Set(), snoozed: false, review: null, file: 0};
|
||||
const ui = {screen: "stream", views: {agents: "orbit", artifacts: "tree", tasks: "list"}, preset: DAY, asOf: null, playing: false, busy: false, offline: false, agent: null, order: null, spot: false, nightOff: new Set(), cursor: 0, selected: new Set(), snoozed: false, review: null, file: 0};
|
||||
const filter = {view: "fuer-dich", saved: "", kinds: new Set(state.views["fuer-dich"].kinds), waiting: true, q: "", agent: "", session: "", sub: "", parts: new Set(PARTS.map(([id]) => id))};
|
||||
const stream = {key: null, events: [], entries: [], last: 0, sessions: {}, busy: false, again: false, dom: null, error: ""};
|
||||
const tree = {data: null, model: null, busy: false, q: "", open: new Set(), dom: null};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
const SPAN_STEPS = 1000;
|
||||
const SHORTEST = 60;
|
||||
|
||||
function windowQuery() {
|
||||
if (ui.preset === -1) {
|
||||
return `from=${Math.floor(ui.from)}&to=${Math.ceil(ui.to)}`;
|
||||
}
|
||||
const end = ui.asOf === null ? nowSeconds() : ui.asOf;
|
||||
const begin = ui.preset === 0 ? 0 : end - ui.preset;
|
||||
return `from=${Math.floor(begin)}${ui.asOf === null ? "" : `&to=${Math.ceil(end)}`}`;
|
||||
@@ -12,9 +12,34 @@
|
||||
return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
|
||||
};
|
||||
|
||||
function spanName(seconds) {
|
||||
if (seconds >= DAY) {
|
||||
return `${Math.round(seconds / DAY)} d`;
|
||||
}
|
||||
return seconds >= 3600 ? `${Math.round(seconds / 3600)} h` : `${Math.max(Math.round(seconds / 60), 1)} min`;
|
||||
}
|
||||
|
||||
function windowName() {
|
||||
const preset = PRESETS.find(([seconds]) => seconds === ui.preset);
|
||||
return `${preset ? preset[1] : spanName(ui.preset)}${ui.asOf === null ? "" : " · past"}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} begin the window's start in epoch seconds.
|
||||
* @param {number} end its end; at or after now the window is live and keeps its length.
|
||||
*/
|
||||
function setWindow(begin, end) {
|
||||
stopReplay();
|
||||
const now = nowSeconds();
|
||||
const stop = Math.min(end, now);
|
||||
ui.preset = Math.max(Math.round(stop - begin), SHORTEST);
|
||||
ui.asOf = end >= now ? null : stop;
|
||||
reload();
|
||||
}
|
||||
|
||||
function customRange() {
|
||||
const from = h("input", {type: "datetime-local", "aria-label": "From", value: localInput(ui.from === null ? state.since : ui.from)});
|
||||
const to = h("input", {type: "datetime-local", "aria-label": "To", value: localInput(ui.to === null ? state.until : ui.to)});
|
||||
const from = h("input", {type: "datetime-local", "aria-label": "From", value: localInput(state.since)});
|
||||
const to = h("input", {type: "datetime-local", "aria-label": "To", value: localInput(state.until)});
|
||||
return h("span", {class: "custom"}, from, h("span", {class: "muted"}, "to"), to,
|
||||
h("button", {type: "button", class: "btn small soft", on: {click: () => {
|
||||
const begin = Date.parse(from.value) / 1000;
|
||||
@@ -23,47 +48,45 @@
|
||||
toast("Time range invalid", ["“From” must come before “To”."], false);
|
||||
return;
|
||||
}
|
||||
stopReplay();
|
||||
ui.preset = -1;
|
||||
ui.from = begin;
|
||||
ui.to = end;
|
||||
reload();
|
||||
setWindow(begin, end);
|
||||
}}}, "Apply"));
|
||||
}
|
||||
|
||||
function timeBar() {
|
||||
const bar = document.getElementById("time");
|
||||
function spanSlider() {
|
||||
const [from, to] = ["from", "to"].map((end, index) => h("input", {type: "range", class: `span-${end}`, min: 0, max: SPAN_STEPS, step: 1, value: index * SPAN_STEPS, "aria-label": `Time range ${end}`}));
|
||||
const fill = h("span", {class: "span-fill", "aria-hidden": "true"});
|
||||
const at = (value) => state.first + (Math.max(state.now - state.first, 1) * Number(value)) / SPAN_STEPS;
|
||||
const moved = (event) => {
|
||||
if (Number(from.value) >= Number(to.value)) {
|
||||
event.target.value = String(event.target === from ? Number(to.value) - 1 : Number(from.value) + 1);
|
||||
}
|
||||
setWindow(at(from.value), Number(to.value) >= SPAN_STEPS ? nowSeconds() : at(to.value));
|
||||
};
|
||||
from.addEventListener("input", moved);
|
||||
to.addEventListener("input", moved);
|
||||
return {box: h("div", {class: "span-slider"}, fill, from, to), from, to, fill};
|
||||
}
|
||||
|
||||
function timeSection() {
|
||||
const presets = h("div", {class: "segmented", role: "group", "aria-label": "Time range"});
|
||||
const summary = h("summary", {title: "Time range and replay"});
|
||||
const slider = h("input", {type: "range", min: 0, max: 1000, step: 1, value: 1000, "aria-label": "Replay position"});
|
||||
const play = iconBtn("bi-play-fill", "Replay", "btn small soft", null);
|
||||
const liveButton = h("button", {type: "button", class: "btn small ghost"}, "Live");
|
||||
const label = h("span", {class: "window-label"});
|
||||
for (const [seconds, name] of PRESETS.filter(([seconds]) => seconds !== -1)) {
|
||||
for (const [seconds, name] of PRESETS) {
|
||||
presets.append(h("button", {type: "button", "data-preset": seconds, on: {click: () => choosePreset(seconds)}}, name));
|
||||
}
|
||||
slider.addEventListener("input", () => {
|
||||
stopReplay();
|
||||
const span = state.now - state.first;
|
||||
ui.asOf = Number(slider.value) >= 1000 ? null : state.first + (span * Number(slider.value)) / 1000;
|
||||
reload();
|
||||
});
|
||||
play.addEventListener("click", () => (ui.playing ? stopReplay() : startReplay()));
|
||||
liveButton.addEventListener("click", () => {
|
||||
const slider = spanSlider();
|
||||
const play = iconBtn("bi-play-fill", "Replay", "btn small soft", () => (ui.playing ? stopReplay() : startReplay()));
|
||||
const liveButton = h("button", {type: "button", class: "btn small ghost", on: {click: () => {
|
||||
stopReplay();
|
||||
ui.asOf = null;
|
||||
if (ui.preset === -1) {
|
||||
ui.preset = DAY;
|
||||
}
|
||||
reload();
|
||||
});
|
||||
bar.append(summary, h("div", {class: "menu-box end"}, h("h3", {}, "Time range"), presets, h("h3", {}, "Replay"), h("div", {class: "replay"}, play, slider, liveButton), label,
|
||||
h("p", {class: "muted"}, "Filter ▾ in the stream sets a custom time range.")));
|
||||
timeDom = {summary, presets, slider, play, live: liveButton, label};
|
||||
}}}, "Live");
|
||||
const label = h("span", {class: "window-label"});
|
||||
timeDom = {presets, from: slider.from, to: slider.to, fill: slider.fill, play, live: liveButton, label};
|
||||
return [h("h3", {}, "Time range"), presets, slider.box, h("div", {class: "replay"}, play, liveButton, label), customRange()];
|
||||
}
|
||||
|
||||
function reload() {
|
||||
load();
|
||||
fetchRates();
|
||||
if (ui.screen === "stream") {
|
||||
fetchEvents();
|
||||
}
|
||||
@@ -72,6 +95,7 @@
|
||||
function choosePreset(seconds) {
|
||||
stopReplay();
|
||||
ui.preset = seconds;
|
||||
ui.asOf = null;
|
||||
reload();
|
||||
}
|
||||
|
||||
@@ -80,27 +104,26 @@
|
||||
return;
|
||||
}
|
||||
for (const button of timeDom.presets.children) {
|
||||
button.setAttribute("aria-pressed", String(Number(button.dataset.preset) === ui.preset));
|
||||
button.setAttribute("aria-pressed", String(Number(button.dataset.preset) === ui.preset && ui.asOf === null));
|
||||
}
|
||||
timeDom.summary.textContent = `${(PRESETS.find(([seconds]) => seconds === ui.preset) || [0, "custom"])[1]}${ui.asOf === null ? "" : " · replay"} ▾`;
|
||||
timeDom.slider.disabled = ui.preset === -1;
|
||||
timeDom.play.disabled = ui.preset === -1;
|
||||
timeDom.live.disabled = live();
|
||||
const span = Math.max(state.now - state.first, 1);
|
||||
if (!ui.playing) {
|
||||
timeDom.slider.value = String(ui.asOf === null ? 1000 : Math.round((1000 * (ui.asOf - state.first)) / span));
|
||||
}
|
||||
const end = ui.asOf === null ? state.now : ui.asOf;
|
||||
const place = (t) => Math.min(Math.max(Math.round((SPAN_STEPS * (t - state.first)) / span), 0), SPAN_STEPS);
|
||||
const [low, high] = [place(ui.preset === 0 ? state.first : end - ui.preset), ui.asOf === null ? SPAN_STEPS : place(end)];
|
||||
timeDom.from.value = String(Math.min(low, high - 1));
|
||||
timeDom.to.value = String(high);
|
||||
timeDom.from.classList.toggle("on-top", low > SPAN_STEPS / 2);
|
||||
timeDom.fill.style.left = `${(100 * low) / SPAN_STEPS}%`;
|
||||
timeDom.fill.style.right = `${100 - (100 * high) / SPAN_STEPS}%`;
|
||||
timeDom.live.disabled = live();
|
||||
timeDom.label.textContent = `${absolute.format(stampOf(state.since))} – ${absolute.format(stampOf(state.until))}${live() ? " · live" : ""}`;
|
||||
}
|
||||
|
||||
function startReplay() {
|
||||
if (ui.preset === -1) {
|
||||
return;
|
||||
}
|
||||
const began = state.first;
|
||||
const began = state.first + (ui.preset === 0 ? 0 : ui.preset);
|
||||
const span = Math.max(state.now - began, 1);
|
||||
const resume = ui.asOf !== null && ui.asOf < state.now - 60;
|
||||
let progress = resume ? (ui.asOf - began) / span : 0;
|
||||
let progress = resume ? Math.max((ui.asOf - began) / span, 0) : 0;
|
||||
ui.playing = true;
|
||||
relabel(timeDom.play, "bi-pause-fill", "Pause");
|
||||
const advance = async () => {
|
||||
@@ -109,8 +132,8 @@
|
||||
}
|
||||
progress = Math.min(progress + 1 / 48, 1);
|
||||
ui.asOf = progress >= 1 ? null : began + span * progress;
|
||||
timeDom.slider.value = String(Math.round(progress * 1000));
|
||||
await load();
|
||||
fetchRates();
|
||||
if (ui.screen === "stream") {
|
||||
fetchEvents();
|
||||
}
|
||||
|
||||
@@ -1,12 +1,28 @@
|
||||
.rates { display: inline-flex; align-items: center; gap: 4px; min-width: 0; max-width: 100%; }
|
||||
.rates-period { padding: 3px 6px; border-radius: 999px; font-size: var(--fs-xs); }
|
||||
.rates-menu > summary.rates-chip { gap: 10px; padding: 3px 10px; border-radius: 999px; font-size: var(--fs-sm); font-weight: 560; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.rates-menu { min-width: 0; max-width: 100%; }
|
||||
.rates-menu > summary.rates-chip { gap: 10px; max-width: 100%; min-width: 0; padding: 3px 10px; overflow: hidden; border-radius: 999px; font-size: var(--fs-sm); font-weight: 560; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.rates-chip .rate { display: inline-flex; align-items: center; gap: 4px; }
|
||||
.rates-chip .rate[hidden], .rates-chip .rate-more[hidden] { display: none; }
|
||||
.rates-chip .rate-window, .rates-chip .rate-more { color: var(--muted); font-size: var(--fs-xs); }
|
||||
.rates-chip .bi { color: var(--muted); }
|
||||
.span-slider { position: relative; height: 28px; }
|
||||
.span-slider::before, .span-fill { position: absolute; top: 50%; height: 4px; margin-top: -2px; border-radius: 2px; content: ""; }
|
||||
.span-slider::before { right: 0; left: 0; background: var(--line); }
|
||||
.span-fill { background: var(--accent); }
|
||||
.span-slider input[type="range"] { position: absolute; inset: 0; width: 100%; height: 100%; margin: 0; background: none; pointer-events: none; appearance: none; -webkit-appearance: none; }
|
||||
.span-slider input[type="range"].on-top { z-index: 1; }
|
||||
.span-slider input[type="range"]::-webkit-slider-runnable-track { background: none; }
|
||||
.span-slider input[type="range"]::-moz-range-track { background: none; }
|
||||
.span-slider input[type="range"]::-webkit-slider-thumb { width: 18px; height: 18px; border: 2px solid var(--panel); border-radius: 50%; background: var(--accent); cursor: grab; pointer-events: auto; appearance: none; -webkit-appearance: none; }
|
||||
.span-slider input[type="range"]::-moz-range-thumb { width: 14px; height: 14px; border: 2px solid var(--panel); border-radius: 50%; background: var(--accent); cursor: grab; pointer-events: auto; }
|
||||
.span-slider input[type="range"]:focus-visible::-webkit-slider-thumb { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.span-slider input[type="range"]:focus-visible::-moz-range-thumb { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.rates-chip .rate[data-approx="true"] .rate-value, .rates-table td[data-approx="true"] { color: var(--muted); }
|
||||
.rates-box { max-width: min(1100px, calc(100vw - 32px)); }
|
||||
.rates-scroll { max-width: 100%; overflow-x: auto; }
|
||||
.rates-box > p { width: 0; min-width: 100%; margin: 0; }
|
||||
.rates-box .replay { flex-wrap: wrap; min-width: 0; }
|
||||
.rates-box .window-label { min-width: 0; white-space: normal; }
|
||||
.rates-table { border-collapse: collapse; font-size: var(--fs-sm); font-variant-numeric: tabular-nums; }
|
||||
.rates-table th, .rates-table td { padding: 3px 8px; border-bottom: 1px solid var(--line); text-align: right; white-space: nowrap; }
|
||||
.rates-table thead th { color: var(--muted); font-size: var(--fs-xs); font-weight: 650; }
|
||||
|
||||
Reference in new issue
Block a user