aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDanilo M. <danix@danix.xyz>2026-11-13 20:49:56 +0100
committerDanilo M. <danix@danix.xyz>2026-11-13 20:49:56 +0100
commit896163d7961d86b4e023a50ce4f6e19a30006a3f (patch)
tree9a2266a1120f8913616991d9350fa6667c248f0e
parent69e6ce2bf7272797cf08ee4fbe0ff9fe0fc3b1f4 (diff)
downloaddeck-it-896163d7961d86b4e023a50ce4f6e19a30006a3f.tar.gz
deck-it-896163d7961d86b4e023a50ce4f6e19a30006a3f.zip
feat(vm): tablet tiles with screen, trends and a power button
Each VM is a tile: its screen from virsh screenshot (JPEG through ffmpeg, every 5s while the tab shows), booting until sshd answers at the ssh -G host and port, CPU and RAM trends, and a big power button, tap for the gentle action and hold to force off. A tap on the tile opens a sheet with every action as an icon and the snapshots as a timeline with their age. hold.js is now the one press and hold, K1C's stop included, and vibrates the tablet when it fires; the Windows long-press buzzes too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-rw-r--r--AGENTS.md11
-rw-r--r--README.md10
-rw-r--r--deckit/modules/vm.py97
-rw-r--r--docs/superpowers/specs/2026-11-13-vm-tab-design.md15
-rw-r--r--static/deck.css63
-rw-r--r--static/hold.js46
-rw-r--r--static/modules/k1c.js27
-rw-r--r--static/modules/vm.js333
-rw-r--r--static/modules/windows.js4
-rw-r--r--tests/test_vm.py38
10 files changed, 492 insertions, 152 deletions
diff --git a/AGENTS.md b/AGENTS.md
index 22ce6f5..e7358e8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -74,7 +74,16 @@ Keep the server dependency-free apart from that one package.
thread every 10s and after an action. A vm or snapshot name must be one
the last state listed. `ssh` opens `ssh <vm>` as a tab in the first
`$XDG_RUNTIME_DIR/kitty-<pid>` that answers `kitty @` and focuses it,
- else spawns kitty. Destructive buttons are press and hold.
+ else spawns kitty. `ready` is sshd answering at `ssh -G <vm>`'s host and
+ port (the agent IP when no alias), re-read every 2s for 5 min while a VM
+ boots. The tile's screen is `virsh screenshot` through ffmpeg at
+ `/api/vm/image/<vm>`, running VMs only. `vm.js`: a tile per VM (screen,
+ power: tap gentle, hold force; SSH; CPU/RAM trends from `dashboard.js`'s
+ `line`/`area`), a `<dialog closedby="any">` sheet with every action and
+ the snapshot timeline. Buttons are Nerd Font glyphs.
+- `static/hold.js` is the one press and hold (K1C stop, VM buttons): it
+ vibrates the tablet when it fires; `buzz()` also marks the Windows
+ long-press.
- `sbbuilder` has no tab, only a running slot. It reads `sbb-remote jobs
--active` (sb-builder 0.13.1+); a running build's `progress` (done of
total with dependencies, the package building, its ETA, the estimated end,
diff --git a/README.md b/README.md
index 1f371bf..228f1fe 100644
--- a/README.md
+++ b/README.md
@@ -71,10 +71,12 @@ launchers included, with a Restart button to apply a save.
- The K1C tab follows a Klipper printer through Moonraker (`[k1c] url`):
state, progress with the slicer's model preview, temperatures, camera, and
a red emergency stop that fires on a press and hold.
-- The VMs tab manages libvirt's `qemu:///system` VMs: state, CPU and
- memory, start, shutdown, reboot, suspend, snapshots (take, revert,
- delete), and SSH, a tab in a running kitty or a new one. Force stop,
- reset, revert and delete fire on a press and hold. SSH connects to the
+- The VMs tab shows libvirt's `qemu:///system` VMs as tiles: the VM's
+ screen, CPU and RAM trends, "booting…" until sshd answers, a big power
+ button (tap to start or shut down, hold to force off) and SSH, a tab in a
+ running kitty or a new one. A tap on the tile opens every action and the
+ snapshot timeline (take, revert, delete). Destructive buttons fire on a
+ press and hold, and the tablet buzzes when they do. SSH connects to the
VM's name, so give each VM an `~/.ssh/config` alias.
- The Assistant tab talks to desktop-assistant: tap the mic to ask,
pick the model, and use the canvas's Ask presets and Do ops on a file you
diff --git a/deckit/modules/vm.py b/deckit/modules/vm.py
index 772e7b9..ae915b3 100644
--- a/deckit/modules/vm.py
+++ b/deckit/modules/vm.py
@@ -17,23 +17,28 @@
"""The VMs on libvirt's default connection (qemu:///system), through virsh.
`virsh domstats` gives every VM's state, CPU time and memory in one call each
-poll. The slower per-VM reads (managed save, snapshots, the guest agent's IP)
-run in a thread at most every SLOW seconds, and after any action, so the poll
-never waits on them. Shelling out to virsh, like keystone's drawer, adds no
-dependency.
+poll. The slower per-VM reads (managed save, snapshots, the guest agent's IP,
+whether sshd answers) run in a thread at most every SLOW seconds, BOOT while a
+VM is booting, and after any action, so the poll never waits on them. Shelling
+out to virsh, like keystone's drawer, adds no dependency.
"""
import os
import re
+import socket
import subprocess
+import tempfile
import threading
import time
+from datetime import datetime
from pathlib import Path
from ..module import Module, ModuleError
from .windows import hypr_lua
SLOW = 10
+BOOT = 2 # re-read this often while a running VM's sshd is not up yet
+BOOT_FOR = 300 # ...for this long after it was first seen booting
STATES = {1: "running", 2: "blocked", 3: "paused", 4: "shutting down",
5: "shut off", 6: "crashed", 7: "suspended"}
POWER = {
@@ -58,12 +63,21 @@ def _spawn(fn):
threading.Thread(target=fn, daemon=True).start()
+def _probe(host, port):
+ try:
+ socket.create_connection((host, port), timeout=1).close()
+ return True
+ except OSError:
+ return False
+
+
def parse_domstats(text: str) -> dict:
doms, cur = {}, None
for line in text.splitlines():
m = re.match(r"^Domain: '(.+)'$", line)
if m:
- cur = doms.setdefault(m[1], {"state": "unknown", "vcpus": 0, "ns": None, "mem": None})
+ cur = doms.setdefault(m[1], {"state": "unknown", "vcpus": 0, "ns": None, "mem": None,
+ "available": None, "usable": None})
continue
kv = line.strip().split("=", 1)
if cur is None or len(kv) != 2:
@@ -77,9 +91,20 @@ def parse_domstats(text: str) -> dict:
cur["ns"] = int(v)
elif k == "balloon.current":
cur["mem"] = int(v) * 1024
+ elif k in ("balloon.available", "balloon.usable"):
+ cur[k.split(".")[1]] = int(v) * 1024
return doms
+def parse_snapshots(table: str, current: str) -> list:
+ """`virsh snapshot-list`'s table, oldest first, with epoch creation times."""
+ snaps = []
+ for name, when in re.findall(r"^\s*(\S+)\s+(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d [+-]\d{4})", table, re.M):
+ created = int(datetime.strptime(when, "%Y-%m-%d %H:%M:%S %z").timestamp())
+ snaps.append({"name": name, "created": created, "current": name == current})
+ return sorted(snaps, key=lambda s: s["created"])
+
+
def _ip(text: str) -> str:
for addr in re.findall(r"\sipv4\s+(\d+\.\d+\.\d+\.\d+)/", text):
if not addr.startswith("127."):
@@ -92,22 +117,47 @@ def make(cfg: dict) -> Module:
clock = cfg.get("clock", time.monotonic)
spawn = cfg.get("spawn", _spawn)
popen = cfg.get("popen", _popen)
+ probe = cfg.get("probe", _probe)
runtime = cfg.get("runtime") or os.environ.get("XDG_RUNTIME_DIR", "/tmp")
lua = hypr_lua(cfg)
doms = {} # last domstats, by name
last = {} # name -> (cpu ns, at)
slow = {"at": float("-inf"), "busy": False, "data": {}}
+ booting = {} # name -> when first seen running without sshd
+ targets = {} # name -> (host, port) from `ssh -G`
+
+ def ssh_target(name, ip):
+ """An ssh alias named after the VM may move sshd off port 22, so host
+ and port come from `ssh -G`; with no alias it echoes the name back, and
+ the agent's address is used instead."""
+ if name not in targets:
+ out = run(["ssh", "-G", name]).stdout
+ host = re.search(r"^hostname (\S+)", out, re.M)
+ port = re.search(r"^port (\d+)", out, re.M)
+ targets[name] = (host[1] if host else name, int(port[1]) if port else 22)
+ host, port = targets[name]
+ return (ip if host == name else host), port
def read_slow():
data = {}
for name, d in list(doms.items()):
info = run(["virsh", "dominfo", name]).stdout
- snaps = run(["virsh", "snapshot-list", name, "--name"]).stdout
- ip = _ip(run(["virsh", "domifaddr", name, "--source", "agent"]).stdout) \
- if d["state"] == "running" else ""
+ current = run(["virsh", "snapshot-current", "--name", name])
+ snaps = parse_snapshots(run(["virsh", "snapshot-list", name]).stdout,
+ current.stdout.strip() if current.returncode == 0 else "")
+ ip, ready = "", None
+ if d["state"] == "running":
+ ip = _ip(run(["virsh", "domifaddr", name, "--source", "agent"]).stdout)
+ host, port = ssh_target(name, ip)
+ ready = bool(host) and probe(host, port)
+ if ready:
+ booting.pop(name, None)
+ else:
+ booting.setdefault(name, clock())
+ else:
+ booting.pop(name, None)
data[name] = {"saved": bool(re.search(r"^Managed save:\s+yes$", info, re.M)),
- "snapshots": [s.strip() for s in snaps.splitlines() if s.strip()],
- "ip": ip}
+ "snapshots": snaps, "ip": ip, "ready": ready}
slow["data"] = data
slow["busy"] = False
@@ -122,7 +172,8 @@ def make(cfg: dict) -> Module:
return {"offline": True, "reason": (p.stderr or "").strip()}
doms.clear()
doms.update(parse_domstats(p.stdout))
- if clock() - slow["at"] >= SLOW:
+ boot = any(clock() - t < BOOT_FOR for t in booting.values())
+ if clock() - slow["at"] >= (BOOT if boot else SLOW):
kick()
now, vms = clock(), []
for name, d in sorted(doms.items()):
@@ -134,9 +185,11 @@ def make(cfg: dict) -> Module:
/ (d["vcpus"] or 1) * 100))
last[name] = (d["ns"], now)
extra = slow["data"].get(name, {})
+ used = d["available"] - d["usable"] if d["available"] and d["usable"] is not None else None
vms.append({"name": name, "state": d["state"], "vcpus": d["vcpus"], "cpu": cpu,
- "mem": d["mem"], "ip": extra.get("ip", ""), "saved": extra.get("saved", False),
- "snapshots": extra.get("snapshots", [])})
+ "mem": d["mem"], "used": used, "ip": extra.get("ip", ""),
+ "ready": extra.get("ready") if d["state"] == "running" else None,
+ "saved": extra.get("saved", False), "snapshots": extra.get("snapshots", [])})
return {"offline": False, "vms": vms}
def virsh(*args, timeout=120):
@@ -152,7 +205,7 @@ def make(cfg: dict) -> Module:
if not snap:
return name, None
s = str(body.get("snap", ""))
- if s not in slow["data"].get(name, {}).get("snapshots", []):
+ if s not in [x["name"] for x in slow["data"].get(name, {}).get("snapshots", [])]:
raise ModuleError(f"unknown snapshot: {s}")
return name, s
@@ -182,6 +235,20 @@ def make(cfg: dict) -> Module:
return
popen(["kitty", "ssh", name])
+ def image(key):
+ """The VM's display, as a small JPEG; only a running VM the last state listed."""
+ if doms.get(key, {}).get("state") != "running":
+ return None
+ with tempfile.TemporaryDirectory() as d:
+ raw, jpg = f"{d}/screen", f"{d}/screen.jpg"
+ if run(["virsh", "screenshot", key, "--file", raw], timeout=5).returncode != 0:
+ return None
+ run(["ffmpeg", "-v", "error", "-i", raw, "-vf", "scale=640:-2", "-q:v", "5", "-y", jpg], timeout=5)
+ try:
+ return Path(jpg).read_bytes(), "image/jpeg"
+ except OSError:
+ return None
+
actions = {verb: power(verb) for verb in POWER}
actions.update(snapshot=snapshot, revert=revert, snapdelete=snapdelete, ssh=ssh)
- return Module(name="vm", title="VMs", state=state, actions=actions)
+ return Module(name="vm", title="VMs", state=state, actions=actions, image=image)
diff --git a/docs/superpowers/specs/2026-11-13-vm-tab-design.md b/docs/superpowers/specs/2026-11-13-vm-tab-design.md
index b327f7a..4a90f05 100644
--- a/docs/superpowers/specs/2026-11-13-vm-tab-design.md
+++ b/docs/superpowers/specs/2026-11-13-vm-tab-design.md
@@ -48,3 +48,18 @@ Docker, a dashboard chip. Add when wanted.
`tests/test_vm.py`: domstats parsing, CPU delta, action validation, the ssh
command choice. `node --check static/modules/vm.js`.
+
+## Tablet UI (second pass)
+
+The first panel copied the drawer row for row. The tab now is a grid of
+tiles: the VM's screen (`virsh screenshot`, JPEG via ffmpeg, every 5s while
+the tab shows), name and status ("booting…" until sshd answers at the
+`ssh -G` host and port, then "ssh ready · IP"), CPU and RAM trends drawn
+with the dashboard's `line`/`area`, and a bar with a big power button (tap:
+start, shut down or resume; hold: force stop), SSH and a "more" button. A
+tap on the tile opens a sheet (`<dialog closedby="any">`) with every action
+as an icon, and the snapshots as a timeline of chips with their age, the
+current one marked; a tapped chip shows its revert and delete. RAM used is
+`balloon.available - balloon.usable` when the balloon reports it.
+`static/hold.js` is now the one press and hold, used by K1C too, and
+vibrates the tablet when it fires.
diff --git a/static/deck.css b/static/deck.css
index c316ff3..9f44eb1 100644
--- a/static/deck.css
+++ b/static/deck.css
@@ -813,23 +813,56 @@ select {
animation: border-rotate 3s linear infinite;
}
-/* VMs tab. Destructive buttons are press and hold, filled over --hold. */
-.vm-list { display: flex; flex-direction: column; gap: 12px; padding: 4px 2px; }
-.vm-list[hidden], .vm-off[hidden], .vm-use[hidden], .vm-err[hidden] { display: none; }
-.vm-card { display: flex; flex-direction: column; gap: 10px; padding: 12px 14px; border-radius: 12px; background: var(--udt-surface0); }
-.vm-card.busy { opacity: .6; pointer-events: none; }
-.vm-head { display: flex; align-items: center; gap: 12px; }
-.vm-name { font-size: 1.286rem; font-weight: 600; }
+/* VMs tab: a tile per VM, its screen on top, a big power button below.
+ Hold buttons fill red over --hold (hold.js). Controls are 56px or more. */
+.vm-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 14px; padding: 4px 2px; }
+.vm-grid[hidden], .vm-off[hidden], .vm-err[hidden], .vm-snapacts[hidden], .vm-screen img[hidden] { display: none; }
+.vm-grid.empty::before { content: "No VMs defined."; color: var(--udt-subtext0); }
+.vm-tile, .vm-sheet { display: flex; flex-direction: column; gap: 10px; }
+.vm-tile { padding: 12px; border-radius: 16px; background: var(--udt-surface0); border: 2px solid transparent; }
+.vm-tile.on { border-color: var(--udt-border-1); }
+.vm-tile.busy, .vm-sheet.busy { opacity: .6; pointer-events: none; }
+.vm-screen { position: relative; aspect-ratio: 16 / 10; border-radius: 10px; background: var(--udt-crust);
+ display: grid; place-items: center; overflow: hidden; }
+.vm-screen img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; }
+.vm-glyph { font-size: 4rem; color: var(--udt-surface2); }
+.vm-screen .vm-state { position: absolute; top: 8px; left: 8px; }
.vm-state { padding: 2px 10px; border-radius: 999px; background: var(--udt-surface2); font-size: 0.857rem; }
.vm-state.good { background: var(--udt-green); color: var(--udt-crust); }
.vm-state.warn { background: var(--udt-yellow); color: var(--udt-crust); }
.vm-state.bad { background: var(--udt-red); color: var(--udt-crust); }
-.vm-ip { margin-left: auto; color: var(--udt-subtext0); }
-.vm-use { display: grid; grid-template-columns: auto 1fr auto auto auto; align-items: center; gap: 10px; }
+.vm-info { display: flex; align-items: baseline; gap: 10px; min-width: 0; }
+.vm-name { font-size: 1.286rem; }
+.vm-status { color: var(--udt-subtext0); font-size: 0.857rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.vm-trends { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
+.vm-trend { position: relative; height: 54px; border-radius: 10px; background: var(--udt-surface1); overflow: hidden;
+ display: flex; align-items: flex-end; justify-content: space-between; padding: 4px 8px; }
+.vm-trend svg { position: absolute; inset: 0; width: 100%; height: 100%; }
+.vm-trend path.hy { fill: url(#vmfill); }
+.vm-trend path.hy.ln { fill: none; stroke: url(#vmline); stroke-width: 2; vector-effect: non-scaling-stroke; }
+.vm-trend .k, .vm-snaphead .k { position: relative; font-size: 0.714rem; text-transform: uppercase; letter-spacing: .08em; color: var(--udt-overlay0); }
+.vm-trend .v { position: relative; font-weight: 600; }
.vm-err { color: var(--udt-red); font-size: 0.857rem; }
-.vm-acts { margin-bottom: 0; }
-.vm-snap { display: flex; align-items: center; gap: 8px; padding: 4px 0; border-top: 1px solid var(--udt-surface1); }
-.vm-snap > span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
-.vm .hold { position: relative; overflow: hidden; isolation: isolate; border-color: var(--udt-red); touch-action: none; }
-.vm .hold::before { content: ""; position: absolute; inset: 0; z-index: -1; background: var(--udt-red); transform: scaleX(0); transform-origin: left; }
-.vm .hold.holding::before { transform: scaleX(1); transition: transform var(--hold, 800ms) linear; }
+.vm-bar { display: flex; align-items: center; gap: 12px; }
+.vm .ib, .vm-sheet .ib { min-width: 56px; min-height: 56px; font-size: 1.5rem; border-radius: 14px; padding: 0 12px; }
+.vm-more { margin-left: auto; }
+.vm-power { width: 72px; height: 72px; border-radius: 50%; font-size: 2rem; padding: 0; }
+.vm-power.go { background: color-mix(in srgb, var(--udt-green) 30%, transparent); border-color: var(--udt-green); }
+.vm-sshb.ready { border-color: var(--udt-accent); color: var(--udt-accent); }
+.vm .hold, .vm-sheet .hold { position: relative; overflow: hidden; isolation: isolate; touch-action: none; }
+.vm .hold:not(.vm-power), .vm-sheet .hold { border-color: var(--udt-red); }
+.vm .hold::before, .vm-sheet .hold::before { content: ""; position: absolute; inset: 0; z-index: -1; background: var(--udt-red);
+ transform: scaleX(0); transform-origin: left; }
+.vm .hold.holding::before, .vm-sheet .hold.holding::before { transform: scaleX(1); transition: transform var(--hold, 800ms) linear; }
+dialog.vm-sheet { margin: auto; width: min(760px, 92vw); max-height: 85vh; overflow-y: auto; overscroll-behavior: contain;
+ padding: 18px; border: 0; border-radius: 18px; background: var(--udt-base); color: var(--udt-text); }
+dialog.vm-sheet:not([open]) { display: none; }
+dialog.vm-sheet::backdrop { background: color-mix(in srgb, var(--udt-crust) 55%, transparent); }
+.vm-acts, .vm-snapacts { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
+.vm-snaphead { display: flex; align-items: center; justify-content: space-between; margin-top: 6px; }
+.vm-timeline { display: flex; gap: 10px; overflow-x: auto; padding-bottom: 4px; color: var(--udt-subtext0); }
+.vm-snap { flex: none; display: flex; flex-direction: column; align-items: flex-start; gap: 2px; min-height: 56px; }
+.vm-snap span { font-size: 0.786rem; color: var(--udt-subtext0); }
+.vm-snap.current { border-color: var(--udt-accent); }
+.vm-snap.on { background: var(--udt-surface2); }
+.vm-snapname { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
diff --git a/static/hold.js b/static/hold.js
new file mode 100644
index 0000000..e937a25
--- /dev/null
+++ b/static/hold.js
@@ -0,0 +1,46 @@
+// deck-it - press and hold, for buttons a stray touch must not fire
+// Copyright (C) 2026 Danilo M. <danix@danix.xyz>
+//
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License version 2 as
+// published by the Free Software Foundation.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+export const HOLD_MS = 800;
+
+// The tablet buzzes when a hold fires (or a long press opens a menu), so
+// the finger knows it can let go.
+export const buzz = () => navigator.vibrate?.(40);
+
+// fire runs after the button is held ms; releasing early cancels, and runs
+// tap instead when one is given. The button gets .holding meanwhile and
+// --hold for the CSS fill.
+export function hold(btn, fire, { ms = HOLD_MS, tap } = {}) {
+ let timer = null;
+ const cancel = () => {
+ clearTimeout(timer);
+ timer = null;
+ btn.classList.remove("holding");
+ };
+ btn.style.setProperty("--hold", `${ms}ms`);
+ btn.addEventListener("pointerdown", (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ btn.setPointerCapture(e.pointerId);
+ btn.classList.add("holding");
+ timer = setTimeout(() => { cancel(); buzz(); fire(); }, ms);
+ });
+ btn.addEventListener("pointerup", () => {
+ if (timer && tap) tap();
+ cancel();
+ });
+ btn.addEventListener("pointercancel", cancel);
+}
diff --git a/static/modules/k1c.js b/static/modules/k1c.js
index 261ef4d..6b41a01 100644
--- a/static/modules/k1c.js
+++ b/static/modules/k1c.js
@@ -15,10 +15,11 @@
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import { offline } from "../offline.js";
+import { hold } from "../hold.js";
-// Holding the stop for this long fires it: fast in an emergency, but a
+// Holding the stop (hold.js's 800 ms) fires it: fast in an emergency, but a
// stray touch on an always-on tablet cannot kill a print.
-const HOLD_MS = 800;
+const armHold = (btn) => hold(btn, () => emergencyStop(btn));
const STATES = {
printing: ["Printing", "good"],
@@ -64,28 +65,6 @@ async function emergencyStop(btn) {
}, 4000);
}
-// Press and hold: the ring fills over HOLD_MS, releasing early cancels.
-function armHold(btn) {
- let timer = null;
- const cancel = () => {
- clearTimeout(timer);
- timer = null;
- btn.classList.remove("holding");
- };
- btn.addEventListener("pointerdown", (e) => {
- e.preventDefault();
- btn.setPointerCapture(e.pointerId);
- btn.classList.add("holding");
- timer = setTimeout(() => {
- cancel();
- emergencyStop(btn);
- }, HOLD_MS);
- });
- btn.addEventListener("pointerup", cancel);
- btn.addEventListener("pointercancel", cancel);
- btn.style.setProperty("--hold", `${HOLD_MS}ms`);
-}
-
// The dashboard's running slot: file, percent, time left, layer and
// temperatures, the press-and-hold stop and a progress bar. Wide slots show
// the slicer thumbnail in place of the icon (deck.css container query).
diff --git a/static/modules/vm.js b/static/modules/vm.js
index fdffd09..df68a07 100644
--- a/static/modules/vm.js
+++ b/static/modules/vm.js
@@ -15,135 +15,290 @@
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import { offline } from "../offline.js";
+import { hold } from "../hold.js";
+import { area, line, push } from "../dashboard.js";
-// Destructive actions fire only after a hold this long, so a stray touch on
-// an always-on tablet cannot force a VM off.
-const HOLD_MS = 800;
+// One tile per VM: its screen, a big power button (tap for the gentle
+// action, hold to force it off), SSH, and CPU/RAM trends. A tap on the tile
+// opens a sheet with every action and the snapshot timeline. Buttons are
+// Nerd Font glyphs; destructive ones fire only on a press and hold.
+const G = {
+ power: "", ssh: "", more: "", start: "", shutdown: "",
+ reboot: "", suspend: "", resume: "", reset: "", destroy: "",
+ discardsave: "", snapshot: "", revert: "", snapdelete: "", vm: "",
+};
+const LABEL = {
+ ssh: "SSH", start: "Start", shutdown: "Shut down", reboot: "Reboot", suspend: "Suspend",
+ resume: "Resume", reset: "Reset (hold)", destroy: "Force stop (hold)",
+ discardsave: "Discard saved state (hold)", snapshot: "Take a snapshot",
+ revert: "Revert to this snapshot (hold)", snapdelete: "Delete this snapshot (hold)",
+};
const HOLD = new Set(["reset", "destroy", "discardsave", "revert", "snapdelete"]);
const PILL = { running: "good", paused: "warn", suspended: "warn", "shutting down": "warn", crashed: "bad" };
+const SHOT = 5000; // the screen preview's refresh, ms
+const HIST = 90; // trend samples: three minutes at the 2 s poll
-// The buttons per state, as keystone's drawer offers them.
+// The sheet's buttons per state, as keystone's drawer offers them.
function actionsFor(st, saved) {
- if (st === "running")
- return [["ssh", "SSH"], ["shutdown", "Shutdown"], ["reboot", "Reboot"], ["suspend", "Suspend"],
- ["reset", "Reset"], ["destroy", "Force stop"]];
- if (st === "paused" || st === "suspended")
- return [["resume", "Resume"], ["shutdown", "Shutdown"], ["destroy", "Force stop"]];
- return saved ? [["start", "Start"], ["discardsave", "Discard saved state"]] : [["start", "Start"]];
+ if (st === "running") return ["ssh", "shutdown", "reboot", "suspend", "reset", "destroy"];
+ if (st === "paused" || st === "suspended") return ["resume", "shutdown", "destroy"];
+ if (st === "shutting down" || st === "crashed") return ["destroy"];
+ return saved ? ["start", "discardsave"] : ["start"];
+}
+
+// The tile's power button: [tap, hold]; either may be absent.
+function powerFor(st) {
+ if (st === "running") return ["shutdown", "destroy"];
+ if (st === "paused" || st === "suspended") return ["resume", "destroy"];
+ if (st === "shutting down" || st === "crashed") return [null, "destroy"];
+ return ["start", null];
}
-const gib = (b) => (b == null ? "—" : `${(b / 2 ** 30).toFixed(1)} GiB`);
+function ago(sec) {
+ const s = Math.max(0, Date.now() / 1000 - sec);
+ for (const [n, u] of [[31536000, "y"], [2592000, "mo"], [86400, "d"], [3600, "h"], [60, "min"]]) {
+ if (s >= n) return `${Math.floor(s / n)} ${u} ago`;
+ }
+ return "just now";
+}
+
+const gib = (b) => (b == null ? "—" : `${(b / 2 ** 30).toFixed(1)}`);
+
+function status(vm) {
+ if (vm.state === "running") {
+ if (vm.ready) return `ssh ready${vm.ip ? ` · ${vm.ip}` : ""}`;
+ return vm.ready === false ? "booting…" : vm.ip;
+ }
+ return vm.saved && vm.state === "shut off" ? "saved state, start restores it" : "";
+}
-async function post(action, body, card) {
- const err = card.querySelector(".vm-err");
- card.classList.add("busy");
+async function post(action, body, v) {
+ v.busy(true);
+ let msg = "";
try {
const r = await fetch(`/api/vm/${action}`, {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
});
- err.textContent = r.ok ? "" : (await r.text()) || r.statusText;
+ if (!r.ok) msg = (await r.text()) || r.statusText;
} catch (e) {
- err.textContent = String(e);
+ msg = String(e);
}
- err.hidden = !err.textContent;
- card.classList.remove("busy");
+ v.busy(false);
+ v.error(msg);
}
-function button(label, action, body, card) {
+function iconButton(action, body, v, cls = "") {
const b = document.createElement("button");
- b.textContent = label;
- const fire = () => post(action, body, card);
- if (!HOLD.has(action)) {
- b.onclick = fire;
- return b;
+ b.className = `ib nf ${cls}`;
+ b.textContent = G[action];
+ b.setAttribute("aria-label", LABEL[action]);
+ b.title = LABEL[action];
+ const fire = () => post(action, body, v);
+ if (HOLD.has(action)) {
+ b.classList.add("hold");
+ hold(b, fire);
+ } else {
+ b.addEventListener("click", (e) => { e.stopPropagation(); fire(); });
}
- // Press and hold: the fill grows over HOLD_MS, releasing early cancels.
- b.className = "hold";
- b.title = "Press and hold";
- b.style.setProperty("--hold", `${HOLD_MS}ms`);
- let timer = null;
- const cancel = () => { clearTimeout(timer); b.classList.remove("holding"); };
- b.addEventListener("pointerdown", (e) => {
- e.preventDefault();
- b.setPointerCapture(e.pointerId);
- b.classList.add("holding");
- timer = setTimeout(() => { cancel(); fire(); }, HOLD_MS);
- });
- b.addEventListener("pointerup", cancel);
- b.addEventListener("pointercancel", cancel);
return b;
}
-function card() {
- const c = document.createElement("div");
- c.className = "vm-card";
- c.innerHTML = `<div class="vm-head"><span class="vm-name"></span><span class="vm-state"></span>
- <span class="vm-ip num"></span></div>
- <div class="vm-use"><span class="mlabel">CPU</span><div class="gbar"><i></i></div><span class="vm-cpu num"></span>
- <span class="mlabel">RAM</span><span class="vm-mem num"></span></div>
- <div class="row vm-acts"></div>
+const SPARK = `<svg viewBox="0 0 120 100" preserveAspectRatio="none"><path class="hy"/><path class="hy ln"/></svg>`;
+
+// A VM's tile and sheet, built once; update() sets text every poll and
+// rebuilds buttons only when what they depend on changed, so a hold in
+// progress is never torn down under the finger.
+function view(name, root) {
+ const tile = document.createElement("div");
+ tile.className = "vm-tile";
+ tile.innerHTML = `<div class="vm-screen"><i class="nf vm-glyph">${G.vm}</i><img alt="" hidden>
+ <span class="vm-state"></span></div>
+ <div class="vm-info"><b class="vm-name"></b><span class="vm-status"></span></div>
+ <div class="vm-trends">
+ <div class="vm-trend t-cpu">${SPARK}<span class="k">CPU</span><span class="v num"></span></div>
+ <div class="vm-trend t-mem">${SPARK}<span class="k">RAM</span><span class="v num"></span></div>
+ </div>
<div class="vm-err" hidden></div>
- <div class="vm-snaps"></div>`;
- return c;
-}
+ <div class="vm-bar"><button class="vm-power nf hold"></button><span class="vm-ssh"></span>
+ <button class="ib nf vm-more" aria-label="All actions and snapshots" title="All actions and snapshots">${G.more}</button></div>`;
+ const sheet = document.createElement("dialog");
+ sheet.setAttribute("closedby", "any");
+ sheet.className = "card vm-sheet";
+ sheet.innerHTML = `<div class="vm-info"><b class="vm-name"></b><span class="vm-state"></span>
+ <span class="vm-status"></span></div>
+ <div class="vm-acts"></div>
+ <div class="vm-err" hidden></div>
+ <div class="vm-snaphead"><span class="k">Snapshots</span></div>
+ <div class="vm-timeline"></div>
+ <div class="vm-snapacts" hidden><span class="vm-snapname"></span></div>`;
+ root.append(tile, sheet);
+ const $ = (sel) => [tile.querySelector(sel), sheet.querySelector(sel)].filter(Boolean);
+ const open = () => sheet.showModal();
+ tile.querySelector(".vm-screen").addEventListener("click", open);
+ tile.querySelector(".vm-info").addEventListener("click", open);
+ tile.querySelector(".vm-more").addEventListener("click", open);
+
+ const v = {
+ tile, sheet,
+ hist: { cpu: [], mem: [] },
+ keys: {},
+ pick: null, // the snapshot chip tapped in the sheet
+ busy(on) { tile.classList.toggle("busy", on); sheet.classList.toggle("busy", on); },
+ error(msg) {
+ for (const e of $(".vm-err")) { e.textContent = msg; e.hidden = !msg; }
+ },
+ };
+ sheet.querySelector(".vm-snaphead").append(iconButton("snapshot", { vm: name }, v));
+
+ const power = tile.querySelector(".vm-power");
+ power.textContent = G.power;
+ let powerAct = [null, null];
+ hold(power, () => powerAct[1] && post(powerAct[1], { vm: name }, v),
+ { tap: () => powerAct[0] && post(powerAct[0], { vm: name }, v) });
+
+ const changed = (k, val) => {
+ const s = JSON.stringify(val);
+ if (v.keys[k] === s) return false;
+ v.keys[k] = s;
+ return true;
+ };
-// Text every poll; buttons only when what they depend on changed, so a
-// hold in progress is not torn down under the finger.
-function fill(c, vm) {
- c.querySelector(".vm-name").textContent = vm.name;
- const pill = c.querySelector(".vm-state");
- pill.textContent = vm.saved && vm.state === "shut off" ? "saved" : vm.state;
- pill.className = `vm-state ${PILL[vm.state] ?? ""}`;
- c.querySelector(".vm-ip").textContent = vm.ip;
- const on = vm.state === "running";
- c.querySelector(".vm-use").hidden = !on;
- c.querySelector(".gbar > i").style.width = `${vm.cpu ?? 0}%`;
- c.querySelector(".vm-cpu").textContent = vm.cpu == null ? "—" : `${Math.round(vm.cpu)}% of ${vm.vcpus}`;
- c.querySelector(".vm-mem").textContent = gib(vm.mem);
-
- const key = JSON.stringify([vm.state, vm.saved, vm.snapshots]);
- if (c.dataset.key === key) return;
- c.dataset.key = key;
- const acts = c.querySelector(".vm-acts");
- acts.replaceChildren(...actionsFor(vm.state, vm.saved).map(([a, l]) => button(l, a, { vm: vm.name }, c)),
- button("Snapshot", "snapshot", { vm: vm.name }, c));
- c.querySelector(".vm-snaps").replaceChildren(...vm.snapshots.map((s) => {
- const row = document.createElement("div");
- row.className = "vm-snap";
- const name = document.createElement("span");
- name.textContent = s;
- row.append(name, button("Revert", "revert", { vm: vm.name, snap: s }, c),
- button("Delete", "snapdelete", { vm: vm.name, snap: s }, c));
- return row;
- }));
+ v.update = (vm, visible) => {
+ for (const e of $(".vm-name")) e.textContent = vm.name;
+ for (const e of $(".vm-state")) {
+ e.textContent = vm.state;
+ e.className = `vm-state ${PILL[vm.state] ?? ""}`;
+ }
+ for (const e of $(".vm-status")) e.textContent = status(vm);
+ const on = vm.state === "running";
+ tile.classList.toggle("on", on);
+
+ // Tap does the gentle thing, hold forces: the fill shows only when a
+ // hold does something.
+ powerAct = powerFor(vm.state);
+ power.classList.toggle("hold", Boolean(powerAct[1]));
+ power.classList.toggle("go", !on && Boolean(powerAct[0]));
+ const pl = [powerAct[0] && LABEL[powerAct[0]], powerAct[1] && LABEL[powerAct[1]]].filter(Boolean).join(", ");
+ power.setAttribute("aria-label", pl);
+ power.title = pl;
+
+ if (changed("ssh", [on, vm.ready])) {
+ const slot = tile.querySelector(".vm-ssh");
+ slot.replaceChildren();
+ if (on) {
+ const b = iconButton("ssh", { vm: vm.name }, v, "vm-sshb");
+ b.classList.toggle("ready", vm.ready === true);
+ slot.append(b);
+ }
+ }
+
+ // Screen: refreshed every SHOT ms, only while the tab is on screen.
+ const img = tile.querySelector("img");
+ if (on && visible) {
+ const url = `/api/vm/image/${encodeURIComponent(vm.name)}?t=${Math.floor(Date.now() / SHOT)}`;
+ if (img.dataset.src !== url) {
+ img.dataset.src = url;
+ img.onload = () => { img.hidden = false; };
+ img.onerror = () => { img.hidden = true; };
+ img.src = url;
+ }
+ } else if (!on) {
+ img.hidden = true;
+ delete img.dataset.src;
+ }
+
+ // Trends: history in the page, cleared while the VM is off.
+ if (on) {
+ push(v.hist.cpu, vm.cpu ?? 0, HIST);
+ push(v.hist.mem, vm.used != null && vm.mem ? (vm.used / vm.mem) * 100 : 0, HIST);
+ } else {
+ v.hist.cpu.length = 0;
+ v.hist.mem.length = 0;
+ }
+ for (const [k, hist] of Object.entries(v.hist)) {
+ const [fill, stroke] = tile.querySelectorAll(`.t-${k} path`);
+ fill.setAttribute("d", area(hist, 100, HIST));
+ stroke.setAttribute("d", line(hist, 100, HIST));
+ }
+ tile.querySelector(".t-cpu .v").textContent = on && vm.cpu != null ? `${Math.round(vm.cpu)}%` : "—";
+ tile.querySelector(".t-mem .v").textContent = !on ? "—"
+ : vm.used != null ? `${gib(vm.used)}/${gib(vm.mem)} GiB` : `${gib(vm.mem)} GiB`;
+
+ if (changed("acts", [vm.state, vm.saved])) {
+ sheet.querySelector(".vm-acts").replaceChildren(
+ ...actionsFor(vm.state, vm.saved).map((a) => iconButton(a, { vm: vm.name }, v)));
+ }
+
+ // Snapshot timeline, oldest first: a chip per snapshot with its age,
+ // the current one marked. A tap picks one, and its revert and delete
+ // appear below.
+ const names = vm.snapshots.map((s) => s.name);
+ if (v.pick && !names.includes(v.pick)) v.pick = null;
+ if (changed("snaps", [vm.snapshots, v.pick])) {
+ const tl = sheet.querySelector(".vm-timeline");
+ tl.replaceChildren(...vm.snapshots.map((s) => {
+ const c = document.createElement("button");
+ c.className = `vm-snap${s.current ? " current" : ""}${s.name === v.pick ? " on" : ""}`;
+ c.innerHTML = "<b></b><span></span>";
+ c.firstChild.textContent = s.name;
+ c.lastChild.textContent = ago(s.created);
+ c.title = new Date(s.created * 1000).toLocaleString();
+ c.onclick = () => { v.pick = s.name === v.pick ? null : s.name; v.update(vm, visible); };
+ return c;
+ }));
+ if (!vm.snapshots.length) tl.textContent = "None yet.";
+ const acts = sheet.querySelector(".vm-snapacts");
+ acts.hidden = !v.pick;
+ acts.querySelector(".vm-snapname").textContent = v.pick ?? "";
+ acts.querySelectorAll("button").forEach((b) => b.remove());
+ if (v.pick) {
+ acts.append(iconButton("revert", { vm: vm.name, snap: v.pick }, v),
+ iconButton("snapdelete", { vm: vm.name, snap: v.pick }, v));
+ }
+ }
+ };
+ return v;
}
+const views = new Map();
+
export default {
title: "VMs",
tab: "VMs",
interval: 2,
mount(el) {
- el.innerHTML = `<div class="vm"><div class="vm-off"></div><div class="vm-list"></div></div>`;
+ el.innerHTML = `<div class="vm">
+ <svg width="0" height="0" aria-hidden="true" style="position:absolute"><defs>
+ <linearGradient id="vmline" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="120" y2="0"><stop offset="0" style="stop-color:var(--udt-border-1)"/>
+ <stop offset=".5" style="stop-color:var(--udt-border-2)"/><stop offset="1" style="stop-color:var(--udt-border-3)"/></linearGradient>
+ <linearGradient id="vmfill" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="0" y2="100">
+ <stop offset="0" style="stop-color:var(--udt-border-2);stop-opacity:.45"/>
+ <stop offset="1" style="stop-color:var(--udt-border-1);stop-opacity:.05"/></linearGradient>
+ </defs></svg>
+ <div class="vm-off"></div><div class="vm-grid"></div></div>`;
},
update(st, el) {
const off = el.querySelector(".vm-off");
- const list = el.querySelector(".vm-list");
+ const grid = el.querySelector(".vm-grid");
off.hidden = !st.offline;
- list.hidden = Boolean(st.offline);
+ grid.hidden = Boolean(st.offline);
if (st.offline) {
offline(off, { icon: "/icons/virt-manager.svg", title: "libvirt is not answering",
detail: "Start libvirtd and the VMs appear here.", reason: st.reason });
return;
}
- const cards = new Map([...list.children].map((c) => [c.dataset.vm, c]));
- list.replaceChildren(...st.vms.map((vm) => {
- const c = cards.get(vm.name) ?? card();
- c.dataset.vm = vm.name;
- fill(c, vm);
- return c;
- }));
- if (!st.vms.length) list.textContent = "No VMs defined.";
+ const visible = !document.hidden && el.offsetParent !== null;
+ const seen = new Set();
+ for (const vm of st.vms) {
+ seen.add(vm.name);
+ if (!views.has(vm.name)) views.set(vm.name, view(vm.name, grid));
+ views.get(vm.name).update(vm, visible);
+ }
+ for (const [name, v] of views) {
+ if (!seen.has(name)) { v.tile.remove(); v.sheet.remove(); views.delete(name); }
+ }
+ grid.classList.toggle("empty", !st.vms.length);
},
};
diff --git a/static/modules/windows.js b/static/modules/windows.js
index 0657a16..639137e 100644
--- a/static/modules/windows.js
+++ b/static/modules/windows.js
@@ -14,6 +14,8 @@
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+import { buzz } from "../hold.js";
+
async function post(action, body = {}) {
try {
await fetch(`/api/windows/${action}`, {
@@ -120,7 +122,7 @@ function card(w, workspaces, wsIcons) {
if (e.target.closest(".wx")) return;
long = false;
const at = { left: e.clientX, bottom: e.clientY };
- timer = setTimeout(() => { long = true; openMenu(at, w, workspaces, wsIcons); }, 600);
+ timer = setTimeout(() => { long = true; buzz(); openMenu(at, w, workspaces, wsIcons); }, 600);
});
// Chrome's own long-press menu (copy or share the image) is not wanted here.
c.addEventListener("contextmenu", (e) => e.preventDefault());
diff --git a/tests/test_vm.py b/tests/test_vm.py
index b84ec97..10791dc 100644
--- a/tests/test_vm.py
+++ b/tests/test_vm.py
@@ -31,6 +31,8 @@ DOMSTATS = """Domain: 'alpha'
state.reason=1
cpu.time={ns}
balloon.current=4194304
+ balloon.available=4000000
+ balloon.usable=3000000
vcpu.current=2
Domain: 'beta'
@@ -50,6 +52,7 @@ class Fake:
self.ns = 1_000_000_000
self.fail = None
self.kitty_ok = True
+ self.listening = set()
def __call__(self, cmd, timeout=10):
self.cmds.append(cmd)
@@ -59,7 +62,17 @@ class Fake:
elif cmd[:2] == ["virsh", "dominfo"]:
out = "Managed save: yes\n" if cmd[2] == "beta" else "Managed save: no\n"
elif cmd[:2] == ["virsh", "snapshot-list"]:
- out = "clean\nworking\n\n" if cmd[2] == "alpha" else ""
+ out = (" Name Creation Time State\n----\n"
+ " clean 2026-03-06 10:27:47 +0100 shutoff\n"
+ " working 2026-04-04 16:00:51 +0200 running\n\n") if cmd[2] == "alpha" else ""
+ elif cmd[:2] == ["virsh", "snapshot-current"]:
+ out, code = ("working\n", 0) if cmd[-1] == "alpha" else ("", 1)
+ elif cmd[:2] == ["ssh", "-G"]:
+ out = "user root\nhostname 192.0.2.9\nport 2290\n" if cmd[2] == "alpha" else f"hostname {cmd[2]}\nport 22\n"
+ elif cmd[:2] == ["virsh", "screenshot"]:
+ Path(cmd[cmd.index("--file") + 1]).write_bytes(b"P6 1 1 255 ...")
+ elif cmd[0] == "ffmpeg":
+ Path(cmd[-1]).write_bytes(b"JPEG")
elif cmd[:2] == ["virsh", "domifaddr"]:
out = (" Name MAC address Protocol Address\n---\n"
" lo 00:00:00:00:00:00 ipv4 127.0.0.1/8\n"
@@ -72,7 +85,8 @@ class Fake:
def make(fake, now, **extra):
- cfg = {"run": fake, "clock": lambda: now[0], "spawn": lambda f: f(), "hyprland": "classic"}
+ cfg = {"run": fake, "clock": lambda: now[0], "spawn": lambda f: f(), "hyprland": "classic",
+ "probe": lambda host, port: (host, port) in fake.listening}
cfg.update(extra)
return vm.make(cfg)
@@ -90,13 +104,31 @@ class VmTest(unittest.TestCase):
self.assertEqual((a["name"], a["state"], a["vcpus"]), ("alpha", "running", 2))
self.assertIsNone(a["cpu"]) # one sample: no rate yet
self.assertEqual(a["mem"], 4194304 * 1024)
+ self.assertEqual(a["used"], 1000000 * 1024)
+ self.assertIsNone(b["used"])
self.assertEqual(a["ip"], "192.0.2.5")
- self.assertEqual(a["snapshots"], ["clean", "working"])
+ self.assertEqual([s["name"] for s in a["snapshots"]], ["clean", "working"])
+ self.assertEqual(a["snapshots"][0]["created"], 1772789267)
+ self.assertEqual([s["current"] for s in a["snapshots"]], [False, True])
self.assertEqual((b["state"], b["saved"], b["ip"]), ("shut off", True, ""))
self.fake.ns += 1_000_000_000 # 1 s of CPU over 2 s, 2 vCPUs
self.now[0] += 2
self.assertAlmostEqual(self.mod.state()["vms"][0]["cpu"], 25.0)
+ def test_ssh_ready_from_ssh_alias(self):
+ st = self.mod.state()
+ self.assertEqual((st["vms"][0]["ready"], st["vms"][1]["ready"]), (False, None))
+ self.fake.listening.add(("192.0.2.9", 2290)) # alias host and port, not the agent IP
+ self.now[0] += 2 # booting: re-probed within seconds
+ self.mod.state()
+ self.assertTrue(self.mod.state()["vms"][0]["ready"])
+
+ def test_screenshot_only_for_running_vm(self):
+ self.mod.state()
+ self.assertEqual(self.mod.image("alpha"), (b"JPEG", "image/jpeg"))
+ self.assertIsNone(self.mod.image("beta")) # shut off
+ self.assertIsNone(self.mod.image("../etc"))
+
def test_offline(self):
self.fake.fail = "domstats"
st = self.mod.state()