Files
vvvomitandClaude Opus 5.5 bd4dcb7be6 Rooms counts all a room takes on disk, its history too
Media alone missed most of it: on a 12 GB database the biggest room's
history was 2.3 GB beside 20 MB of files. Each table with rooms in it is
now split among them by their rows there, which adds up to the tables'
size on disk with their indexes and takes seconds, where measuring every
row took minutes. Size, on the card and as the default sort, is history
plus media; without the database it falls back to state events.

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

436 lines
19 KiB
Go

package ui
import (
"flag"
"fmt"
"math"
"net/netip"
"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},
{"host", func(a *App) {
a.jump(a.index("Host"))
hs := a.cur().(*hostScreen)
hs.done, hs.log = true, []string{"installing IPFS v0.43.1 (from https://infamous.g0th.ir/.ipfs)",
"the server is downloading about 15.7 GB in the background and shares it as it arrives"}
hs.statsFor = targetKey(hs.target())
hs.in, hs.out = []float64{0, 4e6, 9e6, 7e6, 10e6}, []float64{0, 0, 1e5, 3e5, 2e5}
hs.stats = &deploy.HostStats{Installed: true, Active: true, Following: true, Parts: []string{"oci", "packages", "git", "bin"}, Peers: 3,
RepoSize: 6 << 30, DiskFree: 80 << 30, RateIn: 10e6, RateOut: 2e5, TotalIn: 6 << 30, TotalOut: 300 << 20,
BlocksSent: 1200, DataSent: 290 << 20, BlocksReceived: 25000, DataReceived: 6 << 30,
Published: "2026-10-29T03:00:00Z", Wanted: 19 << 30, Received: 6 << 30,
PublishedParts: []deploy.HostPart{{Name: "packages", Size: 3 << 30, Pinned: false}, {Name: "oci", Size: 15 << 30, Pinned: false}, {Name: "git", Size: 200 << 20, Pinned: true}, {Name: "bin", Size: 300 << 20, Pinned: true}},
Last: "fetching bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi"}
}},
{"host-map", openHostMap},
{"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 openHostMap(a *App) {
localMirror.Store(true) // shootAll clears it
a.jump(a.index("Host"))
hs := a.cur().(*hostScreen)
hs.statsFor, hs.phase = targetKey(hs.target()), 1.3
ip := netip.MustParseAddr
hs.stats = &deploy.HostStats{Installed: true, Active: true, Mirror: "ipfs", Parts: []string{"oci", "packages", "git", "bin"}, Peers: 4,
RepoSize: 19 << 30, DiskFree: 80 << 30, RateIn: 2e5, RateOut: 3e6, TotalIn: 6 << 30, TotalOut: 40 << 30,
DataSent: 38 << 30, DataReceived: 1 << 30, Published: "2026-10-29T03:00:00Z",
PublishedParts: []deploy.HostPart{{Name: "oci", Pinned: true}, {Name: "packages", Pinned: true}, {Name: "git", Pinned: true}, {Name: "bin", Pinned: true}},
Self: []netip.Addr{ip("2.176.0.1")}, PeerList: []deploy.Peer{
{ID: "a", Addr: ip("5.160.0.1"), Sent: 9 << 30, Latency: 41 * time.Millisecond, Inbound: true},
{ID: "b", Addr: ip("81.169.145.1"), Sent: 2 << 30, Latency: 120 * time.Millisecond},
{ID: "c", Addr: ip("10.0.0.1"), Recv: 1 << 20},
{ID: "d", Addr: ip("2.176.200.1"), Latency: 18 * time.Millisecond}}}
hs.in, hs.out = []float64{0, 1e5, 2e5}, []float64{1e6, 4e6, 3e6}
hs.rates = map[string]peerRate{"a": {out: 2e6}, "b": {out: 1e6}}
hs.peerHist = map[string][]float64{"a": {1e6, 3e6, 2e6}, "b": {0, 1e6, 1e6}}
at := time.Date(2026, 10, 29, 14, 5, 0, 0, time.UTC)
hs.comings = []hostComing{{at, hs.stats.PeerList[3], true}, {at.Add(time.Minute), deploy.Peer{Addr: ip("8.8.8.8")}, false}}
hs.ripples = []ripple{{addr: ip("2.176.200.1"), start: 0.5, join: true}}
}
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
day := func(y, m, d int) time.Time { return time.Date(y, time.Month(m), d, 12, 0, 0, 0, time.UTC) }
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,
Created: day(2024, 3, 9), MediaCount: 172, MediaBytes: 24 << 20, DataBytes: 310 << 20},
{ID: "!Hw2:matrix.org", Name: "Matrix HQ", Alias: "#matrix:matrix.org", Members: 9120, Local: 2, Events: 960, Public: true, Federated: true,
Created: day(2019, 6, 1), MediaCount: 31, MediaBytes: 6 << 20, DataBytes: 2300 << 20},
{ID: "!p0d:example.org", Name: "Book club", Members: 7, Local: 7, Events: 42, Encrypted: true, Created: day(2025, 11, 2), DataBytes: 4 << 20},
{ID: "!sp4m:spam.example", Name: "free crypto", Members: 3, Local: 1, Events: 12, Federated: true, Blocked: true, MediaCount: -1, DataBytes: -1},
}
rs.sortRooms("") // as loading does
}
// o sorts the rooms, keeping the cursor on the same room.
func TestRoomSort(t *testing.T) {
a := demoApp(t, 120, 36)
openRooms(a)
rs := a.cur().(*roomsScreen)
rs.cursor = 0 // Matrix HQ, the biggest
order := func() (out []string) {
for _, r := range rs.list {
out = append(out, r.Name)
}
return out
}
for _, want := range []string{"Matrix HQ,Lounge,Book club,free crypto", "Book club,Lounge,Matrix HQ,free crypto", "Lounge,Matrix HQ,Book club,free crypto", "Matrix HQ,Lounge,Book club,free crypto"} {
rs.update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("o")})
if got := strings.Join(order(), ","); got != want || rs.list[rs.cursor].Name != "Matrix HQ" {
t.Errorf("by %s: %s, cursor on %s", roomSorts[rs.sortBy], got, rs.list[rs.cursor].Name)
}
}
}
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: "Network", Name: "DNS", Detail: "matrix.example.org → 192.0.2.1 (Tehran, Asiatech)"},
{Group: "Network", Name: "IPv4 and IPv6", Level: deploy.Warn, Detail: "matrix.example.org:443: IPv4 connects, IPv6 timed out"},
{Group: "TLS", Name: "Certificate", Detail: "matrix.example.org:443: TLS 1.3, Let's Encrypt R11, 62 days left"},
{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"},
{Group: "Server", Name: "Sign-ups", Detail: "with a sign-up token only"},
}}, {name: "matrix.org"}}
}
// ctrl+o copies the finished servers' results as text.
func TestProbeCopy(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
var copied string
toClipboard = func(s string) { copied = s }
defer func() { toClipboard = termenv.Copy }()
a := demoApp(t, 120, 36)
openTest(a)
ps := a.cur().(*probeScreen)
ps.update(tea.KeyMsg{Type: tea.KeyCtrlO})
b, err := os.ReadFile(filepath.Join(config.Dir(), "test-results.txt"))
if got := string(b); err != nil || !strings.Contains(got, " TLS\n ✓ Certificate: matrix.example.org:443") ||
!strings.Contains(got, "✗ Element X sync") || strings.Contains(got, "matrix.org,") {
t.Errorf("%v:\n%s", err, got)
}
if !strings.HasPrefix(ps.note, "copied") || copied != string(b) {
t.Error(ps.note)
}
}
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}},
IPFS: []deploy.Check{{Name: "IPFS publish", Target: "https://infamous.g0th.ir/.ipfs/", OK: true, Detail: "signed, from 2026-10-29T21:57:16Z"}},
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)
defer localMirror.Store(false)
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
}
}
}()
}
}
}
}