feat(master): Ledger UI for Services and Agents (#18) (#29)
Docker Build / docker (push) Successful in 41s

## Summary

- Rebuilds the master's **Services** and **Agents** pages per the "Ledger" design: sidebar shell with live nav counts, machine filter and Live indicator; dark/light theme (follows the OS, toggle overrides); embedded Schibsted Grotesk and JetBrains Mono (fontsource 5.3.0, OFL).
- Services: Swarm grouped per cluster with its machines under it, offline banner ("Agent offline since HH:MM", browser-local), Simple Icons derived from the image ref (letter circle fallback), existing badges and mode switch restyled, client-side search, machine filter and Icon / Icon + text / Text toggle.
- Agents: Online / Offline / Never connected / Revoked, master version in the header with outdated agent versions marked, revoke via popover instead of `confirm()`, "Add agent" as a three-step panel that completes when the agent says hello (SSE `agents`).
- Store: migration `0005_agent_cluster.sql` persists each agent's `swarm_cluster_id` (needed to list a cluster's managers and its offline state after a master restart).
- SSE keepalive is now a named `ping` event so the Live indicator also shows the connection is alive. `revokeAgent` now publishes `agents`.

Closes #18

## Notes

- Workers never report a cluster id (Docker only sets `Swarm.Cluster` on managers), so their Swarm role shows "—". Fixing that needs a new hello field.
- Master binary grows by about 2.16 MB, almost all Simple Icons 16.35.0 path data (gzipped JSON, regenerated with `go generate ./internal/master/web/icons`). The agent binary does not import it.
- Jobs, Job and Service detail pages only get the new shell; their own artboards are out of scope, as are Update buttons, Update all, header stats and the drift badge.
- Unchanged: CSRF on every POST, `Cache-Control: no-store` on the token response, 401 + `HX-Redirect` without a session, no `template.HTML` on agent- or user-controlled values, no Node build step.

## Test plan

- [x] `go test ./...`, `go test -race ./internal/master/...`
- [x] `go test -tags integration ./internal/master/store/` against Postgres 17
- [x] `docker build`
- [x] Browser check on fake data: both themes, 1440 px and 390 px, add-agent flow through connect
- [ ] Services grouping and icons against real stacks and a real Swarm cluster
- [ ] "Agent offline since" after stopping an agent
- [ ] Theme toggle, search and machine filter across reloads and mode changes
- [ ] Add agent end to end with a real agent, Copy buttons
- [ ] Phone at 390 px

https://claude.ai/code/session_01GAZsp3P7Qto6JnhipxWUJQ
Reviewed-on: #29
This commit was merged in pull request #29.
This commit is contained in:
2026-10-13 09:20:18 +00:00
parent 919ad91710
commit ec28d1e027
29 changed files with 2140 additions and 199 deletions
@@ -0,0 +1,30 @@
# CC0 1.0 Universal
## Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an “owner”) of an original work of authorship and/or a database (each, a “Work”).
Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works (“Commons”) that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the “Affirmer”), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights (“Copyright and Related Rights”). Copyright and Related Rights include, but are not limited to, the following:
1. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
2. moral rights retained by the original author(s) and/or performer(s);
3. publicity and privacy rights pertaining to a person’s image or likeness depicted in a Work;
4. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(i), below;
5. rights protecting the extraction, dissemination, use and reuse of data in a Work;
6. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
7. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer’s Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the “Waiver”). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer’s heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer’s express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer’s express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer’s Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the “License”). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer’s express Statement of Purpose.
4. Limitations and Disclaimers.
1. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
2. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
3. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person’s Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
4. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work.
For more information, please see <https://creativecommons.org/publicdomain/zero/1.0>.
+128
View File
@@ -0,0 +1,128 @@
// Command gen builds simple-icons.json.gz, the icon data the icons package
// embeds. It downloads the pinned simple-icons npm tarball, checks its
// sha256 and writes a gzipped JSON object {slug: svg path data}. The output
// is deterministic. It writes into the current directory; run it with
//
// go generate ./internal/master/web/icons
package main
import (
"archive/tar"
"bytes"
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path"
"regexp"
"strings"
)
const (
tarballURL = "https://registry.npmjs.org/simple-icons/-/simple-icons-16.35.0.tgz"
tarballSHA256 = "20ebead4f6bc93464812a5e260d19fc4d84772e5eeff69a6fbea263ca2441c5f"
)
var pathData = regexp.MustCompile(`<path d="([^"]+)"`)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, "gen:", err)
os.Exit(1)
}
}
func run() error {
tgz, err := download(tarballURL)
if err != nil {
return err
}
if sum := sha256.Sum256(tgz); hex.EncodeToString(sum[:]) != tarballSHA256 {
return fmt.Errorf("sha256 mismatch for %s: got %x, want %s", tarballURL, sum, tarballSHA256)
}
icons, license, err := extract(tgz)
if err != nil {
return err
}
var js bytes.Buffer
enc := json.NewEncoder(&js)
enc.SetEscapeHTML(false)
if err := enc.Encode(icons); err != nil { // map keys are written sorted
return err
}
var gz bytes.Buffer
zw, err := gzip.NewWriterLevel(&gz, gzip.BestCompression)
if err != nil {
return err
}
if _, err := zw.Write(js.Bytes()); err != nil { // the header has no name and a zero mtime
return err
}
if err := zw.Close(); err != nil {
return err
}
if err := os.WriteFile("simple-icons.json.gz", gz.Bytes(), 0o644); err != nil {
return err
}
if err := os.WriteFile("LICENSE-simple-icons.md", license, 0o644); err != nil {
return err
}
fmt.Printf("wrote %d icons\n", len(icons))
return nil
}
func download(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("GET %s: %s", url, resp.Status)
}
return io.ReadAll(resp.Body)
}
// extract returns the path data of every package/icons/*.svg by slug, and
// package/LICENSE.md.
func extract(tgz []byte) (icons map[string]string, license []byte, err error) {
zr, err := gzip.NewReader(bytes.NewReader(tgz))
if err != nil {
return nil, nil, err
}
tr := tar.NewReader(zr)
icons = map[string]string{}
for {
h, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return nil, nil, err
}
switch {
case h.Name == "package/LICENSE.md":
if license, err = io.ReadAll(tr); err != nil {
return nil, nil, err
}
case path.Dir(h.Name) == "package/icons" && strings.HasSuffix(h.Name, ".svg"):
svg, err := io.ReadAll(tr)
if err != nil {
return nil, nil, err
}
m := pathData.FindAllSubmatch(svg, -1)
if len(m) != 1 {
return nil, nil, fmt.Errorf("%s: want exactly one <path>, found %d", h.Name, len(m))
}
icons[strings.TrimSuffix(path.Base(h.Name), ".svg")] = string(m[0][1])
}
}
if license == nil || len(icons) == 0 {
return nil, nil, fmt.Errorf("tarball has no LICENSE.md or no icons")
}
return icons, license, nil
}
+109
View File
@@ -0,0 +1,109 @@
// Package icons maps container image references to brand icons from the
// Simple Icons set (CC0, see LICENSE-simple-icons.md). Only the master's UI
// imports it, so the agent binary does not carry the data.
package icons
import (
"bytes"
"compress/gzip"
_ "embed"
"encoding/json"
"strings"
"sync"
"github.com/shcizo/package-updater/internal/imageref"
)
//go:generate go run ./gen
//go:embed simple-icons.json.gz
var data []byte
var (
once sync.Once
paths map[string]string
)
// aliases maps a normalised image name to the Simple Icons slug that differs
// from it.
var aliases = map[string]string{
"postgres": "postgresql",
"goauthentik": "authentik",
"traefik": "traefikproxy",
"node": "nodedotjs",
"mongo": "mongodb",
}
// skipNamespaces are registry namespaces that name a publisher, not a product.
var skipNamespaces = map[string]bool{"library": true, "linuxserver": true, "bitnami": true, "hotio": true}
// suffixes are stripped from the last path segment to find the product name
// ("authentik-server" is authentik).
var suffixes = []string{"-server", "-web", "-api", "-worker", "-agent"}
func load() {
once.Do(func() {
paths = map[string]string{}
zr, err := gzip.NewReader(bytes.NewReader(data))
if err != nil {
return
}
_ = json.NewDecoder(zr).Decode(&paths)
})
}
// Path returns the SVG path data (24x24 viewBox) of the icon with this Simple
// Icons slug.
func Path(slug string) (string, bool) {
load()
p, ok := paths[slug]
return p, ok
}
// Count returns how many icons are embedded.
func Count() int {
load()
return len(paths)
}
// ForImage returns the slug of the icon that best matches the image
// reference, or "" when there is none. It tries the last path segment, that
// segment without a role suffix, and the namespace, in that order.
func ForImage(ref string) string {
segs := strings.Split(imageref.Parse(ref).Repo, "/")
if len(segs) > 1 && imageref.IsRegistryHost(segs[0]) {
segs = segs[1:]
}
last := segs[len(segs)-1]
candidates := []string{last}
for _, s := range suffixes {
if base, ok := strings.CutSuffix(last, s); ok && base != "" {
candidates = append(candidates, base)
break
}
}
if len(segs) > 1 && !skipNamespaces[segs[len(segs)-2]] {
candidates = append(candidates, segs[len(segs)-2])
}
for _, c := range candidates {
slug := normalise(c)
if a, ok := aliases[slug]; ok {
slug = a
}
if _, ok := Path(slug); ok {
return slug
}
}
return ""
}
// normalise lowercases s and keeps only a-z and 0-9, the form of Simple Icons slugs.
func normalise(s string) string {
var b strings.Builder
for _, r := range strings.ToLower(s) {
if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' {
b.WriteRune(r)
}
}
return b.String()
}
+46
View File
@@ -0,0 +1,46 @@
package icons
import (
"regexp"
"testing"
"github.com/stretchr/testify/assert"
)
func TestForImage(t *testing.T) {
cases := []struct {
ref, want string
}{
{"gitea/gitea:1.27.3", "gitea"},
{"ghcr.io/goauthentik/server:2026.8.2", "authentik"},
{"postgres:17.10", "postgresql"},
{"grafana/loki:3.4.2", "grafana"},
{"docker.n8n.io/n8nio/n8n:1.112.4", "n8n"},
{"lscr.io/linuxserver/prowlarr:latest", ""},
{"localhost:5000/foo:v1", ""},
{"gitea.shcizo.se/shcizo/slusk:v0.8.1", ""},
}
for _, c := range cases {
t.Run(c.ref, func(t *testing.T) {
assert.Equal(t, c.want, ForImage(c.ref))
})
}
}
// safePath is a strict allowlist for what an embedded path may contain, since
// the paths are written into the page's HTML.
var safePath = regexp.MustCompile(`^[MmLlHhVvCcSsQqTtAaZz0-9.,\- e]+$`)
func TestEmbeddedSet(t *testing.T) {
assert.Greater(t, Count(), 3000)
for slug, p := range paths {
if !safePath.MatchString(p) {
t.Errorf("icon %q has unexpected characters in its path", slug)
}
}
p, ok := Path("gitea")
assert.True(t, ok)
assert.NotEmpty(t, p)
_, ok = Path("no-such-icon")
assert.False(t, ok)
}
Binary file not shown.