Files
interzone/internal/ui/layout_test.go
T
vvvomitandClaude Opus 5.5 75a8724be0 Tiny windows: forms no longer crash, and wide falls back to compact
A form given a negative height panicked (Backups, Alerts, Move, Server
in a small window), and a forced wide layout overflowed below 60x17.
TestTinyWindows opens every screen at small sizes in all layouts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:53:22 +03:30

347 lines
14 KiB
Go

package ui
import (
"flag"
"fmt"
"math"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"github.com/muesli/termenv"
"interzone/internal/catalog"
"interzone/internal/config"
"interzone/internal/deploy"
)
// The layout tests draw the main screens at a phone's size and a desktop
// terminal's and compare them with testdata/layout. After a deliberate
// change, look at the diff and accept it with
//
// go test ./internal/ui -run Layout -update
var update = flag.Bool("update", false, "rewrite the layout golden files")
// stamp is vars.yml's generation time, zeroed before comparing.
var stamp = regexp.MustCompile(`Generated by interzone on [0-9: -]*|\b[0-9]{4}-[0-9]{2}-[0-9]{2}( [0-9]{2}:[0-9]{2})?|\b[0-9]{2}:[0-9]{2}:[0-9]{2}\b`)
var sizes = []struct{ w, h int }{{46, 40}, {120, 36}}
// demoApp is a fresh app on a fixed demo config, with the config and data
// directories somewhere harmless.
func demoApp(t *testing.T, w, h int) *App {
t.Helper()
t.Setenv("HOME", "/home/demo")
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_DATA_HOME", "/home/demo/.local/share")
t.Setenv("INTERZONE_SERVER", "")
lipgloss.SetColorProfile(termenv.Ascii)
cfg := config.Default()
cfg.Domain = "example.org"
cfg.PlaybookDir = "/home/demo/.local/share/interzone/matrix-docker-ansible-deploy"
for _, id := range []string{"element", "cinny", "coturn", "double-puppet"} {
cfg.Components[id] = true
}
a := New(cfg, true)
a.step = 0
a.Update(tea.WindowSizeMsg{Width: w, Height: h})
return a
}
func TestLayout(t *testing.T) {
shots := []struct {
name string
open func(a *App)
}{
{"welcome", func(a *App) {}},
{"welcome-installed", func(a *App) {
ws := a.screens[0].(*welcomeScreen)
ws.installed, ws.domain = true, "example.org"
}},
{"server", func(a *App) { a.jump(a.index("Server")) }},
{"homeserver", func(a *App) { a.jump(a.index("Homeserver")) }},
{"presets", func(a *App) {
a.cfg.ApplyPreset(catalog.Presets[1])
a.jump(a.index("Homeserver"))
}},
{"components", func(a *App) { a.jump(a.index("Components")) }},
{"settings", func(a *App) { a.jump(a.index("Settings")) }},
{"review", func(a *App) { a.jump(a.index("Review")) }},
{"manage", func(a *App) {
a.jump(a.index("Manage"))
a.health = &deploy.Health{Up: true, Trusted: true, CertLeft: 63*24*time.Hour + time.Hour}
}},
{"manage-armed", func(a *App) {
a.jump(a.index("Manage"))
a.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("r")})
}},
{"menu", func(a *App) {
a.jump(a.index("Manage"))
if a.compact() {
a.menuOpen = true
}
}},
{"sheet", func(a *App) {
a.jump(a.index("Manage"))
a.sheetOpen = true
}},
{"dashboard", openDashboard},
{"mirrors", openMirrors},
{"users", openUsers},
{"tokens", openTokens},
{"rooms", openRooms},
{"test", openTest},
{"maintenance", func(a *App) { deliver(a, maintainMsg("vacuum")) }},
{"users-bridge", func(a *App) {
openUsers(a)
us := a.cur().(*usersScreen)
us.open["telegram"] = true
us.cursor = 5 // the Telegram heading
}},
}
shootAll(t, sizes, shots)
// A phone with its keyboard up.
shootAll(t, []struct{ w, h int }{{48, 20}}, shots)
}
// The dashboard and the mirror checks also have a layout for big terminals.
func TestLayoutWide(t *testing.T) {
shootAll(t, []struct{ w, h int }{{180, 50}}, []struct {
name string
open func(a *App)
}{{"dashboard", openDashboard}, {"mirrors", openMirrors}, {"users", openUsers}})
}
func openDashboard(a *App) {
a.jump(a.index("Dashboard"))
ds := a.cur().(*dashboardScreen)
st := &deploy.ServerStatus{Load: [3]float64{1.2, 0.9, 0.7}, CPUs: 4, Uptime: 80 * time.Hour,
MemTotal: 8 << 30, MemAvail: 3 << 30, SwapTotal: 2 << 30, SwapFree: 1 << 30,
OS: "Debian GNU/Linux 12 (bookworm)", Kernel: "6.1.0-26-amd64", Docker: "27.3.1", Hostname: "vps1",
Disks: []deploy.Disk{{Mount: "/", Total: 80 << 30, Used: 62 << 30, Avail: 18 << 30}},
Timer: "Tue 2026-10-27 03:00:00 UTC", Taken: time.Now(),
Certs: []deploy.Cert{
{Host: "matrix.example.org", Services: "Synapse", NotAfter: time.Now().Add(60*24*time.Hour + time.Hour), Issuer: "R11"},
{Host: "element.example.org", Services: "Element Web", NotAfter: time.Now().Add(12*24*time.Hour + time.Hour), Issuer: "R11"},
{Host: "chat.other.net", Services: "Cinny", Err: "connection refused"},
},
Containers: []deploy.Container{
{Name: "matrix-mautrix-telegram", State: "exited", Status: "Exited (1) 2 hours ago", Image: "dock.mau.dev/mautrix/telegram:v0.15.2"},
{Name: "matrix-synapse", State: "running", Status: "Up 3 days", Image: "ghcr.io/element-hq/synapse:v1.120.0",
CPU: "4.10%", Mem: "610MiB / 7.8GiB", MemPerc: 7.6, Net: "1.2GB / 900MB", Restarts: 2, Health: "unhealthy"},
{Name: "matrix-postgres", State: "running", Status: "Up 3 days", Image: "postgres:17.2-alpine",
CPU: "0.80%", Mem: "220MiB / 7.8GiB", MemPerc: 2.7, Net: "40MB / 60MB", Health: "healthy"},
{Name: "matrix-traefik", State: "running", Status: "Up 3 days", Image: "traefik:v3.2.1",
CPU: "0.20%", Mem: "60MiB / 7.8GiB", MemPerc: 0.7, Net: "2.1GB / 2.0GB"},
}}
// Two weeks every 30 minutes: a daily rhythm, the disk growing 2.4 GB a week.
for i := range 14 * 48 {
day := math.Sin(float64(i) / 48 * 2 * math.Pi)
st.History = append(st.History, deploy.Sample{At: time.Now().Add(-time.Duration(14*48-1-i) * 30 * time.Minute),
Load: 0.3 + 0.2*day, MemUsed: int64((0.55 + 0.1*day) * (8 << 30)), MemTotal: 8 << 30,
DiskUsed: (62 << 30) - int64(float64(14*48-1-i)/(7*48)*2.4*(1<<30)), DiskTotal: 80 << 30})
}
ds.st, ds.loading = st, false
}
func openTokens(a *App) {
a.cfg.Components["mas"], a.cfg.Signup, a.cfg.SignupToken = true, true, "q7KzR2mWx9PtL4vNb8Hc"
a.jump(a.index("Tokens"))
ts := a.cur().(*tokensScreen)
at := func(d time.Duration) *time.Time { t := time.Now().Add(d); return &t }
five, ten := 5, 10
ts.busy, ts.loaded = false, true
ts.list = []deploy.RegToken{
{Token: "q7KzR2mWx9PtL4vNb8Hc", TimesUsed: 14, CreatedAt: *at(-40 * 24 * time.Hour), LastUsedAt: at(-3 * time.Hour)},
{Token: "book-club", UsageLimit: &ten, TimesUsed: 4, CreatedAt: *at(-9 * 24 * time.Hour), ExpiresAt: at(21 * 24 * time.Hour)},
{Token: "family2025", UsageLimit: &five, TimesUsed: 5, CreatedAt: *at(-200 * 24 * time.Hour)},
{Token: "old-link", TimesUsed: 2, CreatedAt: *at(-300 * 24 * time.Hour), RevokedAt: at(-100 * 24 * time.Hour)},
}
}
func openRooms(a *App) {
a.jump(a.index("Rooms"))
rs := a.cur().(*roomsScreen)
rs.busy, rs.loaded = false, true
rs.list = []deploy.Room{
{ID: "!kQx:example.org", Name: "Lounge", Alias: "#lounge:example.org", Creator: "@alice:example.org", Members: 214, Local: 31, Events: 1840, Public: true, Federated: true},
{ID: "!Hw2:matrix.org", Name: "Matrix HQ", Alias: "#matrix:matrix.org", Members: 9120, Local: 2, Events: 960, Public: true, Federated: true},
{ID: "!p0d:example.org", Name: "Book club", Members: 7, Local: 7, Events: 42, Encrypted: true},
{ID: "!sp4m:spam.example", Name: "free crypto", Members: 3, Local: 1, Events: 12, Federated: true, Blocked: true},
}
}
func openTest(a *App) {
a.jump(a.index("Test"))
ps := a.cur().(*probeScreen)
ps.form.get("servers").input.SetValue("example.org, matrix.org")
ps.results = []probeResult{{name: "example.org", done: true, findings: []deploy.Finding{
{Group: "Federation", Name: "Delegation", Detail: "/.well-known/matrix/server sends servers to matrix.example.org:443"},
{Group: "Federation", Name: "Federation API", Detail: "matrix.example.org:443 answers as example.org, with a trusted certificate"},
{Group: "Federation", Name: "Software", Detail: "Synapse 1.140.0"},
{Group: "Clients", Name: "Well-known", Level: deploy.Warn, Detail: "https://example.org/.well-known/matrix/client sends apps to https://matrix.example.org, but without the CORS header web apps need"},
{Group: "Clients", Name: "Client API", Detail: "https://matrix.example.org answers, spec up to v1.12"},
{Group: "Clients", Name: "Element X sync", Level: deploy.Fail, Detail: "the homeserver doesn't offer sliding sync, which Element X needs"},
}}, {name: "matrix.org"}}
}
func openUsers(a *App) {
a.jump(a.index("Users"))
us := a.cur().(*usersScreen)
day := 24 * time.Hour
at := func(d time.Duration) time.Time { return time.Now().Add(-d - time.Minute) }
person := func(id, name string, seen, made time.Duration, rooms, devices, files int, mb int64) deploy.MatrixUser {
u := deploy.MatrixUser{ID: id, DisplayName: name, Created: at(made), Rooms: rooms, Devices: devices, MediaCount: files, MediaBytes: mb << 20}
if seen > 0 {
u.LastSeen = at(seen)
}
return u
}
alice := person("@alice:example.org", "Alice Liddell", 2*time.Hour, 400*day, 27, 3, 142, 380)
alice.Admin, alice.Avatar, alice.Emails = true, true, []string{"alice@example.org"}
dave := person("@dave:example.org", "", 90*day, 300*day, 0, 0, 0, 0)
dave.Deactivated = true
bot := deploy.MatrixUser{ID: "@telegrambot:example.org", DisplayName: "Telegram bridge bot", Bridge: "telegram", Bot: true, Rooms: -1, Devices: -1, LastSeen: at(time.Hour)}
puppet := func(id, name string) deploy.MatrixUser {
return deploy.MatrixUser{ID: id, DisplayName: name, Bridge: "telegram", Rooms: -1, Devices: -1, MediaCount: 4, MediaBytes: 2 << 20}
}
us.list = &deploy.UserList{Rooms: 31, Users: []deploy.MatrixUser{
alice,
person("@bob:example.org", "Bob", 3*day, 200*day, 11, 1, 6, 12),
person("@carol:example.org", "Carol", 45*day, 120*day, 4, 1, 0, 0),
person("@eve:example.org", "", 0, 5*day, 0, 0, 0, 0),
dave,
bot, puppet("@telegram_1001:example.org", "Nikolai (Telegram)"), puppet("@telegram_1002:example.org", "Pavel (Telegram)"),
{ID: "@whatsappbot:example.org", Bridge: "whatsapp", Bot: true, Rooms: -1, Devices: -1},
}}
us.busy = false
}
func openMirrors(a *App) {
a.jump(a.index("Mirrors"))
ms := a.cur().(*mirrorsScreen)
ms.loading = [3]bool{}
ms.taken = time.Now()
ms.res = mirrorsResult{
Repos: []deploy.Check{
{Name: "playbook", Target: a.cfg.Sources.PlaybookGit, OK: true, Detail: "HEAD 1a2b3c4d5e"},
{Name: "auxiliary", Target: "https://itsjustadream.g0th.ir/mother-of-all-self-hosting/ansible-role-aux.git", OK: true, Detail: "v2.0.0-0"},
{Name: "cinny", Target: "https://itsjustadream.g0th.ir/mother-of-all-self-hosting/ansible-role-cinny.git", OK: false, Detail: "has no v4.12.8-0 yet; the mirror may be behind"},
},
Sources: []deploy.Check{{Name: "Container registry", Target: a.cfg.Sources.RegistryPrefix, OK: true, Detail: "HTTP 200"}},
Known: []deploy.MirrorResult{{Mirror: config.KnownMirrors[0], OK: true, Detail: "fresh", Took: 120 * time.Millisecond}},
ImgErr: "the images are worked out from the playbook on the server; set it up first",
}
}
func shootAll(t *testing.T, sizes []struct{ w, h int }, shots []struct {
name string
open func(a *App)
}) {
for _, sz := range sizes {
for _, sh := range shots {
name := fmt.Sprintf("%s-%dx%d", sh.name, sz.w, sz.h)
t.Run(name, func(t *testing.T) {
a := demoApp(t, sz.w, sz.h)
sh.open(a)
got := stamp.ReplaceAllStringFunc(ansi.Strip(a.View()), func(m string) string {
return strings.Map(func(r rune) rune {
if r >= '0' && r <= '9' {
return '0'
}
return r
}, m)
})
lines := strings.Split(got, "\n")
if len(lines) > sz.h {
t.Errorf("%d lines, taller than the %d-line terminal", len(lines), sz.h)
}
for i, l := range lines {
if lw := ansi.StringWidth(l); lw > sz.w {
t.Errorf("line %d is %d wide, more than %d: %q", i+1, lw, sz.w, l)
}
}
golden(t, name, got)
})
}
}
}
func golden(t *testing.T, name, got string) {
t.Helper()
path := filepath.Join("testdata", "layout", name+".txt")
if *update {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(got), 0o644); err != nil {
t.Fatal(err)
}
return
}
want, err := os.ReadFile(path)
if err != nil {
t.Fatalf("%v (run with -update to create it)", err)
}
if string(want) != got {
t.Errorf("%s changed; if that's intended, rerun with -update.\n--- want\n%s\n--- got\n%s", path, want, got)
}
}
// With every menu section open in a short window, the sidebar scrolls to
// where you are instead of pushing the header off the screen.
func TestSidebarFits(t *testing.T) {
a := demoApp(t, 120, 24)
a.jump(a.index("Manage"))
for sec := range sectionNames {
a.sideOpen[sec] = true
}
lines := strings.Split(ansi.Strip(a.View()), "\n")
if len(lines) != 24 || !strings.Contains(lines[0], "interzone") || !strings.Contains(a.View(), "Overview") {
t.Errorf("%d lines, the first %q:\n%s", len(lines), lines[0], strings.Join(lines, "\n"))
}
}
// Every screen draws in tiny windows without crashing or growing taller
// than the window.
func TestTinyWindows(t *testing.T) {
for _, sz := range [][2]int{{20, 6}, {30, 10}, {40, 15}, {60, 12}, {80, 24}, {120, 36}, {70, 50}} {
for _, layout := range []string{"auto", "compact", "wide"} {
a := demoApp(t, sz[0], sz[1])
a.layout = layout
for i := range a.screens {
if a.screens[i].name() == "Deploy" {
continue
}
a.step = i
a.cur().enter(a.cfg)
func() {
defer func() {
if r := recover(); r != nil {
t.Errorf("%s at %dx%d (%s): %v", a.screens[i].name(), sz[0], sz[1], layout, r)
}
}()
lines := strings.Split(a.View(), "\n")
if len(lines) > sz[1] {
t.Errorf("%s at %dx%d (%s) is %d lines tall", a.screens[i].name(), sz[0], sz[1], layout, len(lines))
}
for _, l := range lines {
if w := ansi.StringWidth(l); w > sz[0] {
t.Errorf("%s at %dx%d (%s) has a line %d wide: %q", a.screens[i].name(), sz[0], sz[1], layout, w, ansi.Strip(l))
break
}
}
}()
}
}
}
}