eBPF-based security platform
tools/xtop: add a terminal view of the nodes over the backend
John Fastabend3b2164cc82be
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex a184ce00..689bd4b6 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -982,6 +982,11 @@ the query of :src:`tools/xtop/sql/nodes.sql`, with the names and typesof its columns, over nodes healthy, unhealthy, stale and without a treeor an image (``test/xtop-nodes``).+The unit tests of :src:`tools/xtop/test/` cover how xtop turns the rows+of that query into nodes, the health percent, the roll-up by image and+its ClickHouse client; ``make -C tools/xtop tests`` type-checks the+program and runs them (:ref:`testing-xtop`).+Coverage by area----------------diff --git a/Documentation/contribute/testing/testing.rst b/Documentation/contribute/testing/testing.rstindex 87ecc8b2..51f27e54 100644--- a/Documentation/contribute/testing/testing.rst+++ b/Documentation/contribute/testing/testing.rst@@ -1219,6 +1219,25 @@ instead. It has to run inside the container, so it needs the librariesit links there. A test named ``<name>-stub`` feeds quotes in the stub'sform and is skipped then.+.. _testing-xtop:++Run the xtop tests+------------------++:src:`tools/xtop/` is a Bun program. Its tests need ``bun`` on the host+and no ClickHouse: they feed its row mapping, roll-up and client rows+shaped as ``tools/backend/test/xtop-nodes.expected`` has them.++.. code-block:: console++ $ make -C tools/xtop tests++The target installs the locked packages, type-checks the program with+``tsc`` and runs ``bun test``. The query itself is checked against the+schema by the backend test ``xtop-nodes``, which runs+:src:`tools/xtop/sql/nodes.sql` from ``test/xtop-nodes.sh`` over the+rows of ``test/xtop-nodes.setup.sql``.+Write a test------------diff --git a/Documentation/operate/backend/index.rst b/Documentation/operate/backend/index.rstindex 77fc0447..0e67926a 100644--- a/Documentation/operate/backend/index.rst+++ b/Documentation/operate/backend/index.rst@@ -84,6 +84,9 @@ Files* - :src:`tools/backend/test/`- The SQL tests and their runner, ``test/run.sh``(:ref:`testing-backend`).+ * - :src:`tools/xtop/`+ - A terminal view of the nodes over ``node_status``,+ ``latest`` and ``node_vulns`` (:doc:`xtop`)... toctree:::titlesonly:@@ -96,4 +99,5 @@ Filessbom-scanmaintainboot-baselines+ xtoptables/indexdiff --git a/Documentation/operate/backend/status.rst b/Documentation/operate/backend/status.rstindex 4ecb2cd6..66631404 100644--- a/Documentation/operate/backend/status.rst+++ b/Documentation/operate/backend/status.rst@@ -53,7 +53,7 @@ follows. The objects that do it are in :src:`tools/backend/sql/40-status.sql`, a- refreshable materialized view, every minute- Runs the checks for all nodes and replaces the rows of ``node_status`` in one step.-A UI reads ``node_status`` as often as it likes:+A UI reads ``node_status`` as often as it likes, as :doc:`xtop` does:.. code-block:: sqldiff --git a/Documentation/operate/backend/xtop.rst b/Documentation/operate/backend/xtop.rstnew file mode 100644index 00000000..5b169088--- /dev/null+++ b/Documentation/operate/backend/xtop.rst@@ -0,0 +1,121 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: How-to+:audience: Operators, SecOps++Watch the nodes with xtop+=========================++:src:`tools/xtop/` is a terminal view of the backend. Its Nodes view+reads ``shirudo.node_status``, ``shirudo.latest`` and+``shirudo.node_vulns`` over the HTTP interface of the backend's+ClickHouse with one query, :src:`tools/xtop/sql/nodes.sql`, and shows+one row per node, or one per image. It only reads: every query is sent+with ``readonly=1``. It is a `Bun <https://bun.sh>`_ program built on+Ink and React, and runs on an operator's host, never on a target.++Build and run+-------------++1. Install Bun 1.4.4 or later.+2. Build the executable, which embeds the query:++ .. code-block:: console++ $ make -C tools/xtop++3. Point it at the HTTP interface, port 8123 unless the server is set up+ otherwise, and run it:++ .. code-block:: console++ $ CLICKHOUSE_URL=https://clickhouse.example.com:8443/ CLICKHOUSE_USER=xtop \+ CLICKHOUSE_PASSWORD=... tools/xtop/dist/xtop++``bun run src/index.tsx`` in :src:`tools/xtop/` runs it without+building. A user that can only ``SELECT`` from the ``shirudo`` database+is enough.++.. list-table::+ :header-rows: 1++ * - Variable+ - Value+ * - ``CLICKHOUSE_URL``+ - The HTTP interface, ``http`` or ``https``. Default+ ``http://127.0.0.1:8123/``. A URL that carries a user or a+ password is refused, so that they never show in the process list.+ * - ``CLICKHOUSE_USER``, ``CLICKHOUSE_PASSWORD``+ - The ClickHouse user and its password, sent in the+ ``X-ClickHouse-User`` and ``X-ClickHouse-Key`` headers. Without+ them the server's default user answers.++The view queries when it opens, every minute after that, as often as+``node_status_mv`` recomputes the table, and when you press ``r``. A+query that fails leaves the rows of the last one in place and says why+at the start of the summary line.++Read the nodes+--------------++``STATUS`` and ``TRUST`` are the columns of ``node_status`` that+:doc:`status` describes, shown side by side as that page asks: a healthy+node is one whose records match its tree, an enrolled one is one whose+key the operator has recorded as a TPM's.++.. list-table::+ :header-rows: 1++ * - Column+ - Value+ * - ``STATUS``+ - ``unhealthy``, ``stale`` or ``healthy``, worst first.+ * - ``TRUST``+ - ``untrusted`` or ``enrolled``.+ * - ``NODE``+ - ``node_id``.+ * - ``CHECK``+ - The first check that failed, as its line names it, for example+ ``3 reported``; ``—`` when all passed.+ * - ``IMAGE``, ``KERNEL``, ``BUILD``+ - ``image_id`` and ``image_version``, ``kernel_release`` and the+ first eight digits of ``version_id`` from the node's newest+ record. ``—`` for a node that reports no image.+ * - ``TREE``+ - ``✓ #<head>`` at the head of its tree, ``#<last>/#<head>``+ behind it, ``no tree`` when it follows none.+ * - ``SHIELDS``+ - From ``node_vulns``, counted by upatch: ``✓`` loaded and+ shielding (``shielded``), ``…`` coming (``shield_pending``),+ ``✗`` published but doing nothing on the node+ (``shield_module_absent``, ``shield_excludes_node``,+ ``shield_withdrawn``).+ * - ``EXPOSED``+ - From ``node_vulns``, the advisories no loaded upatch shields: those+ ``exposed_no_shield`` and those of the ``✗`` shields. A ``?``+ before it says the node has a finding ``unknown``, see+ :doc:`exposure`.+ * - ``SEEN``+ - How long ago the newest record was received.++The summary line gives the health of the nodes shown: the percent of+them ``healthy``, so 100% when every node is healthy and 0% when none+is. A stale node counts against it like an unhealthy one.++Enter on a node shows its host name, key, what its record says it runs,+and the seven lines of its ``log``, a failed one in red; Esc returns.+``/`` searches the node, host and key names, status, trust, image,+kernel, build and the line of the failed check.++``t`` switches to one row per image id and version. A group's status is+its worst member's, its health the percent of its members ``healthy``,+its kernel ``mixed`` when its members differ, its tree the member+furthest behind, its shields the sums over its members, and its+exposure that of its most exposed member. Enter on an image shows its+nodes.++Labels and detector hits are not shown: the keepalive carries no labels,+and the collector of :src:`tools/backend/otelcol.yaml` takes in no map+snapshot metrics.diff --git a/tools/xtop/.gitignore b/tools/xtop/.gitignorenew file mode 100644index 00000000..b9470778--- /dev/null+++ b/tools/xtop/.gitignore@@ -0,0 +1,2 @@+node_modules/+dist/diff --git a/tools/xtop/Makefile b/tools/xtop/Makefilenew file mode 100644index 00000000..be910472--- /dev/null+++ b/tools/xtop/Makefile@@ -0,0 +1,24 @@+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# xtop is a Bun program; these targets need bun on PATH.++BUN ?= bun++all: dist/xtop++node_modules: package.json bun.lock+ $(BUN) install --frozen-lockfile+ touch $@++dist/xtop: node_modules build.ts $(shell find src sql -type f)+ $(BUN) run build.ts++tests: node_modules+ $(BUN) x tsc --noEmit+ $(BUN) test++clean:+ rm -rf dist node_modules++.PHONY: all tests cleandiff --git a/tools/xtop/build.ts b/tools/xtop/build.tsnew file mode 100644index 00000000..4efc49ec--- /dev/null+++ b/tools/xtop/build.ts@@ -0,0 +1,29 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// Compiles xtop into one executable, dist/xtop. Ink imports+// react-devtools-core, an optional package for DEV=true sessions, from a+// module the bundle evaluates at start; a stub stands in for it.++export {};++const result = await Bun.build({+ entrypoints: ["./src/index.tsx"],+ compile: { outfile: "dist/xtop" },+ plugins: [+ {+ name: "no-devtools",+ setup(build) {+ build.onResolve({ filter: /^react-devtools-core$/ }, () => ({ path: "react-devtools-core", namespace: "stub" }));+ build.onLoad({ filter: /.*/, namespace: "stub" }, () => ({+ contents: "export default { initialize() {}, connectToDevTools() {} };",+ loader: "js",+ }));+ },+ },+ ],+});+if (!result.success) {+ for (const log of result.logs) console.error(log);+ process.exit(1);+}diff --git a/tools/xtop/bun.lock b/tools/xtop/bun.locknew file mode 100644index 00000000..63d98535--- /dev/null+++ b/tools/xtop/bun.lock@@ -0,0 +1,153 @@+{+ "lockfileVersion": 2,+ "configVersion": 1,+ "workspaces": {+ "": {+ "name": "xtop",+ "dependencies": {+ "ink": "^8.0.0",+ "react": "^19.3.1",+ },+ "devDependencies": {+ "@types/bun": "^1.4.4",+ "@types/react": "^19.3.0",+ "typescript": "^7.0.2",+ },+ },+ },+ "packages": {+ "@alcalzone/ansi-tokenize": ["@alcalzone/[email protected]", "", { "dependencies": { "ansi-styles": "^6.2.1", "is-fullwidth-code-point": "^5.0.0" } }, "sha512-GZdcaU9RV2Gn9SAg1hcsSoQ4nIWZfutPqIvxayUYsOzfBPJioJ+aQIXnMJiGDz+35Gg2pskkPxioYnSblPELEw=="],++ "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.4" } }, "sha512-9wkRDXUXK124pEnAutE6n/l18j+i9GC5IAHK8TmX/2nlySETmky0OU6yL5U8pW1AoKh++AN9auDCr647BfurjQ=="],++ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="],++ "@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="],++ "@typescript/typescript-aix-ppc64": ["@typescript/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="],++ "@typescript/typescript-darwin-arm64": ["@typescript/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA=="],++ "@typescript/typescript-darwin-x64": ["@typescript/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA=="],++ "@typescript/typescript-freebsd-arm64": ["@typescript/[email protected]", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ=="],++ "@typescript/typescript-freebsd-x64": ["@typescript/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw=="],++ "@typescript/typescript-linux-arm": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ=="],++ "@typescript/typescript-linux-arm64": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ=="],++ "@typescript/typescript-linux-loong64": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ=="],++ "@typescript/typescript-linux-mips64el": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA=="],++ "@typescript/typescript-linux-ppc64": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA=="],++ "@typescript/typescript-linux-riscv64": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ=="],++ "@typescript/typescript-linux-s390x": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw=="],++ "@typescript/typescript-linux-x64": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A=="],++ "@typescript/typescript-netbsd-arm64": ["@typescript/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA=="],++ "@typescript/typescript-netbsd-x64": ["@typescript/[email protected]", "", { "os": "none", "cpu": "x64" }, "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA=="],++ "@typescript/typescript-openbsd-arm64": ["@typescript/[email protected]", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ=="],++ "@typescript/typescript-openbsd-x64": ["@typescript/[email protected]", "", { "os": "openbsd", "cpu": "x64" }, "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg=="],++ "@typescript/typescript-sunos-x64": ["@typescript/[email protected]", "", { "os": "sunos", "cpu": "x64" }, "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g=="],++ "@typescript/typescript-win32-arm64": ["@typescript/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ=="],++ "@typescript/typescript-win32-x64": ["@typescript/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="],++ "ansi-escapes": ["[email protected]", "", { "dependencies": { "environment": "^1.0.0" } }, "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg=="],++ "ansi-regex": ["[email protected]", "", {}, "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g=="],++ "ansi-styles": ["[email protected]", "", {}, "sha512-kKvt3m4uwzqL0wlkPd09CmljPJGOZZ4D0fP65sqFSvPkMRKhNi+74MgIJ5QxE6SxqB4t4KyUFGg8+n5zjo6hew=="],++ "auto-bind": ["[email protected]", "", {}, "sha512-ooviqdwwgfIfNmDwo94wlshcdzfO64XV0Cg6oDsDYBJfITDz1EngD2z7DkbvCWn+XIMsIqW27sEVF6qcpJrRcg=="],++ "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ=="],++ "chalk": ["[email protected]", "", {}, "sha512-/Ce6KNm3vIbWdMlNna6RVIZ/ICQxnJxCicet5LBKK9ZffBkqzDw0xh9EiKSljdRtiIQ1S1z4YgcscUUGzNCWrA=="],++ "cli-boxes": ["[email protected]", "", {}, "sha512-5IOn+jcCEHEraYolBPs/sT4BxYCe2nHg374OPiItB1O96KZFseS2gthU4twyYzeDcFew4DaUM/xwc5BQf08JJw=="],++ "cli-cursor": ["[email protected]", "", { "dependencies": { "restore-cursor": "^4.0.0" } }, "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg=="],++ "cli-truncate": ["[email protected]", "", { "dependencies": { "slice-ansi": "^10.0.0", "string-width": "^8.3.0" } }, "sha512-5uyZew3nYoDgyltqSI8OER6DuyecorYOSVDAXl9wQ9Y8Re/HaQ/5qP0HmTUOUQqmvtpB+mlsf1gG/FUS3U1gLQ=="],++ "code-excerpt": ["[email protected]", "", { "dependencies": { "convert-to-spaces": "^2.0.1" } }, "sha512-xxodCmBen3iy2i0WtAK8FlFNrRzjUqjRsMfho58xT/wvZU1YTM3fCnRjcy1gJPMepaRlgm/0e6w8SpWHpn3/cA=="],++ "convert-to-spaces": ["[email protected]", "", {}, "sha512-rcQ1bsQO9799wq24uE5AM2tAILy4gXGIK/njFWcVQkGNZ96edlpY+A7bjwvzjYvLDyzmG1MmMLZhpcsb+klNMQ=="],++ "csstype": ["[email protected]", "", {}, "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ=="],++ "environment": ["[email protected]", "", {}, "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q=="],++ "es-toolkit": ["[email protected]", "", {}, "sha512-iUqZ+NlwH4jUgRmXZUxFBsV/9762TQEa1O4IXLFBmDEjVHScBytKuseX23I0+v9ShZ5MYxEx6WKNzm6IPnex8g=="],++ "escape-string-regexp": ["[email protected]", "", {}, "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w=="],++ "get-east-asian-width": ["[email protected]", "", {}, "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q=="],++ "indent-string": ["[email protected]", "", {}, "sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg=="],++ "ink": ["[email protected]", "", { "dependencies": { "@alcalzone/ansi-tokenize": "^0.3.1", "ansi-escapes": "^7.3.0", "ansi-styles": "^7.0.0", "auto-bind": "^5.0.1", "chalk": "^6.0.1", "cli-boxes": "^4.0.1", "cli-cursor": "^4.0.0", "cli-truncate": "^6.0.0", "code-excerpt": "^4.0.0", "es-toolkit": "^1.52.0", "indent-string": "^5.0.0", "is-in-ci": "^2.0.0", "patch-console": "^2.0.0", "quick-lru": "^7.3.0", "react-reconciler": "^0.34.0", "signal-exit": "^3.0.7", "stack-utils": "^2.0.6", "string-width": "^8.3.0", "terminal-size": "^4.0.1", "type-fest": "^5.10.0", "widest-line": "^6.0.0", "wrap-ansi": "^10.0.2", "yoga-layout": "~3.2.1" }, "peerDependencies": { "@types/react": ">=19.3.0", "react": ">=19.3.0", "react-devtools-core": ">=6.1.2" }, "optionalPeers": ["@types/react", "react-devtools-core"] }, "sha512-M2aFwZOqmkFxCwedy6xrP4E+DGoK57iahAFnfTqNyOyJ54O7DZzu027z/NI8EGy44Sw9O9BcbTF4QEUS2GHAtg=="],++ "is-fullwidth-code-point": ["[email protected]", "", { "dependencies": { "get-east-asian-width": "^1.3.1" } }, "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ=="],++ "is-in-ci": ["[email protected]", "", { "bin": { "is-in-ci": "cli.js" } }, "sha512-cFeerHriAnhrQSbpAxL37W1wcJKUUX07HyLWZCW1URJT/ra3GyUTzBgUnh24TMVfNTV2Hij2HLxkPHFZfOZy5w=="],++ "mimic-fn": ["[email protected]", "", {}, "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg=="],++ "onetime": ["[email protected]", "", { "dependencies": { "mimic-fn": "^2.1.0" } }, "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg=="],++ "patch-console": ["[email protected]", "", {}, "sha512-0YNdUceMdaQwoKce1gatDScmMo5pu/tfABfnzEqeG0gtTmd7mh/WcwgUjtAeOU7N8nFFlbQBnFK2gXW5fGvmMA=="],++ "quick-lru": ["[email protected]", "", {}, "sha512-k9lSsjl36EJdK7I06v7APZCbyGT2vMTsYSRX1Q2nbYmnkBqgUhRkAuzH08Ciotteu/PLJmIF2+tti7o3C/ts2g=="],++ "react": ["[email protected]", "", {}, "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw=="],++ "react-reconciler": ["[email protected]", "", { "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { "react": "^19.3.0" } }, "sha512-eVibvB1fc9j5Qf1KRkiM3GzRPBdjg2P6G6QV2f3P6Eb3OGMxRBhdg2rrUwjbV5JrQaJj8nOa8uajmmJA5tJWjQ=="],++ "restore-cursor": ["[email protected]", "", { "dependencies": { "onetime": "^5.1.0", "signal-exit": "^3.0.2" } }, "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg=="],++ "scheduler": ["[email protected]", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="],++ "signal-exit": ["[email protected]", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],++ "slice-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^7.0.0", "string-width": "^8.3.0" } }, "sha512-CJKEH3zwVX4bOnE+bFbmh+JK/YMT9VAazqBsVBTesnYKXlNtz6oVmrhNp1jHrxHzscuUkWiKZpzNzFraZcrorg=="],++ "stack-utils": ["[email protected]", "", { "dependencies": { "escape-string-regexp": "^2.0.0" } }, "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ=="],++ "string-width": ["[email protected]", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ=="],++ "strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="],++ "tagged-tag": ["[email protected]", "", {}, "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng=="],++ "terminal-size": ["[email protected]", "", {}, "sha512-avMLDQpUI9I5XFrklECw1ZEUPJhqzcwSWsyyI8blhRLT+8N1jLJWLWWYQpB2q2xthq8xDvjZPISVh53T/+CLYQ=="],++ "type-fest": ["[email protected]", "", { "dependencies": { "tagged-tag": "^1.0.0" } }, "sha512-NoSdpq/WEiAg5sjmBkmV/hfxv6HJH4NqPNrqjtSO5CwRmpsDfaf4begxW34KdJykH/l1yHtwBWQkCRdoXO8mPA=="],++ "typescript": ["[email protected]", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="],++ "undici-types": ["[email protected]", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],++ "widest-line": ["[email protected]", "", { "dependencies": { "string-width": "^8.1.0" } }, "sha512-U89AsyEeAsyoF0zVJBkG9zBgekjgjK7yk9sje3F4IQpXBJ10TF6ByLlIfjMhcmHMJgHZI4KHt4rdNfktzxIAMA=="],++ "wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^6.2.3", "string-width": "^8.2.0" } }, "sha512-6OLRNZqRntVGBm26ghZ5eZhCuWWyOkRCSn8XsOIuq5stpCE/tjLbdozd93naILZig0lmD8ANfRwnhn0DLeXGlg=="],++ "yoga-layout": ["[email protected]", "", {}, "sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ=="],++ "@alcalzone/ansi-tokenize/ansi-styles": ["[email protected]", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="],++ "wrap-ansi/ansi-styles": ["[email protected]", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="],+ }+}diff --git a/tools/xtop/package.json b/tools/xtop/package.jsonnew file mode 100644index 00000000..d5eb6a9a--- /dev/null+++ b/tools/xtop/package.json@@ -0,0 +1,23 @@+{+ "name": "xtop",+ "version": "0.1.0",+ "description": "Terminal view of the shirudo backend",+ "license": "BSD-2-Clause",+ "private": true,+ "type": "module",+ "scripts": {+ "start": "bun run src/index.tsx",+ "typecheck": "tsc --noEmit",+ "test": "bun test",+ "build": "bun run build.ts"+ },+ "dependencies": {+ "ink": "^8.0.0",+ "react": "^19.3.1"+ },+ "devDependencies": {+ "@types/bun": "^1.4.4",+ "@types/react": "^19.3.0",+ "typescript": "^7.0.2"+ }+}diff --git a/tools/xtop/src/App.tsx b/tools/xtop/src/App.tsxnew file mode 100644index 00000000..b903d118--- /dev/null+++ b/tools/xtop/src/App.tsx@@ -0,0 +1,139 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// The menu of views beside the open one, and the key hints below.++import { useRef, useState } from "react";+import { Box, Text, measureElement, useApp, useInput, useWindowSize, type DOMElement } from "ink";+import type { Backend } from "./lib/backend.ts";+import { useMouse } from "./lib/useMouse.ts";+import { Panel } from "./components/Panel.tsx";+import { Sidebar, type MenuItem } from "./components/Sidebar.tsx";+import { NodesView, type NodesMode } from "./components/NodesView.tsx";++type ViewId = "nodes";++const MENU: readonly (MenuItem & { id: ViewId; title: string })[] = [+ { id: "nodes", label: "Nodes", title: "nodes · status from shirudo.node_status" },+];+const SIDEBAR_WIDTH = 16;++type Focus = "menu" | "menu-open" | "view" | "detail" | "search";++const HINTS: Record<Focus, string> = {+ menu: "j/k menu · l/enter open · 1 nodes · q quit",+ "menu-open": "j/k menu · l/enter open · tab back to view · esc close view · q quit",+ view: "j/k scroll · k past top → sort, then tabs · / search · enter node checks, image → nodes · t by image · r refresh · tab menu · esc close · q quit",+ detail: "esc back · q quit",+ search: "type to filter · enter keep · esc clear",+};++export function App({ backend }: { backend: Backend }) {+ const { exit } = useApp();+ const { columns, rows } = useWindowSize();+ const [openView, setOpenView] = useState<ViewId | null>("nodes");+ const [menuFocused, setMenuFocused] = useState(false);+ const [menuCursor, setMenuCursor] = useState(0);+ const [searching, setSearching] = useState(false);+ const [detail, setDetail] = useState(false);+ // Kept while the app runs, so reopening Nodes keeps the toggle.+ const [nodesMode, setNodesMode] = useState<NodesMode>("nodes");++ const open = (view: ViewId) => {+ setMenuCursor(MENU.findIndex((m) => m.id === view));+ setOpenView(view);+ setMenuFocused(false);+ };+ const close = () => {+ setOpenView(null);+ setMenuFocused(true);+ };++ const focus: Focus = searching+ ? "search"+ : !openView+ ? "menu"+ : menuFocused+ ? "menu-open"+ : detail+ ? "detail"+ : "view";+ const navActive = focus !== "search";++ useInput(+ (input, key) => {+ if (input === "q") return exit();+ if (key.tab && openView) return setMenuFocused((m) => !m);+ if (focus === "menu-open" && key.escape) return close();+ if (focus === "menu" && key.escape) return exit();+ if (focus === "menu" || focus === "menu-open") {+ const move = (d: number) => setMenuCursor((c) => Math.max(0, Math.min(MENU.length - 1, c + d)));+ if (key.upArrow) move(-1);+ if (key.downArrow) move(1);+ for (const ch of input) {+ if (ch === "k") move(-1);+ if (ch === "j") move(1);+ }+ if (key.return || input === "l") open(MENU[menuCursor]!.id);+ }+ for (const ch of input) {+ const item = MENU[Number(ch) - 1];+ if (/[1-9]/.test(ch) && item) open(item.id);+ }+ },+ { isActive: navActive },+ );++ const sidebarRef = useRef<DOMElement>(null);+ useMouse(+ (e) => {+ if (e.kind !== "press" || e.button !== "left" || !sidebarRef.current) return;+ const m = measureElement(sidebarRef.current);+ if (e.x < m.x || e.x >= m.x + m.width) return;+ // The border and the title line come before the first item.+ const item = MENU[e.y - (m.y + 2)];+ if (item) openView === item.id ? close() : open(item.id);+ },+ { isActive: navActive },+ );++ const viewHeight = Math.max(6, rows - 1);+ // Inside a panel: two border lines and a title line.+ const viewLines = viewHeight - 3;+ const view = MENU.find((m) => m.id === openView);++ return (+ <Box flexDirection="column" width={columns} height={rows}>+ <Box flexGrow={1}>+ <Box ref={sidebarRef} flexShrink={0}>+ <Sidebar items={MENU} cursor={menuCursor} openId={openView} focused={!openView || menuFocused} width={SIDEBAR_WIDTH} />+ </Box>+ {view && (+ <Panel+ title={view.title}+ borderColor={menuFocused ? "gray" : "cyan"}+ width={Math.max(20, columns - SIDEBAR_WIDTH)}+ height={viewHeight}+ overflow="hidden"+ >+ <NodesView+ backend={backend}+ mode={nodesMode}+ onModeChange={setNodesMode}+ height={viewLines}+ active={!menuFocused}+ onClose={close}+ onSearchingChange={setSearching}+ onDetailChange={setDetail}+ />+ </Panel>+ )}+ </Box>+ <Box justifyContent="center" flexShrink={0}>+ <Text dimColor wrap="truncate-end">+ {HINTS[focus]}+ </Text>+ </Box>+ </Box>+ );+}diff --git a/tools/xtop/src/components/DataTable.tsx b/tools/xtop/src/components/DataTable.tsxnew file mode 100644index 00000000..6aa0010a--- /dev/null+++ b/tools/xtop/src/components/DataTable.tsx@@ -0,0 +1,340 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo++import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { Box, Text, measureElement, useInput, usePaste, type DOMElement } from "ink";+import { useMouse } from "../lib/useMouse.ts";++export type SortDir = "asc" | "desc";++export type Column<T> = {+ id: string;+ title: string;+ /** Fixed width, or flexible when omitted. */+ width?: number;+ align?: "right";+ /** Direction used when the column is first sorted. */+ defaultDir: SortDir;+ sortKey: (row: T) => number | string;+ render: (row: T) => ReactNode;+};++type Props<T> = {+ rows: readonly T[];+ columns: readonly Column<T>[];+ rowKey: (row: T) => string;+ /** Lines available for the whole table: summary, search, header, rows, footer. */+ height: number;+ /** Whether keyboard and mouse drive this table. */+ active: boolean;+ initialSort: { col: string; dir: SortDir };+ /** Breaks ties after the sorted column. */+ tiebreak?: (a: T, b: T) => number;+ /** Line above the table; receives the visible (filtered, sorted) rows. */+ summary?: (rows: readonly T[], sortedBy: string) => ReactNode;+ /** Enables `/` search; returns whether a row matches the lowercased query. */+ matches?: (row: T, query: string) => boolean;+ /** Search text to start with (e.g. when drilling into a group). */+ initialQuery?: string;+ /**+ * Optional row of view tabs above the table. Keyboard: k past the header+ * reaches it, h/l picks, Enter switches. Clicking a tab switches.+ */+ tabs?: { labels: readonly string[]; selected: number; onSelect: (i: number) => void };+ /** Start with the cursor on the tabs (e.g. right after switching tab). */+ startOnTabs?: boolean;+ /** Dim text at the bottom right, on the scroll footer's line. */+ footerHint?: string;+ /** Search box takes every key while typing. */+ onSearchingChange?: (searching: boolean) => void;+ onClose: () => void;+ /** Enter or click on a row. */+ onOpen?: (row: T) => void;+};++const compare = (a: number | string, b: number | string) =>+ typeof a === "number" && typeof b === "number"+ ? a - b+ : String(a).localeCompare(String(b), undefined, { numeric: true });++function Cell<T>({+ col,+ children,+ inverse,+ cellRef,+}: {+ col: Column<T>;+ children: ReactNode;+ inverse?: boolean;+ cellRef?: (el: DOMElement | null) => void;+}) {+ return (+ <Box+ ref={cellRef}+ width={col.width}+ flexGrow={col.width ? 0 : 1}+ flexBasis={col.width ? undefined : 0}+ flexShrink={col.width ? 0 : 1}+ minWidth={col.width ? undefined : 8}+ justifyContent={col.align === "right" ? "flex-end" : undefined}+ paddingRight={1}+ >+ <Text inverse={inverse} wrap="truncate-end">+ {children}+ </Text>+ </Box>+ );+}++/** Cursor positions above the body rows. */+const HEADER = -1;+const TABS = -2;++/**+ * Sortable, scrollable, optionally searchable table. Keyboard: j/k ↑↓ rows,+ * k past the top reaches the header where h/l ←→ pick a column and Enter+ * sorts; g/G, ^d/^u, PgUp/PgDn; / searches; Enter or l opens a row; h or Esc+ * closes. Mouse: click a header to sort, click a row to open, wheel scrolls.+ */+export function DataTable<T>({+ rows: input,+ columns,+ rowKey,+ height,+ active,+ initialSort,+ tiebreak,+ summary,+ matches,+ initialQuery = "",+ tabs,+ startOnTabs = false,+ footerHint,+ onSearchingChange,+ onClose,+ onOpen,+}: Props<T>) {+ const [cursor, setCursor] = useState(tabs && startOnTabs ? TABS : 0);+ const [tabFocus, setTabFocus] = useState(tabs?.selected ?? 0);+ const tabRefs = useRef<(DOMElement | null)[]>([]);+ const [top, setTop] = useState(0);+ const [headerCol, setHeaderCol] = useState(0);+ const [sort, setSort] = useState(initialSort);+ const [query, setQuery] = useState(initialQuery);+ const [searching, setSearching] = useState(false);+ const headerRefs = useRef<(DOMElement | null)[]>([]);++ useEffect(() => onSearchingChange?.(searching), [searching, onSearchingChange]);+ useEffect(() => () => onSearchingChange?.(false), [onSearchingChange]);++ const rows = useMemo(() => {+ const col = columns.find((c) => c.id === sort.col) ?? columns[0]!;+ const sign = sort.dir === "asc" ? 1 : -1;+ const q = query.trim().toLowerCase();+ return input+ .filter((r) => !q || !matches || matches(r, q))+ .sort((a, b) => sign * compare(col.sortKey(a), col.sortKey(b)) || (tiebreak?.(a, b) ?? 0));+ }, [input, columns, sort, query, matches, tiebreak]);++ // Tabs, summary, search, header and scroll footer each take a line.+ const chrome = (tabs ? 1 : 0) + (summary ? 1 : 0) + (matches ? 1 : 0) + 2;+ const visible = Math.max(1, height - chrome);+ const last = rows.length - 1;++ useEffect(() => {+ const c = Math.max(0, cursor);+ setTop((t) => Math.max(0, Math.min(Math.max(t, c - visible + 1), c, Math.max(0, rows.length - visible))));+ }, [cursor, visible, rows.length]);++ // A new query starts at the top of the results (not on mount, which would+ // undo startOnTabs).+ const lastQuery = useRef(query);+ useEffect(() => {+ if (lastQuery.current === query) return;+ lastQuery.current = query;+ setCursor(0);+ }, [query]);++ const sortBy = (i: number) => {+ const col = columns[i]!;+ setHeaderCol(i);+ setSort((s) => (s.col === col.id ? { col: col.id, dir: s.dir === "asc" ? "desc" : "asc" } : { col: col.id, dir: col.defaultDir }));+ };+ const move = (d: number) => setCursor((c) => Math.max(tabs ? TABS : HEADER, Math.min(last, c + d)));+ const moveRows = (d: number) => setCursor((c) => Math.max(0, Math.min(last, Math.max(0, c) + d)));+ const moveCol = (d: number) => setHeaderCol((i) => (i + d + columns.length) % columns.length);++ useInput(+ (ch, key) => {+ if (searching) {+ if (key.return) setSearching(false);+ else if (key.escape) {+ setQuery("");+ setSearching(false);+ } else if (key.backspace || key.delete) setQuery((q) => q.slice(0, -1));+ else if (key.ctrl && ch === "u") setQuery("");+ else if (!key.ctrl && !key.meta && ch) setQuery((q) => q + ch.replace(/[\x00-\x1f]/g, ""));+ return;+ }+ const half = Math.max(1, Math.floor(visible / 2));+ if (key.escape) return query ? setQuery("") : onClose();+ if (cursor === TABS && tabs) {+ const n = tabs.labels.length;+ if (key.leftArrow || ch === "h") return setTabFocus((i) => (i + n - 1) % n);+ if (key.rightArrow || ch === "l") return setTabFocus((i) => (i + 1) % n);+ if (key.return) return tabFocus !== tabs.selected && tabs.onSelect(tabFocus);+ } else if (cursor === HEADER) {+ if (key.leftArrow || ch === "h") return moveCol(-1);+ if (key.rightArrow || ch === "l") return moveCol(1);+ if (key.return) return sortBy(headerCol);+ } else if (ch === "h") return onClose();+ else if (key.return || ch === "l") {+ const row = rows[cursor];+ if (row && onOpen) return onOpen(row);+ }+ if (key.upArrow) move(-1);+ else if (key.downArrow) move(1);+ else if (key.pageUp) moveRows(-visible);+ else if (key.pageDown) moveRows(visible);+ else if (key.home) setCursor(0);+ else if (key.end) setCursor(last);+ else if (key.ctrl && ch === "d") moveRows(half);+ else if (key.ctrl && ch === "u") moveRows(-half);+ else if (key.ctrl && ch === "f") moveRows(visible);+ else if (key.ctrl && ch === "b") moveRows(-visible);+ else if (!key.ctrl && !key.meta) {+ // Vim keys; fast typing can deliver several in one chunk.+ for (const c of ch) {+ if (c === "j") move(1);+ else if (c === "k") move(-1);+ else if (c === "g") setCursor(0);+ else if (c === "G") setCursor(last);+ else if (c === "/" && matches) setSearching(true);+ }+ }+ },+ { isActive: active },+ );++ usePaste((text) => setQuery((q) => q + text.replace(/\s+/g, " ").trim()), { isActive: active && searching });++ useMouse(+ (e) => {+ const header = headerRefs.current[0];+ if (!header) return;+ const headerY = measureElement(header).y;+ if (e.kind === "wheel") return moveRows(e.direction === "down" ? 3 : -3);+ if (e.kind !== "press" || e.button !== "left") return;+ if (tabs) {+ const i = tabRefs.current.findIndex((el) => {+ if (!el) return false;+ const m = measureElement(el);+ return e.y === m.y && e.x >= m.x && e.x < m.x + m.width;+ });+ if (i >= 0) return i !== tabs.selected && tabs.onSelect(i);+ }+ if (matches && e.y === headerY - 1) return setSearching(true);+ if (e.y === headerY) {+ const i = headerRefs.current.findIndex((el) => {+ if (!el) return false;+ const m = measureElement(el);+ return e.x >= m.x && e.x < m.x + m.width;+ });+ if (i >= 0) {+ sortBy(i);+ setCursor(HEADER);+ }+ } else if (e.y > headerY && e.y <= headerY + Math.min(visible, rows.length - top)) {+ const i = top + (e.y - headerY - 1);+ setCursor(i);+ if (rows[i] && onOpen) onOpen(rows[i]);+ }+ },+ { isActive: active },+ );++ const sortCol = columns.find((c) => c.id === sort.col) ?? columns[0]!;+ const sortedBy = `${sortCol.title.toLowerCase()} ${sort.dir === "asc" ? "▲" : "▼"}`;++ return (+ <Box flexDirection="column">+ {tabs && <Tabs labels={tabs.labels} selected={tabs.selected} focused={active && cursor === TABS ? tabFocus : null} tabRefs={tabRefs} />}+ {summary && <Text wrap="truncate-end">{summary(rows, sortedBy)}</Text>}+ {matches && (+ <Text wrap="truncate-end">+ <Text color={searching ? "cyan" : "gray"}>/ </Text>+ {query ? <Text>{query}</Text> : !searching && <Text dimColor>search</Text>}+ {searching && <Text inverse> </Text>}+ {query && !searching && <Text dimColor> esc clears</Text>}+ </Text>+ )}+ <Box>+ {columns.map((col, i) => {+ const sorted = sort.col === col.id;+ const focused = active && cursor === HEADER && headerCol === i;+ return (+ <Cell key={col.id} col={col} inverse={focused} cellRef={(el) => (headerRefs.current[i] = el)}>+ <Text color={sorted ? "cyan" : "gray"} bold={sorted}>+ {col.title}+ {sorted ? (sort.dir === "asc" ? " ▲" : " ▼") : ""}+ </Text>+ </Cell>+ );+ })}+ </Box>+ {/* Rows live in their own fixed box so the footer below always stays below them. */}+ <Box flexDirection="column" height={Math.min(visible, Math.max(1, rows.length))} flexShrink={0} overflow="hidden">+ {rows.length === 0 && <Text dimColor>{query ? `nothing matches “${query}”` : "no rows"}</Text>}+ {rows.slice(top, top + visible).map((r, i) => {+ const selected = active && top + i === cursor;+ return (+ <Box key={rowKey(r)} flexShrink={0}>+ {columns.map((col) => (+ <Cell key={col.id} col={col} inverse={selected}>+ {col.render(r)}+ </Cell>+ ))}+ </Box>+ );+ })}+ </Box>+ {(rows.length > visible || footerHint) && (+ <Box justifyContent="space-between">+ <Text dimColor>+ {rows.length > visible ? `${top + 1}–${Math.min(rows.length, top + visible)} of ${rows.length}` : ""}+ </Text>+ {footerHint && <Text dimColor>{footerHint}</Text>}+ </Box>+ )}+ </Box>+ );+}++/**+ * View tabs: the selected one is cyan with a filled dot; the one under the+ * keyboard cursor is inverse. Exported so a view can show the same row while+ * its data loads.+ */+export function Tabs({+ labels,+ selected,+ focused = null,+ tabRefs,+}: {+ labels: readonly string[];+ selected: number;+ focused?: number | null;+ tabRefs?: { current: (DOMElement | null)[] };+}) {+ return (+ <Box>+ {labels.map((label, i) => (+ <Box key={label} ref={(el) => void (tabRefs && (tabRefs.current[i] = el))} marginRight={1}>+ <Text inverse={focused === i} color={i === selected ? "cyan" : "gray"} bold={i === selected}>+ {i === selected ? "●" : "○"} {label}+ </Text>+ </Box>+ ))}+ </Box>+ );+}diff --git a/tools/xtop/src/components/NodeDetail.tsx b/tools/xtop/src/components/NodeDetail.tsxnew file mode 100644index 00000000..b667fdb6--- /dev/null+++ b/tools/xtop/src/components/NodeDetail.tsx@@ -0,0 +1,84 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// One node: what it runs and the line of each check the backend ran.++import type { ReactNode } from "react";+import { Box, Text, useInput } from "ink";+import { imageLabel, type FleetNode } from "../lib/fleet.ts";+import { STATUS_STYLE } from "./style.ts";++type Props = {+ /** null when the node left node_status since it was opened. */+ node: FleetNode | null;+ height: number;+ active: boolean;+ onClose: () => void;+};++function Field({ name, children }: { name: string; children: ReactNode }) {+ return (+ <Box>+ <Box width={10} flexShrink={0}>+ <Text dimColor>{name}</Text>+ </Box>+ <Text wrap="truncate-end">{children}</Text>+ </Box>+ );+}++const checkColor = (line: string) => (/^\d+ [a-z]+: FAIL/.test(line) ? "red" : /: pass/.test(line) ? "green" : undefined);++export function NodeDetail({ node, height, active, onClose }: Props) {+ useInput(+ (input, key) => {+ if (key.escape || key.return || input === "h" || key.leftArrow) onClose();+ },+ { isActive: active },+ );++ if (!node)+ return (+ <Box flexDirection="column" height={height}>+ <Text color="yellow">the node is no longer in node_status</Text>+ <Text dimColor>esc back</Text>+ </Box>+ );++ const style = STATUS_STYLE[node.status];+ const t = node.tree;+ return (+ <Box flexDirection="column" height={height} overflow="hidden">+ <Text>+ <Text bold>{node.name}</Text>+ <Text color={style.color}>+ {" "}+ {style.icon} {node.status}+ </Text>+ <Text color={node.trust === "enrolled" ? "green" : "yellow"}> · {node.trust}</Text>+ </Text>+ <Field name="host">{node.hostName}</Field>+ <Field name="key">{node.akName}</Field>+ <Field name="image">{imageLabel(node.imageId, node.imageVersion)}</Field>+ <Field name="kernel">{node.kernel}</Field>+ <Field name="build">{node.version}</Field>+ <Field name="tree">+ {t.lastSeq === null+ ? "follows no tree"+ : `seq ${t.lastSeq} of ${t.headSeq ?? "?"}, generation ${t.generation ?? "?"}, ${node.loaded} loaded`}+ </Field>+ <Field name="seen">{node.lastSeen.toLocaleString()}</Field>+ <Box marginTop={1} flexDirection="column">+ <Text dimColor>checks</Text>+ {node.log.map((line, i) => (+ <Text key={i} color={checkColor(line)} wrap="truncate-end">+ {line}+ </Text>+ ))}+ </Box>+ <Box marginTop={1}>+ <Text dimColor>esc back</Text>+ </Box>+ </Box>+ );+}diff --git a/tools/xtop/src/components/NodesView.tsx b/tools/xtop/src/components/NodesView.tsxnew file mode 100644index 00000000..0eaad957--- /dev/null+++ b/tools/xtop/src/components/NodesView.tsx@@ -0,0 +1,429 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// The fleet from shirudo.node_status: one row per node, or one per image+// with its members rolled up. Enter on a node shows its check lines.++import { useEffect, useMemo, useRef, useState } from "react";+import { Box, Text, useInput } from "ink";+import type { Backend } from "../lib/backend.ts";+import {+ STATUS_RANK,+ STATUSES,+ failedCheckName,+ groupByImage,+ healthPercent,+ imageLabel,+ type FleetNode,+ type FleetReport,+ type ImageGroup,+ type NodeStatus,+ type Shields,+} from "../lib/fleet.ts";+import { DataTable, Tabs, type Column } from "./DataTable.tsx";+import { NodeDetail } from "./NodeDetail.tsx";+import { STATUS_STYLE } from "./style.ts";++export type NodesMode = "nodes" | "images";++/** node_status is recomputed once a minute; asking more often shows nothing new. */+const REFRESH_MS = 60_000;++type Props = {+ backend: Backend;+ mode: NodesMode;+ onModeChange: (mode: NodesMode) => void;+ /** Lines available inside the panel. */+ height: number;+ active: boolean;+ onClose: () => void;+ onSearchingChange: (searching: boolean) => void;+ /** The check lines of a node are open. */+ onDetailChange?: (open: boolean) => void;+};++const healthColor = (h: number) => (h >= 80 ? "green" : h >= 50 ? "yellow" : "red");+const EIGHTHS = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"];++function MiniBar({ value, width }: { value: number; width: number }) {+ const eighths = Math.round((Math.max(0, Math.min(100, value)) / 100) * width * 8);+ const full = Math.floor(eighths / 8);+ const partial = EIGHTHS[eighths % 8]!;+ return (+ <>+ <Text color={healthColor(value)}>{"█".repeat(full) + partial}</Text>+ <Text dimColor>{"░".repeat(width - full - (partial ? 1 : 0))}</Text>+ </>+ );+}++function HealthCell({ health, bar }: { health: number; bar: number }) {+ return (+ <>+ <MiniBar value={health} width={bar} />+ <Text color={healthColor(health)}> {String(health).padStart(3)}%</Text>+ </>+ );+}++const ago = (d: Date) => {+ const s = Math.max(0, Math.round((Date.now() - d.getTime()) / 1000));+ return s < 60 ? `${s}s` : s < 3600 ? `${Math.round(s / 60)}m` : s < 172800 ? `${Math.round(s / 3600)}h` : `${Math.round(s / 86400)}d`;+};++function StatusCell({ status }: { status: NodeStatus }) {+ return (+ <Text color={STATUS_STYLE[status].color}>+ {STATUS_STYLE[status].icon} {status}+ </Text>+ );+}++function ShieldsCell({ s }: { s: Shields }) {+ return (+ <>+ <Text color={s.applied ? "green" : "gray"}>{s.applied}✓</Text>+ {s.pending > 0 && <Text color="yellow"> {s.pending}…</Text>}+ {s.idle > 0 && <Text color="red"> {s.idle}✗</Text>}+ </>+ );+}++function ExposedCell({ exposed, unknown }: { exposed: number; unknown: number }) {+ return (+ <>+ {unknown > 0 && <Text color="yellow">? </Text>}+ <Text color={exposed ? "yellow" : "green"}>{exposed}</Text>+ </>+ );+}++function TreeCell({ last, head, atLeast = false }: { last: number | null; head: number | null; atLeast?: boolean }) {+ if (last === null) return <Text dimColor>no tree</Text>;+ if (head === null) return <Text dimColor>#{last}</Text>;+ if (last < head)+ return (+ <Text color="yellow">+ {atLeast ? "≥" : ""}#{last}/#{head}+ </Text>+ );+ return <Text color="green">✓ #{head}</Text>;+}++const shieldsKey = (s: Shields) => s.idle * 1000 + s.pending;+const imageCell = (id: string | null, version: string | null) =>+ id === null ? <Text dimColor>{imageLabel(id, version)}</Text> : <Text color="cyan">{imageLabel(id, version)}</Text>;++// ---- per-node table --------------------------------------------------------++const NODE_COLUMNS: readonly Column<FleetNode>[] = [+ { id: "status", title: "STATUS", width: 12, defaultDir: "asc", sortKey: (n) => STATUS_RANK[n.status], render: (n) => <StatusCell status={n.status} /> },+ {+ id: "trust",+ title: "TRUST",+ width: 10,+ defaultDir: "asc",+ sortKey: (n) => n.trust,+ render: (n) => <Text color={n.trust === "enrolled" ? "green" : "yellow"}>{n.trust}</Text>,+ },+ { id: "name", title: "NODE", defaultDir: "asc", sortKey: (n) => n.name, render: (n) => <Text bold>{n.name}</Text> },+ {+ id: "check",+ title: "CHECK",+ width: 13,+ defaultDir: "desc",+ sortKey: (n) => n.failedCheck,+ render: (n) => (n.failedCheck ? <Text color="red">{failedCheckName(n)}</Text> : <Text dimColor>—</Text>),+ },+ { id: "image", title: "IMAGE", width: 20, defaultDir: "asc", sortKey: (n) => imageLabel(n.imageId, n.imageVersion), render: (n) => imageCell(n.imageId, n.imageVersion) },+ { id: "kernel", title: "KERNEL", width: 10, defaultDir: "asc", sortKey: (n) => n.kernel, render: (n) => <Text>{n.kernel}</Text> },+ { id: "version", title: "BUILD", width: 9, defaultDir: "asc", sortKey: (n) => n.version, render: (n) => <Text dimColor>{n.version.slice(0, 8)}</Text> },+ {+ id: "tree",+ title: "TREE",+ width: 10,+ defaultDir: "asc",+ sortKey: (n) => (n.tree.lastSeq === null ? -1 : n.tree.lastSeq - (n.tree.headSeq ?? n.tree.lastSeq)),+ render: (n) => <TreeCell last={n.tree.lastSeq} head={n.tree.headSeq} />,+ },+ { id: "shields", title: "SHIELDS", width: 12, defaultDir: "desc", sortKey: (n) => shieldsKey(n.shields), render: (n) => <ShieldsCell s={n.shields} /> },+ {+ id: "exposed",+ title: "EXPOSED",+ width: 8,+ align: "right",+ defaultDir: "desc",+ sortKey: (n) => n.exposed * 1000 + n.unknown,+ render: (n) => <ExposedCell exposed={n.exposed} unknown={n.unknown} />,+ },+ {+ id: "seen",+ title: "SEEN",+ width: 6,+ align: "right",+ defaultDir: "desc",+ sortKey: (n) => n.lastSeen.getTime(),+ render: (n) => <Text color={n.status === "stale" ? "red" : undefined}>{ago(n.lastSeen)}</Text>,+ },+];++const nodeMatches = (n: FleetNode, q: string) =>+ [+ n.name,+ n.hostName,+ n.akName,+ n.status,+ n.trust,+ imageLabel(n.imageId, n.imageVersion),+ n.kernel,+ n.version,+ n.failedCheck ? (n.log[n.failedCheck - 1] ?? "") : "",+ ].some((s) => s.toLowerCase().includes(q));++// ---- per-image table -------------------------------------------------------++const IMAGE_COLUMNS: readonly Column<ImageGroup>[] = [+ { id: "status", title: "STATUS", width: 12, defaultDir: "asc", sortKey: (g) => STATUS_RANK[g.status], render: (g) => <StatusCell status={g.status} /> },+ { id: "image", title: "IMAGE", defaultDir: "asc", sortKey: (g) => g.key, render: (g) => imageCell(g.imageId, g.imageVersion) },+ {+ id: "nodes",+ title: "NODES",+ width: 11,+ defaultDir: "desc",+ sortKey: (g) => g.nodes,+ render: (g) => (+ <>+ <Text bold>{String(g.nodes).padStart(2)}</Text>+ {STATUSES.filter((s) => s !== "healthy" && g.statuses[s] > 0).map((s) => (+ <Text key={s} color={STATUS_STYLE[s].color}>+ {" "}+ {g.statuses[s]}+ {STATUS_STYLE[s].icon}+ </Text>+ ))}+ </>+ ),+ },+ { id: "health", title: "HEALTH", width: 12, defaultDir: "asc", sortKey: (g) => g.health, render: (g) => <HealthCell health={g.health} bar={5} /> },+ {+ id: "kernel",+ title: "KERNEL",+ width: 10,+ defaultDir: "asc",+ sortKey: (g) => g.kernel ?? "~",+ render: (g) => (g.kernel === null ? <Text color="yellow">mixed</Text> : <Text>{g.kernel}</Text>),+ },+ {+ id: "tree",+ title: "TREE",+ width: 11,+ defaultDir: "asc",+ sortKey: (g) => (g.tree.minLastSeq === null ? -1 : g.tree.minLastSeq - (g.tree.headSeq ?? g.tree.minLastSeq)),+ render: (g) => <TreeCell last={g.tree.minLastSeq} head={g.tree.headSeq} atLeast />,+ },+ { id: "shields", title: "SHIELDS", width: 12, defaultDir: "desc", sortKey: (g) => shieldsKey(g.shields), render: (g) => <ShieldsCell s={g.shields} /> },+ {+ id: "exposed",+ title: "EXPOSED",+ width: 8,+ align: "right",+ defaultDir: "desc",+ sortKey: (g) => g.exposed * 1000 + g.unknown,+ render: (g) => <ExposedCell exposed={g.exposed} unknown={g.unknown} />,+ },+ {+ id: "seen",+ title: "SEEN",+ width: 6,+ align: "right",+ defaultDir: "desc",+ sortKey: (g) => g.lastSeen.getTime(),+ render: (g) => <Text color={g.statuses.stale === g.nodes ? "red" : undefined}>{ago(g.lastSeen)}</Text>,+ },+];++const imageMatches = (g: ImageGroup, q: string) =>+ [g.key, g.status, g.kernel ?? "mixed"].some((s) => s.toLowerCase().includes(q));++// ---- view ------------------------------------------------------------------++type Query<T> = { data: T | null; error: string | null; loading: boolean };++/**+ * Loads when enabled, again on every `reload` change and every REFRESH_MS.+ * A failed refresh keeps the rows it had and reports the error beside them.+ */+function useRefreshing<T>(enabled: boolean, reload: number, load: () => Promise<T>): Query<T> {+ const [state, setState] = useState<Query<T>>({ data: null, error: null, loading: false });+ const loadRef = useRef(load);+ loadRef.current = load;+ useEffect(() => {+ if (!enabled) return;+ let alive = true;+ const run = () => {+ setState((s) => ({ ...s, loading: true }));+ loadRef.current().then(+ (data) => alive && setState({ data, error: null, loading: false }),+ (e: unknown) =>+ alive && setState((s) => ({ ...s, error: e instanceof Error ? e.message : String(e), loading: false })),+ );+ };+ run();+ const id = setInterval(run, REFRESH_MS);+ return () => {+ alive = false;+ clearInterval(id);+ };+ }, [enabled, reload]);+ return state;+}++function HealthSummary({ health }: { health: number | null }) {+ if (health === null) return <Text dimColor>health —</Text>;+ return (+ <>+ health <HealthCell health={health} bar={8} />+ </>+ );+}++export function NodesView({ backend, mode, onModeChange, height, active, onClose, onSearchingChange, onDetailChange }: Props) {+ const [reload, setReload] = useState(0);+ const fleet = useRefreshing<FleetReport>(true, reload, () => backend.getFleet());+ const images = useMemo(() => (fleet.data ? groupByImage(fleet.data.nodes) : []), [fleet.data]);+ const [searching, setSearching] = useState(false);+ // Set when drilling into an image; seeds the nodes table's search.+ const [drill, setDrill] = useState("");+ // After switching from the tabs, keep the cursor there in the new table.+ const [onTabs, setOnTabs] = useState(false);+ const [detail, setDetail] = useState<string | null>(null);+ // The open node as of the newest query, so a refresh updates the pane.+ const detailNode = detail ? (fleet.data?.nodes.find((n) => n.akName === detail) ?? null) : null;++ const showDetail = (ak: string | null) => {+ setDetail(ak);+ onDetailChange?.(ak !== null);+ };+ const reportSearching = (s: boolean) => {+ setSearching(s);+ onSearchingChange(s);+ };+ const switchTo = (m: NodesMode, fromTabs = false) => {+ setDrill("");+ setOnTabs(fromTabs);+ onModeChange(m);+ };+ const modes: NodesMode[] = ["nodes", "images"];+ const tabs = {+ labels: ["nodes", "by image"],+ selected: modes.indexOf(mode),+ onSelect: (i: number) => switchTo(modes[i]!, true),+ };++ useInput(+ (input) => {+ if (input === "t") switchTo(mode === "nodes" ? "images" : "nodes");+ if (input === "r") setReload((r) => r + 1);+ },+ { isActive: active && !searching && !detail },+ );++ const tableHeight = Math.max(4, height);+ const asOf = (r: FleetReport) => (+ <>+ <Text dimColor> · as of {r.generatedAt.toTimeString().slice(0, 8)}</Text>+ {fleet.loading && <Text dimColor> · querying…</Text>}+ </>+ );++ // First on the line, so a narrow terminal does not cut the reason off.+ const failed = fleet.error && <Text color="red">refresh failed: {fleet.error} · </Text>;++ if (!fleet.data)+ return (+ <Box flexDirection="column">+ <Tabs labels={tabs.labels} selected={tabs.selected} />+ {fleet.error ? <Text color="red">node query failed: {fleet.error}</Text> : <Text dimColor>querying backend…</Text>}+ </Box>+ );+ const report = fleet.data;++ return (+ <Box flexDirection="column">+ {detail && (+ <NodeDetail node={detailNode} height={tableHeight} active={active} onClose={() => showDetail(null)} />+ )}+ {/* Hidden, not unmounted, so the table keeps its cursor, sort and search. */}+ <Box flexDirection="column" display={detail ? "none" : "flex"}>+ {mode === "nodes" ? (+ <DataTable+ key={`nodes:${drill}`}+ tabs={tabs}+ startOnTabs={onTabs}+ footerHint="t by image · r refresh"+ rows={report.nodes}+ columns={NODE_COLUMNS}+ rowKey={(n) => n.akName}+ height={tableHeight}+ active={active && !detail}+ initialSort={{ col: "status", dir: "asc" }}+ initialQuery={drill}+ tiebreak={(a, b) => b.failedCheck - a.failedCheck || a.name.localeCompare(b.name)}+ matches={nodeMatches}+ onSearchingChange={reportSearching}+ onClose={onClose}+ onOpen={(n) => showDetail(n.akName)}+ summary={(rows, sortedBy) => {+ const count = (s: NodeStatus) => rows.filter((n) => n.status === s).length;+ return (+ <>+ {failed}+ <Text bold>{rows.length}</Text> nodes · <HealthSummary health={healthPercent(rows)} /> ·{" "}+ <Text color="green">{count("healthy")} healthy</Text> · <Text color="red">{count("unhealthy")} unhealthy</Text> ·{" "}+ <Text color="gray">{count("stale")} stale</Text> ·{" "}+ <Text color="yellow">{rows.filter((n) => n.trust === "untrusted").length} untrusted</Text>+ <Text dimColor> · sorted by {sortedBy}</Text>+ {asOf(report)}+ </>+ );+ }}+ />+ ) : (+ <DataTable+ tabs={tabs}+ startOnTabs={onTabs}+ footerHint="t nodes · r refresh"+ rows={images}+ columns={IMAGE_COLUMNS}+ rowKey={(g) => g.key}+ height={tableHeight}+ active={active && !detail}+ initialSort={{ col: "status", dir: "asc" }}+ tiebreak={(a, b) => a.health - b.health || b.nodes - a.nodes}+ matches={imageMatches}+ onSearchingChange={reportSearching}+ onClose={onClose}+ onOpen={(g) => {+ setOnTabs(false);+ setDrill(g.key);+ onModeChange("nodes");+ }}+ summary={(rows, sortedBy) => {+ const members = report.nodes.filter((n) => rows.some((g) => g.key === imageLabel(n.imageId, n.imageVersion)));+ return (+ <>+ {failed}+ <Text bold>{rows.length}</Text> images · {members.length} nodes · <HealthSummary health={healthPercent(members)} />{" "}+ · <Text color="red">{rows.filter((g) => g.statuses.unhealthy).length} with unhealthy</Text> ·{" "}+ <Text color="gray">{rows.filter((g) => g.statuses.stale).length} with stale</Text>+ <Text dimColor> · sorted by {sortedBy}</Text>+ {asOf(report)}+ </>+ );+ }}+ />+ )}+ </Box>+ </Box>+ );+}diff --git a/tools/xtop/src/components/Panel.tsx b/tools/xtop/src/components/Panel.tsxnew file mode 100644index 00000000..30c64053--- /dev/null+++ b/tools/xtop/src/components/Panel.tsx@@ -0,0 +1,28 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo++import { forwardRef, type ReactNode } from "react";+import { Box, Text, type BoxProps, type DOMElement } from "ink";++type Props = BoxProps & { title: string; children: ReactNode };++/** Rounded bordered box with a title line. */+export const Panel = forwardRef<DOMElement, Props>(function Panel(+ { title, children, ...box },+ ref,+) {+ return (+ <Box+ ref={ref}+ borderStyle="round"+ borderColor="gray"+ flexDirection="column"+ paddingX={1}+ flexShrink={0}+ {...box}+ >+ <Text color="gray">{title}</Text>+ {children}+ </Box>+ );+});diff --git a/tools/xtop/src/components/Sidebar.tsx b/tools/xtop/src/components/Sidebar.tsxnew file mode 100644index 00000000..fbb0b10d--- /dev/null+++ b/tools/xtop/src/components/Sidebar.tsx@@ -0,0 +1,37 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo++import { Box, Text } from "ink";+import { Panel } from "./Panel.tsx";++export type MenuItem = { id: string; label: string; badge?: string };++type Props = {+ items: readonly MenuItem[];+ cursor: number;+ /** Id of the item whose view is open, if any. */+ openId: string | null;+ /** Whether the menu has keyboard focus. */+ focused: boolean;+ width: number;+};++export function Sidebar({ items, cursor, openId, focused, width }: Props) {+ return (+ <Panel title="menu" width={width}>+ {items.map((item, i) => {+ const open = item.id === openId;+ const selected = focused && i === cursor;+ return (+ <Box key={item.id}>+ <Text color={selected ? "cyan" : undefined} bold={selected || open} inverse={selected}>+ {open ? "▾ " : "▸ "}+ {item.label}+ </Text>+ {item.badge && <Text color="yellow"> {item.badge}</Text>}+ </Box>+ );+ })}+ </Panel>+ );+}diff --git a/tools/xtop/src/components/style.ts b/tools/xtop/src/components/style.tsnew file mode 100644index 00000000..be83ed1c--- /dev/null+++ b/tools/xtop/src/components/style.ts@@ -0,0 +1,10 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo++import type { NodeStatus } from "../lib/fleet.ts";++export const STATUS_STYLE: Record<NodeStatus, { icon: string; color: string }> = {+ unhealthy: { icon: "✗", color: "red" },+ stale: { icon: "○", color: "gray" },+ healthy: { icon: "●", color: "green" },+};diff --git a/tools/xtop/src/index.tsx b/tools/xtop/src/index.tsxnew file mode 100644index 00000000..3ae0e140--- /dev/null+++ b/tools/xtop/src/index.tsx@@ -0,0 +1,40 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// xtop: a terminal view of the shirudo backend's ClickHouse.++import { render } from "ink";+import { App } from "./App.tsx";+import { ClickHouseBackend } from "./lib/backend.ts";+import { configFromEnv } from "./lib/clickhouse.ts";+import { createMouseInput } from "./lib/mouse.ts";+import { MouseContext } from "./lib/useMouse.ts";+import { APP_TITLE, setTerminalTitle } from "./lib/terminal.ts";++let backend: ClickHouseBackend;+try {+ backend = new ClickHouseBackend(configFromEnv());+} catch (e) {+ console.error(`xtop: ${e instanceof Error ? e.message : String(e)}`);+ process.exit(2);+}++const restoreTitle = setTerminalTitle(APP_TITLE);+const mouse = createMouseInput(process.stdin, process.stdout);+const cleanup = () => {+ mouse.disable();+ restoreTitle();+};+process.on("exit", cleanup);+// A killed terminal or a dropped SSH session still restores the terminal.+for (const sig of ["SIGTERM", "SIGHUP"] as const) process.on(sig, () => process.exit(0));++const app = render(+ <MouseContext.Provider value={mouse.events}>+ <App backend={backend} />+ </MouseContext.Provider>,+ { alternateScreen: true, stdin: mouse.input, kittyKeyboard: { mode: "auto" } },+);+await app.waitUntilExit();+cleanup();+process.exit(0);diff --git a/tools/xtop/src/lib/backend.ts b/tools/xtop/src/lib/backend.tsnew file mode 100644index 00000000..78d1765c--- /dev/null+++ b/tools/xtop/src/lib/backend.ts@@ -0,0 +1,80 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// What the views ask of the backend, and the client that asks ClickHouse.++import NODES_SQL from "../../sql/nodes.sql" with { type: "text" };+import { queryRows, type ClickHouseConfig } from "./clickhouse.ts";+import { STATUSES, TRUSTS, type FleetNode, type FleetReport, type NodeStatus, type Trust } from "./fleet.ts";++export interface Backend {+ /** Every node of shirudo.node_status. */+ getFleet(): Promise<FleetReport>;+}++/** A row of sql/nodes.sql. */+export type NodeRow = {+ node_id: string;+ ak_name: string;+ host_name: string;+ status: string;+ trust: string;+ failed_check: number;+ log: string[];+ last_seen_ms: number;+ updated_ms: number;+ generation: number | null;+ last_seq: number | null;+ head_seq: number | null;+ loaded: number;+ kernel_release: string;+ version_id: string;+ image_id: string | null;+ image_version: string | null;+ shields_applied: number;+ shields_pending: number;+ shields_idle: number;+ exposed: number;+ unknown: number;+};++function oneOf<T extends string>(allowed: readonly T[], value: string, what: string): T {+ if (!(allowed as readonly string[]).includes(value)) throw new Error(`unknown ${what} "${value}"`);+ return value as T;+}++export function toFleetNode(r: NodeRow): FleetNode {+ return {+ name: r.node_id,+ akName: r.ak_name,+ hostName: r.host_name,+ status: oneOf<NodeStatus>(STATUSES, r.status, "status"),+ trust: oneOf<Trust>(TRUSTS, r.trust, "trust"),+ failedCheck: r.failed_check,+ log: r.log,+ lastSeen: new Date(r.last_seen_ms),+ kernel: r.kernel_release,+ version: r.version_id,+ // A node the backend has no record for joins as an empty string.+ imageId: r.image_id || null,+ imageVersion: r.image_version || null,+ tree: { generation: r.generation, lastSeq: r.last_seq, headSeq: r.head_seq },+ loaded: r.loaded,+ shields: { applied: r.shields_applied, pending: r.shields_pending, idle: r.shields_idle },+ exposed: r.exposed,+ unknown: r.unknown,+ };+}++export function toFleetReport(rows: readonly NodeRow[]): FleetReport {+ const updated = Math.max(0, ...rows.map((r) => r.updated_ms));+ return { generatedAt: updated ? new Date(updated) : new Date(), nodes: rows.map(toFleetNode) };+}++export class ClickHouseBackend implements Backend {+ constructor(private readonly cfg: ClickHouseConfig) {}++ async getFleet(): Promise<FleetReport> {+ return toFleetReport(await queryRows<NodeRow>(this.cfg, NODES_SQL));+ }+}diff --git a/tools/xtop/src/lib/clickhouse.ts b/tools/xtop/src/lib/clickhouse.tsnew file mode 100644index 00000000..847cabf7--- /dev/null+++ b/tools/xtop/src/lib/clickhouse.ts@@ -0,0 +1,66 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// Queries over the HTTP interface of the backend's ClickHouse.++export type ClickHouseConfig = {+ url: URL;+ user?: string;+ password?: string;+ timeoutMs: number;+};++export const DEFAULT_URL = "http://127.0.0.1:8123/";++/**+ * CLICKHOUSE_URL, CLICKHOUSE_USER and CLICKHOUSE_PASSWORD. Credentials in+ * the URL are refused: they would show in the process list and the error+ * lines this tool prints.+ */+export function configFromEnv(env: Record<string, string | undefined> = process.env): ClickHouseConfig {+ const raw = env.CLICKHOUSE_URL || DEFAULT_URL;+ let url: URL;+ try {+ url = new URL(raw);+ } catch {+ throw new Error(`CLICKHOUSE_URL is not a URL: ${raw}`);+ }+ if (url.protocol !== "http:" && url.protocol !== "https:")+ throw new Error(`CLICKHOUSE_URL must be http or https: ${raw}`);+ if (url.username || url.password)+ throw new Error("CLICKHOUSE_URL must not carry credentials; set CLICKHOUSE_USER and CLICKHOUSE_PASSWORD");+ return {+ url,+ ...(env.CLICKHOUSE_USER ? { user: env.CLICKHOUSE_USER } : {}),+ ...(env.CLICKHOUSE_PASSWORD ? { password: env.CLICKHOUSE_PASSWORD } : {}),+ timeoutMs: 10_000,+ };+}++/** Runs one SELECT and returns its rows as objects keyed by column name. */+export async function queryRows<T>(+ cfg: ClickHouseConfig,+ sql: string,+ fetchImpl: typeof fetch = fetch,+): Promise<T[]> {+ const url = new URL(cfg.url);+ url.searchParams.set("default_format", "JSONEachRow");+ url.searchParams.set("output_format_json_quote_64bit_integers", "0");+ url.searchParams.set("readonly", "1");+ const headers: Record<string, string> = { "Content-Type": "text/plain" };+ if (cfg.user) headers["X-ClickHouse-User"] = cfg.user;+ if (cfg.password) headers["X-ClickHouse-Key"] = cfg.password;++ const res = await fetchImpl(url, {+ method: "POST",+ headers,+ body: sql,+ signal: AbortSignal.timeout(cfg.timeoutMs),+ });+ const text = await res.text();+ if (!res.ok) throw new Error(`${res.status} ${text.trim().split("\n")[0]?.slice(0, 300) ?? ""}`);+ return text+ .split("\n")+ .filter((line) => line.length)+ .map((line) => JSON.parse(line) as T);+}diff --git a/tools/xtop/src/lib/fleet.ts b/tools/xtop/src/lib/fleet.tsnew file mode 100644index 00000000..57fad3eb--- /dev/null+++ b/tools/xtop/src/lib/fleet.ts@@ -0,0 +1,134 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// The nodes as the backend's shirudo.node_status judges them, and their+// roll-up by the image they booted.++/** node_status.status, worst first in STATUS_RANK. */+export type NodeStatus = "unhealthy" | "stale" | "healthy";+export type Trust = "untrusted" | "enrolled";++export const STATUS_RANK: Record<NodeStatus, number> = { unhealthy: 0, stale: 1, healthy: 2 };+export const STATUSES = ["unhealthy", "stale", "healthy"] as const;+export const TRUSTS = ["untrusted", "enrolled"] as const;++export type Shields = {+ /** Upatches loaded that shield a finding of the node. */+ applied: number;+ /** Upatches published for a finding the node has not reached yet. */+ pending: number;+ /** Upatches published for a finding that do nothing on the node. */+ idle: number;+};++export type FleetNode = {+ name: string;+ akName: string;+ hostName: string;+ status: NodeStatus;+ trust: Trust;+ /** 0 when every check passed, 2 for stale, 3 to 7 for unhealthy. */+ failedCheck: number;+ /** One line per check, in order. */+ log: string[];+ lastSeen: Date;+ kernel: string;+ version: string;+ imageId: string | null;+ imageVersion: string | null;+ tree: { generation: number | null; lastSeq: number | null; headSeq: number | null };+ loaded: number;+ shields: Shields;+ /** Findings no loaded upatch shields. */+ exposed: number;+ /** Findings the backend cannot place: no image, no SBOM. */+ unknown: number;+};++export type FleetReport = {+ /** When node_status was last computed. */+ generatedAt: Date;+ nodes: FleetNode[];+};++export type ImageGroup = {+ /** Image id and version, the drill-down query. */+ key: string;+ imageId: string | null;+ imageVersion: string | null;+ nodes: number;+ statuses: Record<NodeStatus, number>;+ /** The worst member's status. */+ status: NodeStatus;+ health: number;+ /** Shared by every member, null when members differ. */+ kernel: string | null;+ tree: { minLastSeq: number | null; headSeq: number | null };+ shields: Shields;+ /** Exposed findings of the worst member. */+ exposed: number;+ unknown: number;+ lastSeen: Date;+};++export const NO_IMAGE = "—";++export const imageLabel = (id: string | null, version: string | null) =>+ id === null ? NO_IMAGE : version ? `${id} ${version}` : id;++/** The check a node failed, as its log line names it: "3 reported". */+export function failedCheckName(n: Pick<FleetNode, "failedCheck" | "log">): string {+ if (!n.failedCheck) return "";+ const m = /^(\d+ [a-z]+):/.exec(n.log[n.failedCheck - 1] ?? "");+ return m ? m[1]! : String(n.failedCheck);+}++/** The fleet's scorecard: percent of nodes healthy, null with no nodes. */+export function healthPercent(nodes: readonly Pick<FleetNode, "status">[]): number | null {+ if (!nodes.length) return null;+ return Math.round((100 * nodes.filter((n) => n.status === "healthy").length) / nodes.length);+}++const minOrNull = (xs: (number | null)[]) => {+ const v = xs.filter((x): x is number => x !== null);+ return v.length ? Math.min(...v) : null;+};+const maxOrNull = (xs: (number | null)[]) => {+ const v = xs.filter((x): x is number => x !== null);+ return v.length ? Math.max(...v) : null;+};++export function groupByImage(nodes: readonly FleetNode[]): ImageGroup[] {+ const byImage = new Map<string, FleetNode[]>();+ for (const n of nodes) {+ const key = imageLabel(n.imageId, n.imageVersion);+ byImage.set(key, [...(byImage.get(key) ?? []), n]);+ }+ return [...byImage].map(([key, members]) => {+ const first = members[0]!;+ const statuses: Record<NodeStatus, number> = { unhealthy: 0, stale: 0, healthy: 0 };+ for (const m of members) statuses[m.status]++;+ const sum = (k: keyof Shields) => members.reduce((t, m) => t + m.shields[k], 0);+ return {+ key,+ imageId: first.imageId,+ imageVersion: first.imageVersion,+ nodes: members.length,+ statuses,+ status: members.reduce<NodeStatus>(+ (w, m) => (STATUS_RANK[m.status] < STATUS_RANK[w] ? m.status : w),+ "healthy",+ ),+ health: healthPercent(members) ?? 0,+ kernel: members.every((m) => m.kernel === first.kernel) ? first.kernel : null,+ tree: {+ minLastSeq: minOrNull(members.map((m) => m.tree.lastSeq)),+ headSeq: maxOrNull(members.map((m) => m.tree.headSeq)),+ },+ shields: { applied: sum("applied"), pending: sum("pending"), idle: sum("idle") },+ exposed: Math.max(...members.map((m) => m.exposed)),+ unknown: members.reduce((t, m) => t + m.unknown, 0),+ lastSeen: new Date(Math.max(...members.map((m) => m.lastSeen.getTime()))),+ };+ });+}diff --git a/tools/xtop/src/lib/mouse.ts b/tools/xtop/src/lib/mouse.tsnew file mode 100644index 00000000..46360056--- /dev/null+++ b/tools/xtop/src/lib/mouse.ts@@ -0,0 +1,85 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo++import { EventEmitter } from "node:events";+import { PassThrough } from "node:stream";+import { StringDecoder } from "node:string_decoder";++/** Coordinates are 0-based terminal cells. */+export type MouseEvent =+ | { kind: "press" | "release"; button: "left" | "middle" | "right"; x: number; y: number }+ | { kind: "wheel"; direction: "up" | "down"; x: number; y: number };++// SGR (1006) encoding: ESC [ < button ; x ; y (M = press, m = release)+const SGR_MOUSE = /\x1b\[<(\d+);(\d+);(\d+)([Mm])/g;+const PARTIAL_SGR = /\x1b\[<[\d;]*$/;+const BUTTONS = ["left", "middle", "right"] as const;++const ENABLE = "\x1b[?1000h\x1b[?1006h";+const DISABLE = "\x1b[?1000l\x1b[?1006l";++/**+ * Ink drops mouse reports, so we sit between the terminal and Ink: mouse+ * sequences are parsed and emitted as "mouse" events, everything else is+ * forwarded to the stream Ink reads. Raw mode and ref/unref are proxied to+ * the real stdin so Ink treats the wrapper as a TTY.+ */+export function createMouseInput(source: NodeJS.ReadStream, stdout: NodeJS.WriteStream) {+ const events = new EventEmitter();+ const decoder = new StringDecoder("utf8");+ const input = Object.assign(new PassThrough(), {+ isTTY: source.isTTY,+ setRawMode(mode: boolean) {+ source.setRawMode(mode);+ return input;+ },+ ref() {+ source.ref();+ return input;+ },+ unref() {+ source.unref();+ return input;+ },+ });++ // Raw mode now, not when Ink first asks for it: the terminal answers+ // startup queries (kitty keyboard `ESC[?u`) right away, and in cooked mode+ // the tty echoes the reply onto the screen as `^[[?0u`.+ if (source.isTTY) source.setRawMode(true);++ let pending = "";+ source.on("data", (chunk: Buffer | string) => {+ let text = pending + (typeof chunk === "string" ? chunk : decoder.write(chunk));+ pending = "";+ const partial = text.match(PARTIAL_SGR);+ if (partial) {+ pending = partial[0];+ text = text.slice(0, partial.index);+ }+ text = text.replace(SGR_MOUSE, (_m, b: string, x: string, y: string, t: string) => {+ const code = Number(b);+ const pos = { x: Number(x) - 1, y: Number(y) - 1 };+ if (code & 64) events.emit("mouse", { kind: "wheel", direction: code & 1 ? "down" : "up", ...pos });+ else if (!(code & 32)) {+ const button = BUTTONS[code & 3];+ if (button) events.emit("mouse", { kind: t === "M" ? "press" : "release", button, ...pos });+ }+ return "";+ });+ if (text) input.write(text);+ });++ let enabled = false;+ const disable = () => {+ if (enabled && stdout.isTTY) stdout.write(DISABLE);+ enabled = false;+ if (source.isTTY) source.setRawMode(false);+ };+ if (stdout.isTTY) {+ stdout.write(ENABLE);+ enabled = true;+ }++ return { input, events, disable };+}diff --git a/tools/xtop/src/lib/terminal.ts b/tools/xtop/src/lib/terminal.tsnew file mode 100644index 00000000..4cb5692b--- /dev/null+++ b/tools/xtop/src/lib/terminal.ts@@ -0,0 +1,26 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo++export const APP_TITLE = "xtop";++const ESC = "\x1b";+const pushTitle = `${ESC}[22;0t`;+const popTitle = `${ESC}[23;0t`;+const setTitleSeq = (title: string) => `${ESC}]0;${title}\x07`;++/**+ * Rename the terminal window/tab. The previous title is saved on the+ * terminal's title stack and restored by the returned function.+ */+export function setTerminalTitle(title: string): () => void {+ process.title = title;+ if (!process.stdout.isTTY) return () => {};++ process.stdout.write(pushTitle + setTitleSeq(title));+ let restored = false;+ return () => {+ if (restored) return;+ restored = true;+ process.stdout.write(popTitle);+ };+}diff --git a/tools/xtop/src/lib/useMouse.ts b/tools/xtop/src/lib/useMouse.tsnew file mode 100644index 00000000..c4250a20--- /dev/null+++ b/tools/xtop/src/lib/useMouse.ts@@ -0,0 +1,23 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo++import { createContext, useContext, useEffect, useRef } from "react";+import type { EventEmitter } from "node:events";+import type { MouseEvent } from "./mouse.ts";++export const MouseContext = createContext<EventEmitter | null>(null);++/** Subscribe to terminal mouse events while `isActive`. */+export function useMouse(handler: (e: MouseEvent) => void, { isActive = true } = {}) {+ const events = useContext(MouseContext);+ const latest = useRef(handler);+ latest.current = handler;+ useEffect(() => {+ if (!events || !isActive) return;+ const listener = (e: MouseEvent) => latest.current(e);+ events.on("mouse", listener);+ return () => {+ events.off("mouse", listener);+ };+ }, [events, isActive]);+}diff --git a/tools/xtop/src/sql.d.ts b/tools/xtop/src/sql.d.tsnew file mode 100644index 00000000..79c1738b--- /dev/null+++ b/tools/xtop/src/sql.d.ts@@ -0,0 +1,8 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo++// sql/*.sql, imported as text and embedded by bun build --compile.+declare module "*.sql" {+ const text: string;+ export default text;+}diff --git a/tools/xtop/test/fleet.test.ts b/tools/xtop/test/fleet.test.tsnew file mode 100644index 00000000..749fdd79--- /dev/null+++ b/tools/xtop/test/fleet.test.ts@@ -0,0 +1,193 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// The rows of sql/nodes.sql as tools/backend/test/xtop-nodes.expected has+// them, turned into nodes and rolled up by image.++import { describe, expect, test } from "bun:test";+import { toFleetNode, toFleetReport, type NodeRow } from "../src/lib/backend.ts";+import { configFromEnv, queryRows } from "../src/lib/clickhouse.ts";+import { failedCheckName, groupByImage, healthPercent, imageLabel } from "../src/lib/fleet.ts";++const BUILD = "d6d918ad22ff597579e6678bef75adca84d30f9661e0b7bbdbf534eebc138c1f";+const LOG = [+ "1 signed: pass, untrusted, 0 rejected in the last hour",+ "2 fresh: pass, last record 12 s ago",+ "3 reported: pass, verdict ok, cond 0x1555, flags 0, tamper +0, build d6d918ad",+ "4 chain: pass, root 15452248",+ "5 head: pass, seq 3 of 3, generation 3",+ "6 set: pass, 1 loaded",+ "7 peers: pass, 2 in group",+];++function row(over: Partial<NodeRow>): NodeRow {+ return {+ node_id: "node-a",+ ak_name: "000b23602ab98bfb",+ host_name: "edge-01",+ status: "healthy",+ trust: "untrusted",+ failed_check: 0,+ log: LOG,+ last_seen_ms: 1_795_000_000_000,+ updated_ms: 1_795_000_030_000,+ generation: 3,+ last_seq: 3,+ head_seq: 3,+ loaded: 1,+ kernel_release: "7.4.2",+ version_id: BUILD,+ image_id: "fleet-os",+ image_version: "2026.11.1",+ shields_applied: 1,+ shields_pending: 0,+ shields_idle: 0,+ exposed: 1,+ unknown: 0,+ ...over,+ };+}++const ROWS: NodeRow[] = [+ row({}),+ row({ node_id: "node-b", ak_name: "000b9d72e08380a1", host_name: "core-01", loaded: 0, shields_applied: 0, shields_idle: 1, exposed: 2 }),+ row({+ node_id: "node-c",+ ak_name: "000b0c",+ host_name: "lab-01",+ generation: null,+ last_seq: null,+ head_seq: null,+ loaded: 0,+ kernel_release: "7.5.1",+ image_id: null,+ image_version: null,+ shields_applied: 0,+ exposed: 0,+ unknown: 1,+ }),+ row({+ node_id: "node-d",+ ak_name: "000b0d",+ host_name: "edge-02",+ status: "unhealthy",+ failed_check: 3,+ log: LOG.map((l, i) => (i === 2 ? "3 reported: FAIL, verdict degraded, cond 0x1555, flags 0, tamper +0, build d6d918ad" : l)),+ }),+ row({ node_id: "node-e", ak_name: "000b0e", host_name: "core-02", status: "stale", failed_check: 2, last_seq: 2, loaded: 0, shields_applied: 0, shields_idle: 1, exposed: 2 }),+];++describe("toFleetNode", () => {+ test("maps every column", () => {+ const n = toFleetNode(ROWS[0]!);+ expect(n.name).toBe("node-a");+ expect(n.hostName).toBe("edge-01");+ expect(n.status).toBe("healthy");+ expect(n.trust).toBe("untrusted");+ expect(n.lastSeen.getTime()).toBe(1_795_000_000_000);+ expect(n.tree).toEqual({ generation: 3, lastSeq: 3, headSeq: 3 });+ expect(n.shields).toEqual({ applied: 1, pending: 0, idle: 0 });+ expect(n.version).toBe(BUILD);+ });++ test("a node with no image or tree keeps its nulls", () => {+ const n = toFleetNode(ROWS[2]!);+ expect(n.imageId).toBeNull();+ expect(n.tree.lastSeq).toBeNull();+ expect(imageLabel(n.imageId, n.imageVersion)).toBe("—");+ });++ test("an empty image from a missing join reads as none", () => {+ expect(toFleetNode(row({ image_id: "", image_version: "" })).imageId).toBeNull();+ });++ test("refuses a status the view does not know", () => {+ expect(() => toFleetNode(row({ status: "degraded" }))).toThrow(/unknown status/);+ expect(() => toFleetNode(row({ trust: "maybe" }))).toThrow(/unknown trust/);+ });++ test("names the failed check from its log line", () => {+ expect(failedCheckName(toFleetNode(ROWS[3]!))).toBe("3 reported");+ expect(failedCheckName(toFleetNode(ROWS[4]!))).toBe("2 fresh");+ expect(failedCheckName(toFleetNode(ROWS[0]!))).toBe("");+ });+});++describe("health", () => {+ test("is the percent of nodes healthy", () => {+ const nodes = ROWS.map(toFleetNode);+ expect(healthPercent(nodes)).toBe(60);+ expect(healthPercent(nodes.filter((n) => n.status === "healthy"))).toBe(100);+ expect(healthPercent(nodes.filter((n) => n.status !== "healthy"))).toBe(0);+ expect(healthPercent([])).toBeNull();+ });+});++describe("groupByImage", () => {+ const groups = groupByImage(ROWS.map(toFleetNode));+ const fleetOs = groups.find((g) => g.key === "fleet-os 2026.11.1")!;+ const none = groups.find((g) => g.key === "—")!;++ test("groups by image id and version", () => {+ expect(groups.map((g) => g.key).sort()).toEqual(["fleet-os 2026.11.1", "—"]);+ expect(fleetOs.nodes).toBe(4);+ expect(none.nodes).toBe(1);+ });++ test("takes the worst status and the share healthy", () => {+ expect(fleetOs.status).toBe("unhealthy");+ expect(fleetOs.statuses).toEqual({ unhealthy: 1, stale: 1, healthy: 2 });+ expect(fleetOs.health).toBe(50);+ expect(none.status).toBe("healthy");+ expect(none.health).toBe(100);+ });++ test("rolls up kernel, tree, shields and exposure", () => {+ expect(fleetOs.kernel).toBe("7.4.2");+ expect(fleetOs.tree).toEqual({ minLastSeq: 2, headSeq: 3 });+ expect(fleetOs.shields).toEqual({ applied: 2, pending: 0, idle: 2 });+ expect(fleetOs.exposed).toBe(2);+ expect(none.tree).toEqual({ minLastSeq: null, headSeq: null });+ expect(none.unknown).toBe(1);+ });++ test("reports a mixed kernel as null", () => {+ const mixed = groupByImage([toFleetNode(ROWS[0]!), toFleetNode(row({ ak_name: "x", kernel_release: "7.5.0" }))]);+ expect(mixed[0]!.kernel).toBeNull();+ });+});++describe("toFleetReport", () => {+ test("dates the report by the newest computation", () => {+ expect(toFleetReport(ROWS).generatedAt.getTime()).toBe(1_795_000_030_000);+ });+});++describe("clickhouse", () => {+ test("defaults to the local HTTP interface", () => {+ expect(configFromEnv({}).url.href).toBe("http://127.0.0.1:8123/");+ });++ test("refuses credentials in the URL and other schemes", () => {+ expect(() => configFromEnv({ CLICKHOUSE_URL: "http://u:p@host:8123/" })).toThrow(/credentials/);+ expect(() => configFromEnv({ CLICKHOUSE_URL: "tcp://host:9000" })).toThrow(/http or https/);+ });++ test("posts the query and parses JSONEachRow", async () => {+ let seen: { url: string; init: RequestInit } | null = null;+ const fake = (async (url: URL, init: RequestInit) => {+ seen = { url: String(url), init };+ return new Response('{"a":1}\n{"a":2}\n');+ }) as unknown as typeof fetch;+ const cfg = configFromEnv({ CLICKHOUSE_URL: "http://ch:8123/", CLICKHOUSE_USER: "ro", CLICKHOUSE_PASSWORD: "pw" });+ expect(await queryRows<{ a: number }>(cfg, "SELECT 1", fake)).toEqual([{ a: 1 }, { a: 2 }]);+ expect(seen!.url).toContain("default_format=JSONEachRow");+ expect(seen!.init.body).toBe("SELECT 1");+ expect((seen!.init.headers as Record<string, string>)["X-ClickHouse-User"]).toBe("ro");+ });++ test("turns a ClickHouse error into its first line", async () => {+ const fake = (async () => new Response("Code: 60. DB::Exception: Unknown table\nstack", { status: 404 })) as unknown as typeof fetch;+ await expect(queryRows(configFromEnv({}), "SELECT 1", fake)).rejects.toThrow("404 Code: 60. DB::Exception: Unknown table");+ });+});diff --git a/tools/xtop/tsconfig.json b/tools/xtop/tsconfig.jsonnew file mode 100644index 00000000..c41dff36--- /dev/null+++ b/tools/xtop/tsconfig.json@@ -0,0 +1,25 @@+{+ "compilerOptions": {+ "target": "ESNext",+ "module": "Preserve",+ "moduleResolution": "bundler",+ "lib": [+ "ESNext"+ ],+ "types": [+ "bun"+ ],+ "jsx": "react-jsx",+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "allowImportingTsExtensions": true,+ "verbatimModuleSyntax": true,+ "skipLibCheck": true,+ "noEmit": true+ },+ "include": [+ "src",+ "test",+ "build.ts"+ ]+}