feat(cli): rework developer CLI with non-blocking tasks and GitHub CI checks (#6651)

This commit is contained in:
Thomas authored and GitHub committed 2026-08-21 18:59:11 +02:00
1 parent f0f9539466
commit 81aa704537
56 files changed
+7950 -2548

No files matched your search

+410
View File
@@ -0,0 +1,410 @@
package tui
import (
"context"
"fmt"
"strconv"
"strings"
tea "charm.land/bubbletea/v2"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/docker"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/platform"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/registry"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/run"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/task"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/ui"
)
// target is everything the actions need to know about the selected row,
// resolved once so the same code can act on a pull request, a local image, or a
// bare container without caring which screen the user is on.
type target struct {
label string
container string
localImage string
volume string
pr int
running bool
port string
provenance docker.Image
buildable bool
}
func (m Model) currentTarget() (target, bool) {
if m.screen == screenInstances {
row, found := m.selectedInstance()
if !found {
return target{}, false
}
return m.instanceTarget(row), true
}
row, found := m.selectedDev()
if !found {
return target{}, false
}
return m.devTarget(row), true
}
func (m Model) devTarget(row devRow) target {
result := target{
label: row.label(),
container: row.containerName(),
volume: row.volumeName(),
running: row.running,
port: row.port,
buildable: true,
}
if row.kind == rowLocal {
result.localImage = row.local.Reference()
result.provenance = row.local
result.pr = row.local.PRNumber
return result
}
result.pr = row.pr.Number
result.localImage = row.localReference()
// A pull request always has a rebuild recipe even without a local image:
// clone the head into a temporary checkout and build it as homarr:pr-N.
result.provenance = docker.Image{Tag: fmt.Sprintf("pr-%d", row.pr.Number), PRNumber: row.pr.Number}
if row.local.Tag != "" {
result.provenance = row.local
}
return result
}
func (m Model) instanceTarget(row instanceRow) target {
result := target{
label: row.container.Name,
container: row.container.Name,
volume: row.container.Name + "_data",
running: row.container.Running(),
port: row.container.HostPort(),
}
if strings.HasPrefix(row.container.Image, "homarr:") {
result.localImage = row.container.Image
tag := strings.TrimPrefix(row.container.Image, "homarr:")
for _, image := range m.images {
if image.Tag == tag {
result.provenance, result.buildable = image, true
break
}
}
}
if number := row.prNumber(); number > 0 {
result.pr = number
if !result.buildable {
result.provenance = docker.Image{Tag: fmt.Sprintf("pr-%d", number), PRNumber: number}
result.buildable = true
}
}
return result
}
// primaryAction is Enter: stop what is running, start what is not. A matching
// local build and a published registry image open a small source selector;
// otherwise the only available source is started directly.
func (m Model) primaryAction() (Model, tea.Cmd) {
if m.screen == screenInstances {
row, found := m.selectedInstance()
if !found {
return m, nil
}
if row.container.Running() {
return m.stopContainer(row.container.Name)
}
return m.restartContainer(row.container.Name)
}
row, found := m.selectedDev()
if !found {
return m, nil
}
if row.running {
return m.stopContainer(row.containerName())
}
if row.kind == rowLocal {
return m.startLocal(row)
}
if row.hasCurrentLocalImage() {
if m.remoteImageAvailable(row) {
return m.selectImage(row)
}
return m.startLocalPR(row)
}
switch row.image {
case ui.ImageUnknown, ui.ImageChecking:
m.status, m.statusLevel = "still checking whether CI published an image for "+row.label(), levelWarn
return m, nil
case ui.ImageMissing:
m.status, m.statusLevel = fmt.Sprintf("CI has not published an image for PR #%d yet — press R to build it locally", row.pr.Number), levelWarn
return m, nil
}
return m.deployRemotePR(row)
}
func (m Model) remoteImageAvailable(row devRow) bool {
return row.kind == rowRemote && m.tagsKnown && registry.HasPRImage(m.tags, row.pr.Number)
}
func (m Model) selectImage(row devRow) (Model, tea.Cmd) {
m.imageSelection = imageSelection{rowKey: row.key(), choice: imageChoiceLocal}
m.mode = modeImageSelect
m.status, m.statusLevel = "choose an image source for "+row.label(), levelInfo
m.relayout()
return m, nil
}
func (m Model) startLocal(row devRow) (Model, tea.Cmd) {
plan, err := run.BuildPlan(run.Options{Context: context.Background(), Tag: row.local.Tag, Demo: m.demo})
if err != nil {
m.status, m.statusLevel = err.Error(), levelError
return m, nil
}
return m.startPlan("start "+row.local.Reference(), row.containerName(), plan)
}
func (m Model) startLocalPR(row devRow) (Model, tea.Cmd) {
plan, err := localPRPlan(row, m.demo)
if err != nil {
m.status, m.statusLevel = err.Error(), levelError
return m, nil
}
return m.startPlan(fmt.Sprintf("start PR #%d from local build", row.pr.Number), row.containerName(), plan)
}
// localPRPlan runs a locally built image under the pull request's container and
// volume identity, so switching between a local build and the registry build of
// the same pull request keeps the same data and port.
func localPRPlan(row devRow, demo bool) (*run.Plan, error) {
plan, err := run.BuildPlan(run.Options{Context: context.Background(), Tag: row.local.Tag, Demo: demo})
if err != nil {
return nil, err
}
plan.Name = row.containerName()
plan.Volume = row.volumeName()
plan.Label = fmt.Sprintf("PR #%d · local %s", row.pr.Number, truncateRevision(row.local.Revision))
plan.PRNumber = row.pr.Number
return plan, nil
}
func truncateRevision(revision string) string {
if len(revision) > 12 {
return revision[:12]
}
return revision
}
func (m Model) startPlan(title, container string, plan *run.Plan) (Model, tea.Cmd) {
m.tasks.Action(title, container, func(ctx context.Context) error {
plan.Pull = false
return run.StartDetached(plan)
})
m.status, m.statusLevel = fmt.Sprintf("%s → http://localhost:%d", title, plan.HostPort), levelInfo
return m, nil
}
// deployRemotePR pulls the registry image and starts it as one job, so the
// sidebar shows a single continuous progress stream rather than two.
func (m Model) deployRemotePR(row devRow) (Model, tea.Cmd) {
if existing, running := m.tasks.RunningFor(row.containerName()); running {
m.status, m.statusLevel = existing.Title+" is already running", levelWarn
return m, nil
}
plan, err := run.BuildPlan(run.Options{Context: context.Background(), PR: row.pr.Number, Demo: m.demo})
if err != nil {
m.status, m.statusLevel = err.Error(), levelError
return m, nil
}
// Reuse the port a running instance already holds so a redeploy does not
// move the URL out from under an open browser tab.
if row.running && row.port != "" {
if port, err := strconv.Atoi(row.port); err == nil {
plan.HostPort = port
}
}
title := fmt.Sprintf("pull and start PR #%d", row.pr.Number)
created := m.tasks.Start(task.KindPull, title, row.containerName(), func(ctx context.Context, report *task.Reporter) error {
if err := task.PullImage(ctx, report, plan.Image, plan.Platform); err != nil {
return err
}
report.SetDetail("starting container on port " + strconv.Itoa(plan.HostPort))
plan.Pull = false
return run.StartDetached(plan)
})
return m.focusOn(created.ID(), title)
}
// buildLocally rebuilds the selection in the background. A pull request without
// a local image is cloned into a temporary checkout first.
func (m Model) buildLocally(subject target) (Model, tea.Cmd) {
if !subject.buildable {
m.status, m.statusLevel = subject.label+" has no build source to rebuild from", levelWarn
return m, nil
}
reference := "homarr:" + subject.provenance.Tag
if existing, running := m.tasks.RunningFor(reference); running {
m.status, m.statusLevel = existing.Title+" is already running", levelWarn
return m, nil
}
image := subject.provenance
title := "build " + reference
created := m.tasks.BuildFrom(title, reference, func(ctx context.Context, report *task.Reporter) (docker.BuildOptions, error) {
options, cleanup, err := run.RebuildOptions(ctx, image, report.Log)
if err != nil {
return docker.BuildOptions{}, err
}
// The checkout has to outlive option construction but not the build,
// and BuildFrom runs both inside one job, so releasing it when the job
// goroutine unwinds is both correct and the simplest thing available.
context.AfterFunc(ctx, cleanup)
return options, nil
})
return m.focusOn(created.ID(), title)
}
func (m Model) pullRemote(row devRow) (Model, tea.Cmd) {
if row.kind != rowRemote {
m.status, m.statusLevel = "pulling only applies to pull-request images", levelWarn
return m, nil
}
return m.deployRemotePR(row)
}
// focusOn points the tray and sidebar at a freshly started job so its progress
// is visible without any further keystrokes.
func (m Model) focusOn(id int, title string) (Model, tea.Cmd) {
m.focusTask = id
m.sidebar.visible = true
m.sidebar.source = sourceTask
m.sidebar.follow = true
m.status, m.statusLevel = title+" started in the background", levelInfo
m.relayout()
cmd := m.refreshSidebar()
clocks := m.animate()
return m, tea.Batch(cmd, clocks)
}
func (m Model) stopContainer(name string) (Model, tea.Cmd) {
m.tasks.Action("stop "+name, name, func(ctx context.Context) error { return docker.StopContext(ctx, name) })
m.status, m.statusLevel = "stopping "+name+"…", levelInfo
return m, nil
}
func (m Model) restartContainer(name string) (Model, tea.Cmd) {
m.tasks.Action("restart "+name, name, func(ctx context.Context) error { return docker.RestartContext(ctx, name) })
m.status, m.statusLevel = "restarting "+name+"…", levelInfo
return m, nil
}
func (m Model) removeContainer(name string) (Model, tea.Cmd) {
m.tasks.Action("remove "+name, name, func(ctx context.Context) error { return docker.RemoveContext(ctx, name) })
m.status, m.statusLevel = "removing "+name+"…", levelInfo
return m, nil
}
func (m Model) deleteImage(reference string) (Model, tea.Cmd) {
m.tasks.Action("delete "+reference, reference, func(ctx context.Context) error {
return docker.RemoveImage(ctx, reference)
})
m.status, m.statusLevel = "deleting "+reference+"…", levelInfo
return m, nil
}
// deleteData removes an instance's volume. Docker refuses to delete a volume
// that is still attached, so the container is removed first — the data is going
// away either way, and failing halfway would leave the user to work out why.
func (m Model) deleteData(subject target) (Model, tea.Cmd) {
container, volume := subject.container, subject.volume
m.tasks.Action("delete data "+volume, volume, func(ctx context.Context) error {
_ = docker.RemoveContext(ctx, container)
return docker.RemoveVolume(ctx, volume)
})
m.status, m.statusLevel = "deleting "+volume+"…", levelInfo
return m, nil
}
func (m Model) pruneStopped() (Model, tea.Cmd) {
names := make([]string, 0)
for _, container := range m.containers {
if !container.Running() {
names = append(names, container.Name)
}
}
if len(names) == 0 {
m.status, m.statusLevel = "no stopped Homarr containers to prune", levelInfo
return m, nil
}
m.tasks.Action(fmt.Sprintf("prune %d stopped containers", len(names)), "prune", func(ctx context.Context) error {
for _, name := range names {
if err := docker.RemoveContext(ctx, name); err != nil {
return err
}
}
return nil
})
m.status, m.statusLevel = fmt.Sprintf("pruning %d stopped containers…", len(names)), levelInfo
return m, nil
}
func (m Model) openPullRequest() (Model, tea.Cmd) {
row, found := m.selectedDev()
if !found || row.kind != rowRemote {
m.status, m.statusLevel = "select a pull request to open it on GitHub", levelWarn
return m, nil
}
return m.openPullRequestNumber(row.pr.Number)
}
func (m Model) openPullRequestNumber(number int) (Model, tea.Cmd) {
if number <= 0 {
return m, nil
}
url := fmt.Sprintf("https://github.com/%s/pull/%d", gitHubRepo, number)
if err := platform.OpenURL(url); err != nil {
m.status, m.statusLevel = "open failed: "+err.Error(), levelError
return m, nil
}
m.status, m.statusLevel = "opened "+url, levelOK
return m, nil
}
const gitHubRepo = "homarr-labs/homarr"
func (m Model) openApp() (Model, tea.Cmd) {
subject, found := m.currentTarget()
if !found || !subject.running || subject.port == "" {
m.status, m.statusLevel = "selection is not running", levelWarn
return m, nil
}
url := "http://localhost:" + subject.port
if err := platform.OpenURL(url); err != nil {
m.status, m.statusLevel = "open failed: "+err.Error(), levelError
return m, nil
}
m.status, m.statusLevel = "opened "+url, levelOK
return m, nil
}
func (m Model) copyURL() (Model, tea.Cmd) {
subject, found := m.currentTarget()
if !found || subject.port == "" {
m.status, m.statusLevel = "selection has no published port", levelWarn
return m, nil
}
url := "http://localhost:" + subject.port
if err := platform.CopyText(url); err != nil {
m.status, m.statusLevel = "copy failed: "+err.Error(), levelError
return m, nil
}
m.status, m.statusLevel = "copied "+url, levelOK
return m, nil
}
// remoteImageFor is used by the detail view to name the registry image a row
// would pull.
func remoteImageFor(row devRow) string {
if row.kind != rowRemote {
return ""
}
return registry.ImageReference(row.pr.Number)
}
-122
View File
@@ -1,122 +0,0 @@
package tui
import (
"charm.land/bubbles/v2/spinner"
tea "charm.land/bubbletea/v2"
)
type appModel struct {
dev prsModel
dashboard dashModel
showDashboard bool
width int
height int
}
func newAppModel(showDashboard bool) appModel {
return appModel{dev: newPRsModel(), dashboard: newDashModel(), showDashboard: showDashboard}
}
func (m appModel) Init() tea.Cmd {
if m.showDashboard {
return m.dashboard.Init()
}
return m.dev.Init()
}
func (m appModel) canSwitch() bool {
if m.showDashboard {
return !m.dashboard.filtering
}
return !m.dev.filtering && !m.dev.pulling
}
func (m appModel) switchScreen() (tea.Model, tea.Cmd) {
m.showDashboard = !m.showDashboard
commands := make([]tea.Cmd, 0, 2)
if m.width > 0 && m.height > 0 {
resize := tea.WindowSizeMsg{Width: m.width, Height: m.height}
if m.showDashboard {
updated, command := m.dashboard.Update(resize)
m.dashboard = updated.(dashModel)
commands = append(commands, command)
} else {
updated, command := m.dev.Update(resize)
m.dev = updated.(prsModel)
commands = append(commands, command)
}
}
if m.showDashboard {
commands = append(commands, m.dashboard.Init())
} else {
commands = append(commands, m.dev.Init())
}
return m, tea.Batch(commands...)
}
func (m appModel) updateDev(msg tea.Msg) (appModel, tea.Cmd) {
updated, command := m.dev.Update(msg)
m.dev = updated.(prsModel)
return m, command
}
func (m appModel) updateDashboard(msg tea.Msg) (appModel, tea.Cmd) {
updated, command := m.dashboard.Update(msg)
m.dashboard = updated.(dashModel)
return m, command
}
func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if window, ok := msg.(tea.WindowSizeMsg); ok {
m.width = window.Width
m.height = window.Height
m, devCommand := m.updateDev(msg)
m, dashboardCommand := m.updateDashboard(msg)
return m, tea.Batch(devCommand, dashboardCommand)
}
if key, ok := msg.(tea.KeyPressMsg); ok {
if key.String() == "d" && m.canSwitch() {
return m.switchScreen()
}
if m.showDashboard {
return m.updateDashboard(msg)
}
return m.updateDev(msg)
}
switch msg.(type) {
case prsLoadedMsg, imageCheckedMsg, prActionMsg, rebuildDoneMsg, runningRefreshedMsg, pullReadyMsg, pullEvent, spinner.TickMsg:
return m.updateDev(msg)
case tickMsg, actionMsg, rowsMsg:
if m.showDashboard {
return m.updateDashboard(msg)
}
return m, nil
case prLogTickMsg:
if !m.showDashboard {
return m.updateDev(msg)
}
return m, nil
case logsMsg:
m, devCommand := m.updateDev(msg)
m, dashboardCommand := m.updateDashboard(msg)
return m, tea.Batch(devCommand, dashboardCommand)
}
if m.showDashboard {
return m.updateDashboard(msg)
}
return m.updateDev(msg)
}
func (m appModel) View() tea.View {
if m.showDashboard {
return m.dashboard.View()
}
return m.dev.View()
}
func runApp(showDashboard bool) error {
program := tea.NewProgram(newAppModel(showDashboard))
_, err := program.Run()
return err
}
-47
View File
@@ -1,47 +0,0 @@
package tui
import (
"testing"
tea "charm.land/bubbletea/v2"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/gh"
)
func TestAppTogglePreservesDevelopmentState(t *testing.T) {
m := newAppModel(false)
m.dev.rows = []prRow{{kind: "remote", pr: gh.PR{Number: 6502}}}
updated, _ := m.Update(tea.KeyPressMsg(tea.Key{Code: 'd', Text: "d"}))
dashboard := updated.(appModel)
if !dashboard.showDashboard {
t.Fatal("d did not open the instance dashboard")
}
updated, _ = dashboard.Update(tea.KeyPressMsg(tea.Key{Code: 'd', Text: "d"}))
development := updated.(appModel)
if development.showDashboard || len(development.dev.rows) != 1 || development.dev.rows[0].pr.Number != 6502 {
t.Fatalf("development state was not preserved: %#v", development.dev.rows)
}
}
func TestAppToggleDoesNotInterceptFilterInput(t *testing.T) {
m := newAppModel(false)
m.dev.filtering = true
m.dev.filter.Focus()
updated, _ := m.Update(tea.KeyPressMsg(tea.Key{Code: 'd', Text: "d"}))
got := updated.(appModel)
if got.showDashboard || got.dev.filter.Value() != "d" {
t.Fatalf("filter input was intercepted: dashboard=%v filter=%q", got.showDashboard, got.dev.filter.Value())
}
}
func TestAppCanOpenInstancesDuringBuild(t *testing.T) {
m := newAppModel(false)
m.dev.rebuilding = true
updated, _ := m.Update(tea.KeyPressMsg(tea.Key{Code: 'd', Text: "d"}))
if !updated.(appModel).showDashboard {
t.Fatal("background build blocked dashboard navigation")
}
}
-415
View File
@@ -1,415 +0,0 @@
package tui
import (
"context"
"fmt"
"os/exec"
"strings"
"time"
"charm.land/bubbles/v2/table"
"charm.land/bubbles/v2/textinput"
"charm.land/bubbles/v2/viewport"
tea "charm.land/bubbletea/v2"
"charm.land/lipgloss/v2"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/docker"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/platform"
)
var (
titleStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("212"))
helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241"))
logHeadSt = lipgloss.NewStyle().Foreground(lipgloss.Color("241"))
runningLegend = lipgloss.NewStyle().Foreground(lipgloss.Color("42")).Render("● running")
stoppedLegend = lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render("○ stopped")
)
type dashModel struct {
table table.Model
allRows []table.Row
filter textinput.Model
filtering bool
logs viewport.Model
showLogs bool
follow bool
status string
confirmRemove string
width int
height int
}
type tickMsg time.Time
type actionMsg string
type rowsMsg []table.Row
type logsMsg struct {
name string
content string
}
func tick() tea.Cmd {
return tea.Tick(3*time.Second, func(t time.Time) tea.Msg { return tickMsg(t) })
}
func fetchLogs(name string) tea.Cmd {
return func() tea.Msg {
if name == "" {
return logsMsg{}
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, "docker", "logs", "--tail", "200", name).CombinedOutput()
if err != nil {
return logsMsg{name: name, content: "logs unavailable: " + err.Error()}
}
return logsMsg{name: name, content: string(out)}
}
}
func loadRows() tea.Cmd {
return func() tea.Msg { return rowsMsg(refreshRows()) }
}
func refreshRows() []table.Row {
containers, _ := docker.List()
rows := make([]table.Row, 0, len(containers))
for _, c := range containers {
port := c.HostPort()
url := ""
if port != "" && c.Running() {
url = "http://localhost:" + port
}
state := "● " + c.State
if !c.Running() {
state = "○ " + c.State
}
img := strings.TrimPrefix(c.Image, "ghcr.io/homarr-labs/")
rows = append(rows, table.Row{c.Name, state, img, port, url, c.Status})
}
return rows
}
func dashboardColumns(width int) []table.Column {
nameWidth := 26
imageWidth := 30
urlWidth := 24
if width < 100 {
nameWidth = 22
imageWidth = max(width-54, 18)
urlWidth = 0
}
return []table.Column{
{Title: "NAME", Width: nameWidth},
{Title: "STATE", Width: 14},
{Title: "IMAGE", Width: imageWidth},
{Title: "PORT", Width: 6},
{Title: "URL", Width: urlWidth},
{Title: "STATUS", Width: 0},
}
}
func newDashModel() dashModel {
t := table.New(
table.WithColumns(dashboardColumns(104)),
table.WithFocused(true),
table.WithHeight(10),
table.WithWidth(104),
)
s := table.DefaultStyles()
s.Header = s.Header.Bold(true)
s.Selected = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("230")).Background(lipgloss.Color("57"))
t.SetStyles(s)
logs := viewport.New(viewport.WithWidth(104), viewport.WithHeight(12))
logs.SoftWrap = true
filter := textinput.New()
filter.Prompt = "/ "
filter.Placeholder = "filter name, image, port, state…"
filter.SetWidth(50)
styles := textinput.DefaultDarkStyles()
styles.Focused.Prompt = styles.Focused.Prompt.Foreground(lipgloss.Color("212")).Bold(true)
styles.Focused.Text = styles.Focused.Text.Foreground(lipgloss.Color("229"))
filter.SetStyles(styles)
return dashModel{table: t, filter: filter, logs: logs, showLogs: true, follow: true, width: 104, height: 30}
}
func (m *dashModel) applyFilter() {
query := strings.ToLower(strings.TrimSpace(m.filter.Value()))
if query == "" {
m.table.SetRows(m.allRows)
return
}
rows := make([]table.Row, 0, len(m.allRows))
for _, row := range m.allRows {
if strings.Contains(strings.ToLower(strings.Join(row, " ")), query) {
rows = append(rows, row)
}
}
m.table.SetRows(rows)
}
func (m dashModel) selected() string {
row := m.table.SelectedRow()
if len(row) == 0 {
return ""
}
return row[0]
}
func (m dashModel) selectedPort() string {
row := m.table.SelectedRow()
if len(row) < 4 {
return ""
}
return row[3]
}
func (m dashModel) Init() tea.Cmd {
return tea.Batch(tick(), loadRows(), fetchLogs(m.selected()))
}
func (m dashModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
m.table.SetColumns(dashboardColumns(msg.Width))
m.table.SetWidth(msg.Width)
m.logs.SetWidth(msg.Width)
m.filter.SetWidth(max(min(msg.Width-4, 60), 10))
m.layout()
return m, nil
case tickMsg:
return m, tea.Batch(tick(), loadRows())
case rowsMsg:
m.allRows = []table.Row(msg)
m.applyFilter()
return m, fetchLogs(m.selected())
case logsMsg:
if msg.name != "" && msg.name != m.selected() {
return m, nil
}
m.logs.SetContent(strings.TrimRight(msg.content, "\n"))
if m.follow {
m.logs.GotoBottom()
}
return m, nil
case actionMsg:
m.status = string(msg)
m.confirmRemove = ""
return m, loadRows()
case tea.KeyPressMsg:
if m.filtering {
switch msg.Key().Code {
case tea.KeyEscape:
m.filtering = false
m.filter.Reset()
m.filter.Blur()
m.applyFilter()
return m, fetchLogs(m.selected())
case tea.KeyEnter:
m.filtering = false
m.filter.Blur()
return m, fetchLogs(m.selected())
}
var cmd tea.Cmd
m.filter, cmd = m.filter.Update(msg)
m.applyFilter()
return m, tea.Batch(cmd, fetchLogs(m.selected()))
}
name := m.selected()
switch msg.Key().Code {
case tea.KeyUp, tea.KeyKpUp:
m.table.MoveUp(1)
return m, fetchLogs(m.selected())
case tea.KeyDown, tea.KeyKpDown:
m.table.MoveDown(1)
return m, fetchLogs(m.selected())
case tea.KeyPgUp, tea.KeyKpPgUp:
m.follow = false
m.logs.PageUp()
return m, nil
case tea.KeyPgDown, tea.KeyKpPgDown:
m.logs.PageDown()
m.follow = m.logs.AtBottom()
return m, nil
}
switch msg.String() {
case "q", "ctrl+c", "esc":
return m, tea.Quit
case "l":
m.showLogs = !m.showLogs
m.layout()
if m.showLogs {
return m, fetchLogs(name)
}
return m, nil
case "/":
m.filtering = true
return m, m.filter.Focus()
case "f":
m.follow = !m.follow
if m.follow {
m.logs.GotoBottom()
}
return m, nil
case "s":
if name != "" {
m.status = "stopping " + name + "…"
return m, func() tea.Msg {
if err := docker.Stop(name); err != nil {
return actionMsg("stop failed: " + err.Error())
}
return actionMsg("stopped " + name)
}
}
case "x":
if name != "" {
if m.confirmRemove != name {
m.confirmRemove = name
m.status = "press x again to remove " + name
return m, nil
}
m.status = "removing " + name + "…"
return m, func() tea.Msg {
if err := docker.Remove(name); err != nil {
return actionMsg("remove failed: " + err.Error())
}
return actionMsg("removed " + name)
}
}
case "R":
if name != "" {
m.status = "restarting " + name + "…"
return m, func() tea.Msg {
if err := docker.Restart(name); err != nil {
return actionMsg("restart failed: " + err.Error())
}
return actionMsg("restarted " + name)
}
}
case "o":
if name != "" {
if port := m.selectedPort(); port != "" {
if err := platform.OpenURL("http://localhost:" + port); err != nil {
m.status = "open failed: " + err.Error()
}
}
}
case "c":
if name != "" {
if port := m.selectedPort(); port != "" {
url := "http://localhost:" + port
if err := platform.CopyText(url); err != nil {
m.status = "copy failed: " + err.Error()
} else {
m.status = "copied " + url
}
}
}
case "r":
return m, loadRows()
case "k":
m.table.MoveUp(1)
return m, fetchLogs(m.selected())
case "j":
m.table.MoveDown(1)
return m, fetchLogs(m.selected())
}
}
var cmd tea.Cmd
m.table, cmd = m.table.Update(msg)
return m, cmd
}
func (m *dashModel) layout() {
available := m.height - 11
if m.filtering || m.filter.Value() != "" {
available -= 2
}
if !m.showLogs {
m.table.SetHeight(max(available, 5))
return
}
tableH := min(12, max(available/2, 5))
m.table.SetHeight(tableH)
logsH := available - tableH
if logsH < 3 {
logsH = 3
}
m.logs.SetHeight(logsH)
}
func (m dashModel) selectedDetailView() string {
row := m.table.SelectedRow()
if len(row) < 6 {
return ""
}
title := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("229")).Render(row[0])
meta := row[2] + " · " + row[1]
if row[3] != "" {
meta += " · port " + row[3]
}
if row[4] != "" {
meta += " · " + row[4]
}
if row[5] != "" {
meta += " · " + row[5]
}
return title + "\n" + helpStyle.Render(meta)
}
func (m dashModel) View() tea.View {
var b strings.Builder
running := 0
for _, row := range m.allRows {
if len(row) > 1 && strings.Contains(row[1], "running") {
running++
}
}
b.WriteString(titleStyle.Render("🦞 homarr instances") + " " + helpStyle.Render(fmt.Sprintf("%d total · %d running · %d shown", len(m.allRows), running, len(m.table.Rows()))))
b.WriteString("\n\n")
if m.filtering || m.filter.Value() != "" {
b.WriteString(m.filter.View() + "\n\n")
}
if len(m.table.Rows()) == 0 {
message := "no homarr containers — start one with `homarr run <tag>` or `homarr run --pr N`"
if len(m.allRows) > 0 {
message = "no instances match " + m.filter.Value()
}
b.WriteString(helpStyle.Render(" " + message + "\n"))
} else {
b.WriteString(m.table.View())
b.WriteString("\n")
}
if detail := m.selectedDetailView(); detail != "" {
b.WriteString("\n" + detail + "\n")
}
if m.showLogs && len(m.table.Rows()) > 0 {
mode := "paused"
if m.follow {
mode = "following"
}
b.WriteString("\n" + logHeadSt.Render("── logs: "+m.selected()+" ("+mode+") ──") + "\n")
b.WriteString(m.logs.View())
}
if m.status != "" {
statusStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("42"))
lower := strings.ToLower(m.status)
if strings.Contains(lower, "fail") || strings.Contains(lower, "error") {
statusStyle = statusStyle.Foreground(lipgloss.Color("196"))
} else if strings.Contains(lower, "press x") {
statusStyle = statusStyle.Foreground(lipgloss.Color("214"))
}
b.WriteString("\n" + statusStyle.Render(m.status))
}
b.WriteString("\n\n" + helpStyle.Render("/ filter · ↑/↓ select · l logs · f follow · pgup/pgdn scroll · s stop · R restart · x remove · o open · c copy URL · r refresh · d development · q quit"))
b.WriteString("\n" + helpStyle.Render(runningLegend+" · "+stoppedLegend))
v := tea.NewView(b.String())
v.AltScreen = true
v.WindowTitle = "🦞 Homarr instances"
return v
}
func RunDashboard() error {
return runApp(true)
}
@@ -1,62 +0,0 @@
package tui
import (
"strings"
"testing"
"charm.land/bubbles/v2/table"
tea "charm.land/bubbletea/v2"
)
func TestDashboardRendersRowsAndLogs(t *testing.T) {
m := newDashModel()
m.table.SetRows([]table.Row{{
"homarr_pr_6441",
"running",
"homarr-test:pr-6441",
"7575",
"http://localhost:7575",
"Up 2 minutes",
}})
m.logs.SetWidth(104)
m.logs.SetHeight(5)
m.logs.SetContent("server ready")
got := m.View().Content
for _, want := range []string{"homarr_pr_6441", "server ready"} {
if !strings.Contains(got, want) {
t.Fatalf("dashboard omitted %q: %q", want, got)
}
}
if !m.View().AltScreen {
t.Fatal("dashboard must use the alternate screen")
}
}
func TestDashboardArrowNavigation(t *testing.T) {
m := newDashModel()
m.table.SetRows([]table.Row{
{"homarr_first", "running", "homarr:first", "7575", "", "Up 1 minute"},
{"homarr_second", "running", "homarr:second", "7576", "", "Up 1 minute"},
})
updated, _ := m.Update(tea.KeyPressMsg(tea.Key{Code: tea.KeyDown}))
got := updated.(dashModel).selected()
if got != "homarr_second" {
t.Fatalf("down arrow selected %q, want homarr_second", got)
}
}
func TestDashboardIgnoresStaleLogs(t *testing.T) {
m := newDashModel()
m.table.SetRows([]table.Row{{"homarr_current", "running", "homarr:current", "7575", "", "Up 1 minute"}})
m.logs.SetWidth(104)
m.logs.SetHeight(5)
m.logs.SetContent("current logs")
updated, _ := m.Update(logsMsg{name: "homarr_old", content: "stale logs"})
got := updated.(dashModel).View().Content
if strings.Contains(got, "stale logs") || !strings.Contains(got, "current logs") {
t.Fatalf("stale log result replaced current content: %q", got)
}
}
+155
View File
@@ -0,0 +1,155 @@
package tui
import (
"context"
"sync"
"time"
tea "charm.land/bubbletea/v2"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/docker"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/gh"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/logs"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/registry"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/task"
)
// loadedMsg carries a full refresh. Every source is fetched concurrently and
// each failure is reported separately, so a missing GitHub CLI degrades the
// pull-request list without hiding local images.
type loadedMsg struct {
generation int
prs []gh.PR
images []docker.Image
containers []docker.Container
volumes []docker.Volume
tags map[string]bool
prErr error
imageErr error
tagErr error
}
// containersMsg is the cheap periodic refresh; it skips GitHub and the registry.
type containersMsg struct {
generation int
containers []docker.Container
volumes []docker.Volume
}
type (
tasksChangedMsg struct{}
logsChangedMsg struct{}
ciChecksMsg struct {
pr int
checks []gh.Check
err error
}
pollCIChecksMsg struct {
pr int
}
frameMsg time.Time
refreshMsg time.Time
statusMsg struct {
text string
level statusLevel
}
)
const (
loadTimeout = 45 * time.Second
refreshEvery = 3 * time.Second
frameEvery = 90 * time.Millisecond
prListingLimit = 60
)
// loadAll fetches every data source in parallel and reports them as one
// message, so the table is only rebuilt once per refresh.
func loadAll(generation int, includeBots, refresh bool) tea.Cmd {
return func() tea.Msg {
ctx, cancel := context.WithTimeout(context.Background(), loadTimeout)
defer cancel()
var (
group sync.WaitGroup
message = loadedMsg{generation: generation}
)
group.Add(3)
go func() {
defer group.Done()
if refresh {
message.prs, message.prErr = gh.RefreshPRs(ctx, prListingLimit, includeBots)
return
}
message.prs, message.prErr = gh.ListPRs(ctx, prListingLimit, includeBots)
}()
go func() {
defer group.Done()
message.images, message.imageErr = docker.ListLocalImages(ctx)
}()
go func() {
defer group.Done()
message.tags, message.tagErr = registry.PublishedTags(ctx, refresh)
}()
group.Wait()
message.containers, _ = docker.List()
message.volumes, _ = docker.ListVolumes(ctx, true)
return message
}
}
// loadContainers is the lightweight poll that keeps running state current
// without paying for GitHub, registry or disk-usage round trips.
func loadContainers(generation int) tea.Cmd {
return func() tea.Msg {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
containers, _ := docker.List()
volumes, _ := docker.ListVolumes(ctx, false)
return containersMsg{generation: generation, containers: containers, volumes: volumes}
}
}
// waitForTasks parks a goroutine on the task manager's coalescing wake-up
// channel. Exactly one of these is in flight at a time; each wake-up re-arms
// itself, which is what lets background work drive redraws without polling.
func waitForTasks(manager *task.Manager) tea.Cmd {
return func() tea.Msg {
<-manager.Changed()
return tasksChangedMsg{}
}
}
// waitForLogs mirrors waitForTasks for the live container log streams.
func waitForLogs(registry *logs.Registry) tea.Cmd {
return func() tea.Msg {
<-registry.Changed()
return logsChangedMsg{}
}
}
func tickRefresh() tea.Cmd {
return tea.Tick(refreshEvery, func(now time.Time) tea.Msg { return refreshMsg(now) })
}
// tickFrame drives spinner and progress-bar animation. It only runs while
// something is actually moving, so an idle CLI costs no wake-ups at all.
func tickFrame() tea.Cmd {
return tea.Tick(frameEvery, func(now time.Time) tea.Msg { return frameMsg(now) })
}
func notify(text string, level statusLevel) tea.Cmd {
return func() tea.Msg { return statusMsg{text: text, level: level} }
}
func fetchCIChecks(pr int, refresh bool) tea.Cmd {
if pr <= 0 {
return nil
}
return func() tea.Msg {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
checks, err := gh.GetPRChecks(ctx, pr, refresh)
return ciChecksMsg{pr: pr, checks: checks, err: err}
}
}
File diff suppressed because it is too large. Load diff
-228
View File
@@ -1,228 +0,0 @@
package tui
import (
"errors"
"strings"
"testing"
tea "charm.land/bubbletea/v2"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/docker"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/gh"
)
func TestPRTableRendersRows(t *testing.T) {
m := newPRsModel()
m.rows = []prRow{{
kind: "remote",
pr: gh.PR{Number: 6441, Title: "Human PR", Author: "ajnart", CIState: "SUCCESS"},
imageState: "yes",
}}
m.table.SetRows(buildTableRows(m.rows))
if got := m.View().Content; !strings.Contains(got, "Human PR") {
t.Fatalf("table view omitted rows: %q", got)
}
if !m.View().AltScreen {
t.Fatal("development browser must use the alternate screen")
}
}
func TestPRTableArrowNavigation(t *testing.T) {
m := newPRsModel()
m.rows = []prRow{
{kind: "remote", pr: gh.PR{Number: 1, Title: "First"}},
{kind: "remote", pr: gh.PR{Number: 2, Title: "Second"}},
}
m.table.SetRows(buildTableRows(m.rows))
updated, _ := m.Update(tea.KeyPressMsg(tea.Key{Code: tea.KeyDown}))
got := updated.(prsModel).table.SelectedRow()
if len(got) < 3 || got[2] != "2" {
t.Fatalf("down arrow selected %v, want PR 2", got)
}
}
func TestPRImageChecksAreBounded(t *testing.T) {
m := newPRsModel()
prs := make([]gh.PR, 20)
for i := range prs {
prs[i] = gh.PR{Number: i + 1, Title: "PR"}
}
updated, cmd := m.Update(prsLoadedMsg{prs: prs})
got := updated.(prsModel)
if cmd == nil {
t.Fatal("expected image check commands")
}
if got.imageActive != 6 || len(got.imageQueue) != 14 {
t.Fatalf("active=%d queued=%d, want active=6 queued=14", got.imageActive, len(got.imageQueue))
}
}
func TestPRLoadedReusesImageChecksUnlessRefreshIsForced(t *testing.T) {
m := newPRsModel()
m.rows = []prRow{{kind: "remote", pr: gh.PR{Number: 1}, imageState: "yes"}}
updated, _ := m.Update(prsLoadedMsg{prs: []gh.PR{{Number: 1}, {Number: 2}}})
cached := updated.(prsModel)
if cached.rows[0].imageState != "yes" || len(cached.imageQueue) != 0 || cached.imageActive != 1 {
t.Fatalf("cached states were not reused: rows=%#v queue=%v active=%d", cached.rows, cached.imageQueue, cached.imageActive)
}
updated, _ = cached.Update(prsLoadedMsg{prs: []gh.PR{{Number: 1}, {Number: 2}}, refresh: true})
refreshed := updated.(prsModel)
if refreshed.rows[0].imageState != "checking" || refreshed.imageActive != 2 {
t.Fatalf("forced refresh reused image states: rows=%#v active=%d", refreshed.rows, refreshed.imageActive)
}
}
func TestDevelopmentRowsFoldCurrentLocalPRImage(t *testing.T) {
prs := []gh.PR{{Number: 6502, HeadSHA: "current"}}
images := []docker.Image{
{Tag: "pr-6502", PRNumber: 6502, Revision: "current"},
{Tag: "pr-6502-stale", PRNumber: 6502, Revision: "stale"},
}
rows, queue := developmentRows(prs, images, nil)
if len(rows) != 2 || !rows[0].hasCurrentLocalImage() || rows[0].local.Tag != "pr-6502" {
t.Fatalf("current image was not folded into PR row: %#v", rows)
}
if rows[1].kind != "local" || rows[1].local.Tag != "pr-6502-stale" {
t.Fatalf("stale image should remain separate: %#v", rows[1])
}
if got := buildTableRows(rows)[0][6]; got != imgLocal {
t.Fatalf("image marker = %q, want %q", got, imgLocal)
}
if len(queue) != 0 {
t.Fatalf("current local image queued unnecessary registry checks: %v", queue)
}
}
func TestLocalPRPlanUsesPRContainerIdentity(t *testing.T) {
row := prRow{
kind: "remote",
pr: gh.PR{Number: 6502, HeadSHA: "abcdef1234567890"},
local: docker.Image{Tag: "pr-6502", PRNumber: 6502, Revision: "abcdef1234567890"},
}
plan, err := localPRPlan(row, false, func(int) int { return 7575 })
if err != nil {
t.Fatal(err)
}
if plan.Image != "homarr:pr-6502" || plan.Name != "homarr_pr_6502" || plan.Volume != "homarr_pr_6502_data" || plan.Pull || plan.PRNumber != 6502 {
t.Fatalf("unexpected local PR plan: %#v", plan)
}
}
func TestRemotePRBuildUsesTemporaryPRWorkflow(t *testing.T) {
image, action, status := localBuildForRow(prRow{kind: "remote", pr: gh.PR{Number: 6441}})
if image.Tag != "pr-6441" || image.PRNumber != 6441 || action != "built" || !strings.Contains(status, "building PR #6441 locally") {
t.Fatalf("image=%#v action=%q status=%q", image, action, status)
}
}
func TestPRImageCheckInProgressDoesNotLaunch(t *testing.T) {
m := newPRsModel()
m.rows = []prRow{{kind: "remote", pr: gh.PR{Number: 6441, Title: "Pending image"}, imageState: "checking"}}
m.table.SetRows(buildTableRows(m.rows))
updated, cmd := m.Update(tea.KeyPressMsg(tea.Key{Code: tea.KeyEnter}))
got := updated.(prsModel)
if cmd != nil {
t.Fatal("unavailable image returned a launch command")
}
if !strings.Contains(got.status, "still in progress") {
t.Fatalf("status = %q, want launch rejection", got.status)
}
}
func TestPullErrorIncludesLastDockerMessage(t *testing.T) {
err := commandErrorWithDetail(errors.New("exit status 1"), "manifest unknown")
if !strings.Contains(err.Error(), "manifest unknown") {
t.Fatalf("pull error = %v", err)
}
}
func TestOutputTailRetainsBuildFailure(t *testing.T) {
tail := &outputTail{}
_, _ = tail.Write([]byte("building\r\nERROR: Dockerfile not found\n"))
if got := tail.lastLine(); got != "ERROR: Dockerfile not found" {
t.Fatalf("last line = %q", got)
}
}
func TestDevTableRendersLocalImageSource(t *testing.T) {
m := newPRsModel()
m.rows = []prRow{{
kind: "local",
local: docker.Image{Tag: "feature", Source: "/tmp/homarr", Revision: "abcdef1234567890"},
imageState: "yes",
}}
m.table.SetRows(buildTableRows(m.rows))
content := m.View().Content
for _, want := range []string{"local", "homarr:feature", "/tmp/homarr", "abcdef123456"} {
if !strings.Contains(content, want) {
t.Fatalf("development view omitted %q: %q", want, content)
}
}
}
func TestRebuildCompletionRestoresLoadingState(t *testing.T) {
m := newPRsModel()
m.rebuilding = true
image := docker.Image{Tag: "feature"}
updated, cmd := m.Update(rebuildDoneMsg{image: image})
got := updated.(prsModel)
if got.rebuilding || !got.loading || got.status != "rebuilt homarr:feature" || cmd == nil {
t.Fatalf("unexpected rebuild state: rebuilding=%v loading=%v status=%q", got.rebuilding, got.loading, got.status)
}
}
func TestRebuildCanBeCanceled(t *testing.T) {
m := newPRsModel()
canceled := false
m.rebuilding = true
m.rebuildCancel = func() { canceled = true }
updated, cmd := m.Update(tea.KeyPressMsg(tea.Key{Code: 'q'}))
got := updated.(prsModel)
if !canceled || cmd != nil || got.status != "canceling rebuild…" {
t.Fatalf("cancel state: canceled=%v status=%q", canceled, got.status)
}
}
func TestNavigationRemainsAvailableDuringBuild(t *testing.T) {
m := newPRsModel()
m.rebuilding = true
m.rows = []prRow{
{kind: "remote", pr: gh.PR{Number: 1}},
{kind: "remote", pr: gh.PR{Number: 2}},
}
m.table.SetRows(buildTableRows(m.rows))
updated, _ := m.Update(tea.KeyPressMsg(tea.Key{Code: tea.KeyDown}))
selected := updated.(prsModel).table.SelectedRow()
if len(selected) < 3 || selected[2] != "2" {
t.Fatalf("build blocked navigation: %v", selected)
}
}
func TestCompletedPullWithoutPlanDoesNotPanic(t *testing.T) {
m := newPRsModel()
m.pulling = true
m.pullCancel = func() {}
updated, cmd := m.Update(pullEvent{done: true})
got := updated.(prsModel)
if got.pulling || cmd != nil {
t.Fatalf("pulling=%v cmd=%v", got.pulling, cmd)
}
}
func TestTruncateTextPreservesUTF8(t *testing.T) {
if got := truncateText("🦞homarr", 2); got != "🦞h" {
t.Fatalf("truncateText() = %q", got)
}
}
@@ -0,0 +1,270 @@
package tui
import (
"context"
"fmt"
"strings"
"testing"
"time"
tea "charm.land/bubbletea/v2"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/docker"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/gh"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/task"
)
func sample() (Model, tea.Cmd) {
m := New(false)
updated, _ := m.Update(tea.WindowSizeMsg{Width: 140, Height: 40})
m = updated.(Model)
loaded := loadedMsg{
prs: []gh.PR{
{Number: 6646, Title: "feat: rework the developer CLI from the ground up", Author: "ajnart", HeadRef: "excited-pelican", HeadSHA: "abc123", CIState: "SUCCESS"},
{Number: 6612, Title: "fix(board): keep the item modal aligned", Author: "meierschlurf", HeadRef: "fix/modal", HeadSHA: "def456", CIState: "PENDING"},
{Number: 6503, Title: "chore(deps): bump everything", Author: "renovate[bot]", HeadRef: "renovate/all", HeadSHA: "ghi789", CIState: "FAILURE", IsDraft: true},
},
images: []docker.Image{
{ID: "1", Tag: "pr-6646", PRNumber: 6646, Revision: "abc123", Size: "492MB", Created: "33 minutes ago", Source: "https://github.com/homarr-labs/homarr/pull/6646"},
{ID: "2", Tag: "dev", Revision: "zzz999", Size: "481MB", Created: "2 days ago", Source: "/Users/ajnart/homarr"},
},
containers: []docker.Container{
{ID: "c1", Name: "homarr_pr_6612", Image: "ghcr.io/homarr-labs/homarr-test:pr-6612", State: "running", Status: "Up 45 hours (healthy)", Ports: "0.0.0.0:7576->7575/tcp"},
{ID: "c2", Name: "homarr_dev", Image: "homarr:dev", State: "exited", Status: "Exited (0) 3 weeks ago"},
},
volumes: []docker.Volume{{Name: "homarr_pr_6612_data", Size: "6.8MB"}, {Name: "homarr_dev_data", Size: "12MB"}},
tags: map[string]bool{"pr-6612": true, "pr-6503": true},
}
next, cmd := m.Update(loaded)
return next.(Model), cmd
}
func TestRenderDev(t *testing.T) {
m, _ := sample()
fmt.Println("=========== DEV ===========")
fmt.Println(m.View().Content)
}
func TestRenderInstances(t *testing.T) {
m, _ := sample()
next, _ := m.switchScreen(screenInstances)
fmt.Println("=========== INSTANCES ===========")
fmt.Println(next.View().Content)
}
func TestDebugSelection(t *testing.T) {
m, _ := sample()
t.Logf("devFiltered=%d cursor=%d rows=%d", len(m.devFiltered), m.devTable.Cursor(), len(m.devTable.Rows()))
row, found := m.selectedDev()
t.Logf("selectedDev found=%v key=%q", found, row.key())
t.Logf("detailVisible=%v", m.detailVisible())
t.Logf("detail=%q", m.detail())
t.Logf("bodyHeight=%d sidebarCols=%d height=%d", m.bodyHeight, m.sidebarCols, m.height)
}
func fakePullTask(m Model) Model {
m.tasks.Start(task.KindPull, "pull and start PR #6612", "homarr_pr_6612", func(ctx context.Context, report *task.Reporter) error {
report.SetDetail("4/6 layers · 128.4MB/492.1MB · 12.4MB/s")
report.SetPercent(0.58)
report.SetSteps([]task.Step{
{ID: "a1b2c3d4e5f6", Label: "a1b2c3d4e5f6", Status: "Pull complete", Percent: 1, Done: true, Note: "48.2MB"},
{ID: "b2c3d4e5f6a7", Label: "b2c3d4e5f6a7", Status: "Already exists", Percent: 1, Done: true, Note: "12.1MB"},
{ID: "c3d4e5f6a7b8", Label: "c3d4e5f6a7b8", Status: "Extracting", Percent: 0.72, Note: "88.4MB/122.0MB"},
{ID: "d4e5f6a7b8c9", Label: "d4e5f6a7b8c9", Status: "Downloading", Percent: 0.21, Note: "18.2MB/86.5MB"},
{ID: "e5f6a7b8c9d0", Label: "e5f6a7b8c9d0", Status: "Waiting", Percent: 0},
})
<-ctx.Done()
return ctx.Err()
})
time.Sleep(60 * time.Millisecond)
next, _ := m.applyTasks()
next.focusTask = 1
next.sidebar.source = sourceTask
next.relayout()
next.refreshSidebar()
return next
}
func TestRenderPullProgress(t *testing.T) {
m, _ := sample()
m = fakePullTask(m)
fmt.Println("=========== PULL ===========")
fmt.Println(m.View().Content)
m.tasks.CancelAll()
}
func TestRenderManageAndConfirm(t *testing.T) {
m, _ := sample()
updated, _ := m.handleKey(tea.KeyPressMsg{Code: 'm', Text: "m"})
manage := updated.(Model)
fmt.Println("=========== MANAGE ===========")
fmt.Println(manage.View().Content)
updated, _ = manage.handleKey(tea.KeyPressMsg{Code: 'd', Text: "d"})
fmt.Println("=========== CONFIRM ===========")
fmt.Println(updated.(Model).View().Content)
}
func TestRenderTaskOverlayAndHelp(t *testing.T) {
m, _ := sample()
m = fakePullTask(m)
updated, _ := m.handleKey(tea.KeyPressMsg{Code: 't', Text: "t"})
fmt.Println("=========== TASKS ===========")
fmt.Println(updated.(Model).View().Content)
m.tasks.CancelAll()
m2, _ := sample()
updated, _ = m2.handleKey(tea.KeyPressMsg{Code: '?', Text: "?"})
fmt.Println("=========== HELP ===========")
fmt.Println(updated.(Model).View().Content)
}
func TestRenderNarrow(t *testing.T) {
m, _ := sample()
updated, _ := m.Update(tea.WindowSizeMsg{Width: 84, Height: 30})
fmt.Println("=========== NARROW (stacked sidebar) ===========")
fmt.Println(updated.(Model).View().Content)
}
func TestSidebarTaskAutoSwitchToLogsOnSuccess(t *testing.T) {
m, _ := sample()
started := m.tasks.Start(task.KindPull, "pull PR #6612", "homarr_pr_6612", func(ctx context.Context, report *task.Reporter) error {
return nil
})
next, _ := m.focusOn(started.ID(), "pull PR #6612")
if next.sidebar.source != sourceTask {
t.Fatalf("expected sidebar source to be sourceTask while task is focused, got %v", next.sidebar.source)
}
time.Sleep(50 * time.Millisecond)
next, _ = next.applyTasks()
if next.sidebar.source != sourceLogs {
t.Fatalf("expected sidebar source to auto-switch to sourceLogs on task success, got %v", next.sidebar.source)
}
if next.focusTask != 0 {
t.Fatalf("expected focusTask to reset to 0 on task success, got %d", next.focusTask)
}
}
func TestSidebarTaskAutoSwitchToLogsOnCancel(t *testing.T) {
m, _ := sample()
started := m.tasks.Start(task.KindBuild, "build homarr:dev", "homarr:dev", func(ctx context.Context, report *task.Reporter) error {
<-ctx.Done()
return ctx.Err()
})
next, _ := m.focusOn(started.ID(), "build homarr:dev")
if next.sidebar.source != sourceTask {
t.Fatalf("expected sidebar source to be sourceTask, got %v", next.sidebar.source)
}
m.tasks.Cancel(started.ID())
time.Sleep(50 * time.Millisecond)
next, _ = next.applyTasks()
if next.sidebar.source != sourceLogs {
t.Fatalf("expected sidebar source to auto-switch to sourceLogs on task cancel, got %v", next.sidebar.source)
}
}
func TestInstanceScreenActionsAndManageChords(t *testing.T) {
m, _ := sample()
next, _ := m.switchScreen(screenInstances)
if next.screen != screenInstances {
t.Fatalf("expected screenInstances, got %v", next.screen)
}
// Test manage mode entry
updated, _ := next.handleKey(tea.KeyPressMsg{Code: 'm', Text: "m"})
manage := updated.(Model)
if manage.mode != modeManage {
t.Fatalf("expected modeManage, got %v", manage.mode)
}
// Press Esc to return to normal mode
updated, _ = manage.handleKey(tea.KeyPressMsg{Code: tea.KeyEscape})
normal := updated.(Model)
if normal.mode != modeNormal {
t.Fatalf("expected modeNormal after Esc, got %v", normal.mode)
}
}
func TestSidebarRelevanceOnNavigationAndPinning(t *testing.T) {
m, _ := sample()
// Row 0 is PR 6646 (not running, no container)
if m.sidebarRelevant() {
t.Fatalf("expected sidebar to NOT be relevant for row without container")
}
// Move down to Row 1 (PR 6612, which is running)
moved, _ := m.moveSelection(1)
if !moved.sidebarRelevant() {
t.Fatalf("expected sidebar to BE relevant for running container")
}
if moved.logTarget() != "homarr_pr_6612" {
t.Fatalf("expected logTarget=homarr_pr_6612, got %q", moved.logTarget())
}
// Move down to Row 2 (PR 6503, no container)
moved2, _ := moved.moveSelection(1)
if moved2.sidebarRelevant() {
t.Fatalf("expected sidebar to NOT be relevant for row without container")
}
// Pin while on Row 1
pinned, _ := moved.togglePin()
if pinned.sidebar.pinned != "homarr_pr_6612" {
t.Fatalf("expected pinned container to be homarr_pr_6612, got %q", pinned.sidebar.pinned)
}
// Move to Row 2 while pinned -> sidebar remains relevant!
movedPinned, _ := pinned.moveSelection(1)
if !movedPinned.sidebarRelevant() {
t.Fatalf("expected sidebar to remain relevant when a valid container is pinned")
}
}
func TestSidebarTabCycleAndCIRendering(t *testing.T) {
m, _ := sample()
// Initial source is sourceLogs
if m.sidebar.source != sourceLogs {
t.Fatalf("expected sourceLogs, got %v", m.sidebar.source)
}
// Press Tab (no active tasks) -> cycles to sourceCI
tabbed, _ := m.handleKey(tea.KeyPressMsg{Code: tea.KeyTab})
mTabbed := tabbed.(Model)
if mTabbed.sidebar.source != sourceCI {
t.Fatalf("expected sourceCI after Tab, got %v", mTabbed.sidebar.source)
}
if !mTabbed.sidebarRelevant() {
t.Fatalf("expected sidebar to be relevant on PR row when in sourceCI mode")
}
// Supply mock CI checks for PR 6646
updated, _ := mTabbed.Update(ciChecksMsg{
pr: 6646,
checks: []gh.Check{
{Name: "Fast gate", Bucket: "pass", State: "SUCCESS", StartedAt: "2026-08-21T10:00:00Z", CompletedAt: "2026-08-21T10:12:00Z"},
{Name: "Build amd64", Bucket: "pass", State: "SUCCESS", StartedAt: "2026-08-21T10:12:00Z", CompletedAt: "2026-08-21T10:17:00Z"},
{Name: "E2E tests", Bucket: "pending", State: "PENDING", StartedAt: "2026-08-21T10:17:00Z"},
{Name: "publish", Bucket: "skipping", State: "SKIPPED"},
},
})
mCI := updated.(Model)
if mCI.sidebar.title != "ci · PR #6646" {
t.Fatalf("unexpected title: %q", mCI.sidebar.title)
}
if !strings.Contains(mCI.sidebar.subtitle, "2 pass") || !strings.Contains(mCI.sidebar.subtitle, "1 pending") || !strings.Contains(mCI.sidebar.subtitle, "1 skipped") {
t.Fatalf("unexpected subtitle: %q", mCI.sidebar.subtitle)
}
// Press Tab again -> cycles back to sourceLogs
tabbedAgain, _ := mCI.handleKey(tea.KeyPressMsg{Code: tea.KeyTab})
mLogs := tabbedAgain.(Model)
if mLogs.sidebar.source != sourceLogs {
t.Fatalf("expected sourceLogs after Tab, got %v", mLogs.sidebar.source)
}
}
+415
View File
@@ -0,0 +1,415 @@
package tui
import (
"fmt"
"charm.land/bubbles/v2/key"
"charm.land/bubbles/v2/table"
tea "charm.land/bubbletea/v2"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/task"
)
// handleKey routes by mode. Modes are what let one letter mean several things
// without ambiguity: `d` switches screens normally and deletes data once manage
// mode is armed, and neither reading can leak into the other.
func (m Model) handleKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
switch m.mode {
case modeFilter:
return m.handleFilterKey(msg)
case modeConfirm:
return m.handleConfirmKey(msg)
case modeImageSelect:
return m.handleImageSelectKey(msg)
case modeManage:
return m.handleManageKey(msg)
case modeHelp:
return m.handleOverlayKey(msg)
case modeTasks:
return m.handleTasksKey(msg)
default:
return m.handleNormalKey(msg)
}
}
func (m Model) handleImageSelectKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
switch {
case key.Matches(msg, m.keys.Cancel):
m.mode = modeNormal
m.imageSelection = imageSelection{}
m.status, m.statusLevel = "launch canceled", levelInfo
m.relayout()
return m, nil
case key.Matches(msg, m.keys.Up), key.Matches(msg, m.keys.Down):
if m.imageSelection.choice == imageChoiceLocal {
m.imageSelection.choice = imageChoiceRemote
} else {
m.imageSelection.choice = imageChoiceLocal
}
return m, nil
case key.Matches(msg, m.keys.Enter):
selection := m.imageSelection
row, found := m.selectedDev()
m.mode = modeNormal
m.imageSelection = imageSelection{}
if !found || row.key() != selection.rowKey {
m.status, m.statusLevel = "image selection expired; choose a row again", levelWarn
m.relayout()
return m, nil
}
m.relayout()
if selection.choice == imageChoiceRemote {
return m.deployRemotePR(row)
}
return m.startLocalPR(row)
}
return m, nil
}
func (m Model) handleNormalKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
switch {
case key.Matches(msg, m.keys.Quit):
m.tasks.CancelAll()
m.logs.Close()
return m, tea.Quit
case key.Matches(msg, m.keys.Help):
m.mode = modeHelp
m.relayout()
return m, nil
case key.Matches(msg, m.keys.Tasks):
m.mode = modeTasks
m.taskList = m.tasks.Snapshots()
m.taskCursor = max(len(m.taskList)-1, 0)
m.relayout()
return m, nil
case key.Matches(msg, m.keys.Manage):
subject, found := m.currentTarget()
if !found {
m.status, m.statusLevel = "nothing selected to manage", levelWarn
return m, nil
}
m.mode = modeManage
m.status, m.statusLevel = "manage "+subject.label, levelInfo
m.relayout()
return m, nil
case key.Matches(msg, m.keys.Filter):
m.mode = modeFilter
m.relayout()
return m, m.filter.Focus()
// A submitted filter keeps narrowing the table after the input loses focus,
// so escape has to be able to clear it from normal mode too.
case key.Matches(msg, m.keys.Cancel):
if m.filter.Value() == "" {
return m, nil
}
m.filter.Reset()
m.applyFilter()
m.relayout()
cmd := m.refreshSidebar()
m.status, m.statusLevel = "filter cleared", levelInfo
return m, cmd
case key.Matches(msg, m.keys.Refresh):
m.generation++
m.loading = true
m.status, m.statusLevel = "refreshing…", levelInfo
clocks := m.animate()
return m, tea.Batch(loadAll(m.generation, m.includeBots, true), clocks)
case key.Matches(msg, m.keys.Dev):
return m.switchScreen(screenDev)
case key.Matches(msg, m.keys.Instances):
return m.switchScreen(screenInstances)
case key.Matches(msg, m.keys.Cycle):
if m.screen == screenDev {
return m.switchScreen(screenInstances)
}
return m.switchScreen(screenDev)
case key.Matches(msg, m.keys.Sidebar):
m.sidebar.visible = !m.sidebar.visible
m.relayout()
cmd := m.refreshSidebar()
return m, cmd
case key.Matches(msg, m.keys.SidebarTab):
switch m.sidebar.source {
case sourceLogs:
if m.tasks.Running() > 0 || len(m.taskList) > 0 {
m.sidebar.source = sourceTask
} else {
m.sidebar.source = sourceCI
}
case sourceTask:
m.sidebar.source = sourceCI
case sourceCI:
m.sidebar.source = sourceLogs
default:
m.sidebar.source = sourceLogs
}
m.sidebar.visible = true
m.relayout()
cmd := m.refreshSidebar()
return m, cmd
case key.Matches(msg, m.keys.Pin):
return m.togglePin()
case key.Matches(msg, m.keys.Follow):
m.sidebar.toggleFollow()
return m, nil
case key.Matches(msg, m.keys.PageUp):
m.sidebar.pageUp()
return m, nil
case key.Matches(msg, m.keys.PageDown):
m.sidebar.pageDown()
return m, nil
case key.Matches(msg, m.keys.Enter):
return m.primaryAction()
case key.Matches(msg, m.keys.Build):
subject, found := m.currentTarget()
if !found {
return m, nil
}
return m.buildLocally(subject)
case key.Matches(msg, m.keys.Up):
return m.moveSelection(-1)
case key.Matches(msg, m.keys.Down):
return m.moveSelection(1)
case key.Matches(msg, m.keys.Top):
m.activeTable().GotoTop()
if m.tasks.Running() == 0 && m.sidebar.source == sourceTask && m.focusTask == 0 {
m.sidebar.source = sourceLogs
}
m.relayout()
cmd := m.refreshSidebar()
return m, cmd
case key.Matches(msg, m.keys.Bottom):
m.activeTable().GotoBottom()
if m.tasks.Running() == 0 && m.sidebar.source == sourceTask && m.focusTask == 0 {
m.sidebar.source = sourceLogs
}
m.relayout()
cmd := m.refreshSidebar()
return m, cmd
case key.Matches(msg, m.keys.OpenApp):
return m.openApp()
}
if m.screen == screenDev {
return m.handleDevKey(msg)
}
return m.handleInstanceKey(msg)
}
func (m Model) handleDevKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
switch {
case key.Matches(msg, m.keys.Pull):
row, found := m.selectedDev()
if !found {
return m, nil
}
return m.pullRemote(row)
case key.Matches(msg, m.keys.Demo):
m.demo = !m.demo
if m.demo {
m.status, m.statusLevel = "demo mode on — the next launch mocks integrations", levelWarn
return m, nil
}
m.status, m.statusLevel = "demo mode off", levelInfo
return m, nil
case key.Matches(msg, m.keys.Bots):
m.includeBots = !m.includeBots
m.generation++
m.loading = true
if m.includeBots {
m.status, m.statusLevel = "including bot pull requests…", levelInfo
} else {
m.status, m.statusLevel = "hiding bot pull requests…", levelInfo
}
clocks := m.animate()
return m, tea.Batch(loadAll(m.generation, m.includeBots, false), clocks)
case key.Matches(msg, m.keys.OpenPR):
return m.openPullRequest()
}
return m, nil
}
func (m Model) handleInstanceKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
row, found := m.selectedInstance()
if !found {
return m, nil
}
switch {
case key.Matches(msg, m.keys.Stop):
return m.stopContainer(row.container.Name)
case key.Matches(msg, m.keys.Restart):
return m.restartContainer(row.container.Name)
case key.Matches(msg, m.keys.Remove):
return m.arm(actionRemoveContainer, m.instanceTarget(row))
case key.Matches(msg, m.keys.Copy):
return m.copyURL()
case key.Matches(msg, m.keys.OpenPR):
if row.container.Running() && row.container.HostPort() != "" {
return m.openApp()
}
if number := row.prNumber(); number > 0 {
return m.openPullRequestNumber(number)
}
return m.openApp()
}
return m, nil
}
func (m Model) handleFilterKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
switch msg.Key().Code {
case tea.KeyEscape:
m.mode = modeNormal
m.filter.Reset()
m.filter.Blur()
m.relayout()
cmd := m.refreshSidebar()
return m, cmd
case tea.KeyEnter:
m.mode = modeNormal
m.filter.Blur()
m.relayout()
return m, nil
}
var command tea.Cmd
m.filter, command = m.filter.Update(msg)
m.applyFilter()
cmd := m.refreshSidebar()
return m, tea.Batch(command, cmd)
}
func (m Model) handleOverlayKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
if key.Matches(msg, m.keys.Quit) {
m.tasks.CancelAll()
m.logs.Close()
return m, tea.Quit
}
m.mode = modeNormal
m.relayout()
return m, nil
}
func (m Model) handleTasksKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
switch {
case key.Matches(msg, m.keys.Quit), key.Matches(msg, m.keys.Cancel), key.Matches(msg, m.keys.Tasks):
m.mode = modeNormal
m.relayout()
if key.Matches(msg, m.keys.Quit) {
m.tasks.CancelAll()
m.logs.Close()
return m, tea.Quit
}
return m, nil
case key.Matches(msg, m.keys.Up):
m.taskCursor = max(m.taskCursor-1, 0)
return m, nil
case key.Matches(msg, m.keys.Down):
m.taskCursor = min(m.taskCursor+1, max(len(m.taskList)-1, 0))
return m, nil
case key.Matches(msg, m.keys.Enter):
if snapshot, found := m.taskAt(m.taskCursor); found {
m.mode = modeNormal
return m.focusOn(snapshot.ID, snapshot.Title)
}
return m, nil
case key.Matches(msg, m.keys.Remove):
if snapshot, found := m.taskAt(m.taskCursor); found && snapshot.Cancellable {
m.tasks.Cancel(snapshot.ID)
m.status, m.statusLevel = "canceling "+snapshot.Title+"…", levelWarn
return m, nil
}
m.tasks.Prune()
m.taskList = m.tasks.Snapshots()
m.taskCursor = 0
m.status, m.statusLevel = "cleared finished tasks", levelInfo
return m, nil
}
return m, nil
}
func (m Model) taskAt(index int) (task.Snapshot, bool) {
if index < 0 || index >= len(m.taskList) {
return task.Snapshot{}, false
}
return m.taskList[index], true
}
func (m *Model) activeTable() *table.Model {
if m.screen == screenInstances {
return &m.instTable
}
return &m.devTable
}
func (m Model) moveSelection(delta int) (Model, tea.Cmd) {
if delta < 0 {
m.activeTable().MoveUp(-delta)
} else {
m.activeTable().MoveDown(delta)
}
if m.tasks.Running() == 0 && m.sidebar.source == sourceTask && m.focusTask == 0 {
m.sidebar.source = sourceLogs
}
cmd := m.refreshSidebar()
return m, cmd
}
func (m Model) switchScreen(next screen) (Model, tea.Cmd) {
if m.screen == next {
return m, nil
}
m.screen = next
if m.tasks.Running() == 0 && m.sidebar.source == sourceTask && m.focusTask == 0 {
m.sidebar.source = sourceLogs
}
m.relayout()
cmd := m.refreshSidebar()
return m, cmd
}
// togglePin locks the sidebar onto one container so the user can browse other
// rows while still watching the instance they care about.
func (m Model) togglePin() (Model, tea.Cmd) {
if m.sidebar.pinned != "" {
m.status, m.statusLevel = "unpinned "+m.sidebar.pinned, levelInfo
m.sidebar.pinned = ""
m.relayout()
cmd := m.refreshSidebar()
return m, cmd
}
name := m.logTarget()
if name == "" {
m.status, m.statusLevel = "select a container to pin its logs", levelWarn
return m, nil
}
m.sidebar.pinned = name
m.sidebar.source = sourceLogs
m.sidebar.visible = true
m.status, m.statusLevel = fmt.Sprintf("pinned logs of %s", name), levelOK
m.relayout()
cmd := m.refreshSidebar()
return m, cmd
}
+171
View File
@@ -0,0 +1,171 @@
package tui
import (
"fmt"
"charm.land/bubbles/v2/key"
tea "charm.land/bubbletea/v2"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/ui"
)
type manageAction int
const (
actionNone manageAction = iota
actionBuild
actionDeleteImage
actionDeleteData
actionRemoveContainer
actionPrune
)
// confirmation is the armed destructive action awaiting a yes or no.
type confirmation struct {
action manageAction
subject target
prompt string
detail string
}
// handleManageKey is the second half of the `m` chord. Non-destructive actions
// run immediately; anything that deletes state goes through a confirmation, so
// a mistyped chord cannot destroy an instance.
func (m Model) handleManageKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
if key.Matches(msg, m.keys.Quit) {
m.tasks.CancelAll()
m.logs.Close()
return m, tea.Quit
}
if key.Matches(msg, m.keys.ManageAbort) || key.Matches(msg, m.keys.Manage) {
m.mode = modeNormal
m.status, m.statusLevel = "manage mode closed", levelInfo
m.relayout()
return m, nil
}
subject, found := m.currentTarget()
if !found {
m.mode = modeNormal
m.relayout()
return m, nil
}
switch {
case key.Matches(msg, m.keys.ManageBuild):
m.mode = modeNormal
m.relayout()
return m.buildLocally(subject)
case key.Matches(msg, m.keys.ManageImage):
if subject.localImage == "" {
m.status, m.statusLevel = subject.label+" has no local image to delete", levelWarn
return m, nil
}
return m.arm(actionDeleteImage, subject)
case key.Matches(msg, m.keys.ManageData):
return m.arm(actionDeleteData, subject)
case key.Matches(msg, m.keys.ManageStop):
return m.arm(actionRemoveContainer, subject)
case key.Matches(msg, m.keys.ManagePrune):
return m.arm(actionPrune, subject)
}
return m, nil
}
// arm moves into the confirmation mode with a prompt describing exactly what is
// about to be destroyed.
func (m Model) arm(action manageAction, subject target) (Model, tea.Cmd) {
confirm := confirmation{action: action, subject: subject}
switch action {
case actionDeleteImage:
confirm.prompt = "Delete image " + subject.localImage + "?"
confirm.detail = "The image is removed from Docker. Rebuild it later with R."
case actionDeleteData:
confirm.prompt = "Delete data volume " + subject.volume + "?"
confirm.detail = "Boards, users and integrations in this instance are lost. The container is removed first."
if size := m.volumeSize(subject.volume); size != "" {
confirm.detail += " (" + size + " reclaimed)"
}
case actionRemoveContainer:
confirm.prompt = "Remove container " + subject.container + "?"
confirm.detail = "The container is force-removed. Its data volume is kept."
case actionPrune:
stopped := 0
for _, container := range m.containers {
if !container.Running() {
stopped++
}
}
confirm.prompt = fmt.Sprintf("Remove %d stopped Homarr containers?", stopped)
confirm.detail = "Data volumes are kept."
default:
return m, nil
}
m.confirm = confirm
m.mode = modeConfirm
// The confirmation is the only prompt that should be speaking.
m.status = ""
m.relayout()
return m, nil
}
func (m Model) volumeSize(name string) string {
for _, volume := range m.volumes {
if volume.Name == name {
return volume.Size
}
}
return ""
}
func (m Model) handleConfirmKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
switch {
case key.Matches(msg, m.keys.ManageAbort):
m.mode = modeNormal
m.confirm = confirmation{}
m.status, m.statusLevel = "canceled", levelInfo
m.relayout()
return m, nil
case key.Matches(msg, m.keys.ManageConfirm):
confirm := m.confirm
m.mode = modeNormal
m.confirm = confirmation{}
m.relayout()
switch confirm.action {
case actionDeleteImage:
return m.deleteImage(confirm.subject.localImage)
case actionDeleteData:
return m.deleteData(confirm.subject)
case actionRemoveContainer:
return m.removeContainer(confirm.subject.container)
case actionPrune:
return m.pruneStopped()
}
return m, nil
}
return m, nil
}
// manageBar is the hint strip shown while the chord is armed.
func (m Model) manageBar() string {
subject, found := m.currentTarget()
label := "selection"
if found {
label = subject.label
}
return clip(ui.ModeBadge("MANAGE", ui.Warning)+" "+
ui.Body.Render(label)+" "+
m.helpView.ShortHelpView(m.keys.ManageHelp()), m.width)
}
// confirmBar is the destructive-action prompt. It is deliberately loud.
func (m Model) confirmBar() string {
prompt := ui.ModeBadge("CONFIRM", ui.Danger) + " " + ui.Heading.Render(m.confirm.prompt)
detail := ui.Help.Render(m.confirm.detail + " y confirm · n cancel")
return clip(prompt, m.width) + "\n" + clip(detail, m.width)
}
+788
View File
@@ -0,0 +1,788 @@
package tui
import (
"fmt"
"strings"
"time"
"charm.land/bubbles/v2/help"
"charm.land/bubbles/v2/key"
"charm.land/bubbles/v2/progress"
"charm.land/bubbles/v2/spinner"
"charm.land/bubbles/v2/table"
"charm.land/bubbles/v2/textinput"
tea "charm.land/bubbletea/v2"
"charm.land/lipgloss/v2"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/docker"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/gh"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/logs"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/task"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/ui"
)
type screen int
const (
screenDev screen = iota
screenInstances
)
// mode is the interaction state. Every key press is routed by mode first, which
// is what makes chords like `m` then `i` unambiguous: the same physical key
// means different things depending on which mode armed it.
type mode int
const (
modeNormal mode = iota
modeFilter
modeManage
modeConfirm
modeImageSelect
modeHelp
modeTasks
)
type imageChoice int
const (
imageChoiceLocal imageChoice = iota
imageChoiceRemote
)
type imageSelection struct {
rowKey string
choice imageChoice
}
type statusLevel int
const (
levelInfo statusLevel = iota
levelOK
levelWarn
levelError
)
type ciCheckState struct {
loading bool
checks []gh.Check
err error
updated time.Time
}
// Model is the whole application. It owns the data, the two screens, the
// sidebar, and the background task manager; the panes are rendering concerns
// rather than separate Bubble Tea models, which keeps the message routing flat
// and means any key can act on any part of the state.
type Model struct {
keys ui.KeyMap
tasks *task.Manager
logs *logs.Registry
screen screen
mode mode
prs []gh.PR
images []docker.Image
containers []docker.Container
volumes []docker.Volume
tags map[string]bool
tagsKnown bool
devRows []devRow
devFiltered []devRow
instRows []instanceRow
instFiltered []instanceRow
devTable table.Model
instTable table.Model
filter textinput.Model
helpView help.Model
spinner spinner.Model
progress progress.Model
sidebar sidebar
ciChecks map[int]ciCheckState
taskList []task.Snapshot
taskStates map[int]task.State
taskCursor int
focusTask int
confirm confirmation
imageSelection imageSelection
includeBots bool
demo bool
loading bool
animating bool
spinning bool
generation int
status string
statusLevel statusLevel
width int
height int
bodyHeight int
sidebarCols int
sidebarStacked bool
}
// New builds the application model. showInstances picks the starting screen.
func New(showInstances bool) Model {
styles := table.DefaultStyles()
styles.Header = styles.Header.Bold(true).Foreground(ui.Muted)
styles.Selected = ui.Selected
devTable := table.New(table.WithColumns(devColumns(110)), table.WithFocused(true), table.WithHeight(16), table.WithWidth(110))
devTable.SetStyles(styles)
instTable := table.New(table.WithColumns(instanceColumns(110)), table.WithFocused(true), table.WithHeight(16), table.WithWidth(110))
instTable.SetStyles(styles)
filter := textinput.New()
filter.Prompt = "/ "
filter.Placeholder = "filter by PR, title, author, branch, image, state, port…"
filter.SetWidth(60)
filterStyles := textinput.DefaultDarkStyles()
filterStyles.Focused.Prompt = filterStyles.Focused.Prompt.Foreground(ui.Accent).Bold(true)
filterStyles.Focused.Text = filterStyles.Focused.Text.Foreground(ui.Bright)
filter.SetStyles(filterStyles)
helpModel := help.New()
helpModel.Styles = help.DefaultStyles(true)
spin := spinner.New(spinner.WithSpinner(spinner.Dot), spinner.WithStyle(lipgloss.NewStyle().Foreground(ui.Accent)))
start := screenDev
if showInstances {
start = screenInstances
}
return Model{
keys: ui.DefaultKeyMap(),
tasks: task.NewManager(),
logs: logs.NewRegistry(),
screen: start,
devTable: devTable,
instTable: instTable,
filter: filter,
helpView: helpModel,
spinner: spin,
progress: progress.New(progress.WithWidth(24), progress.WithoutPercentage(), progress.WithColors(ui.Accent)),
sidebar: newSidebar(),
ciChecks: make(map[int]ciCheckState),
taskStates: make(map[int]task.State),
loading: true,
// Init cannot persist state because it takes the model by value, so the
// clocks it arms are recorded as running here instead.
spinning: true,
animating: true,
status: "loading pull requests, images and instances…",
width: 110,
height: 34,
}
}
func (m Model) Init() tea.Cmd {
return tea.Batch(
loadAll(m.generation, m.includeBots, false),
waitForTasks(m.tasks),
waitForLogs(m.logs),
tickRefresh(),
m.spinner.Tick,
tickFrame(),
)
}
// animate arms the animation clocks that are needed and not already ticking.
// Both clocks stop themselves once nothing is in flight, so an idle CLI does no
// work at all, and because arming is centralised a handler cannot start a second
// competing tick chain. It mutates the receiver, so callers must hoist the call
// out of a `return m, m.animate()` — the order of evaluation there is not
// specified, and getting it wrong is exactly how a duplicate chain appears.
func (m *Model) animate() tea.Cmd {
if !m.busy() {
return nil
}
commands := make([]tea.Cmd, 0, 2)
if !m.spinning {
m.spinning = true
commands = append(commands, m.spinner.Tick)
}
if !m.animating {
m.animating = true
commands = append(commands, tickFrame())
}
return tea.Batch(commands...)
}
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width, m.height = msg.Width, msg.Height
m.filter.SetWidth(clampInt(msg.Width-6, 20, 72))
m.helpView.SetWidth(msg.Width)
m.relayout()
return m, nil
case loadedMsg:
if msg.generation != m.generation {
return m, nil
}
return m.applyLoaded(msg)
case containersMsg:
if msg.generation != m.generation {
return m, nil
}
sizesByName := make(map[string]string, len(m.volumes))
for _, v := range m.volumes {
if v.Size != "" {
sizesByName[v.Name] = v.Size
}
}
for i := range msg.volumes {
if msg.volumes[i].Size == "" {
msg.volumes[i].Size = sizesByName[msg.volumes[i].Name]
}
}
m.containers, m.volumes = msg.containers, msg.volumes
m.rebuildRows()
m.relayout()
cmd := m.refreshSidebar()
return m, tea.Batch(cmd, m.syncLogStreams())
case tasksChangedMsg:
return m.applyTasks()
case logsChangedMsg:
cmd := m.refreshSidebar()
return m, tea.Batch(cmd, waitForLogs(m.logs))
case ciChecksMsg:
m.ciChecks[msg.pr] = ciCheckState{
loading: false,
checks: msg.checks,
err: msg.err,
updated: time.Now(),
}
cmd := m.refreshSidebar()
for _, c := range msg.checks {
if c.IsPending() {
pollCmd := tea.Tick(6*time.Second, func(t time.Time) tea.Msg {
return pollCIChecksMsg{pr: msg.pr}
})
return m, tea.Batch(cmd, pollCmd)
}
}
return m, cmd
case pollCIChecksMsg:
if m.sidebar.source == sourceCI && m.selectedPRNumber() == msg.pr {
return m, fetchCIChecks(msg.pr, true)
}
return m, nil
case refreshMsg:
return m, tea.Batch(tickRefresh(), loadContainers(m.generation))
case frameMsg:
cmd := m.refreshSidebar()
if !m.busy() {
m.animating = false
return m, cmd
}
return m, tea.Batch(cmd, tickFrame())
case spinner.TickMsg:
if !m.busy() {
m.spinning = false
return m, nil
}
var cmd tea.Cmd
m.spinner, cmd = m.spinner.Update(msg)
return m, cmd
case statusMsg:
m.status, m.statusLevel = msg.text, msg.level
return m, nil
case progress.FrameMsg:
var cmd tea.Cmd
m.progress, cmd = m.progress.Update(msg)
return m, cmd
case tea.KeyPressMsg:
return m.handleKey(msg)
}
return m, nil
}
func (m Model) busy() bool { return m.loading || m.tasks.Running() > 0 }
// applyLoaded folds a full refresh into the model, preserving the selected row
// so a background refresh never moves the cursor under the user's hands.
func (m Model) applyLoaded(msg loadedMsg) (Model, tea.Cmd) {
m.loading = false
if msg.prErr == nil {
m.prs = msg.prs
}
if msg.imageErr == nil {
m.images = msg.images
}
if msg.tagErr == nil && msg.tags != nil {
m.tags, m.tagsKnown = msg.tags, true
}
m.containers, m.volumes = msg.containers, msg.volumes
switch {
case msg.prErr != nil && msg.imageErr != nil:
m.status, m.statusLevel = "cannot reach GitHub or Docker: "+msg.prErr.Error(), levelError
case msg.prErr != nil:
m.status, m.statusLevel = "pull requests unavailable: "+msg.prErr.Error(), levelWarn
case msg.imageErr != nil:
m.status, m.statusLevel = "local images unavailable: "+msg.imageErr.Error(), levelWarn
case msg.tagErr != nil:
m.status, m.statusLevel = "GHCR tag listing unavailable: "+msg.tagErr.Error(), levelWarn
}
m.rebuildRows()
if msg.prErr == nil && msg.imageErr == nil && msg.tagErr == nil {
m.status, m.statusLevel = m.summary(), levelInfo
}
m.relayout()
cmd := m.refreshSidebar()
return m, tea.Batch(cmd, m.syncLogStreams())
}
func (m Model) summary() string {
remote, local, running := 0, 0, 0
for _, row := range m.devRows {
if row.kind == rowLocal {
local++
} else {
remote++
if row.hasCurrentLocalImage() {
local++
}
}
if row.running {
running++
}
}
return fmt.Sprintf("%d pull requests · %d local images · %d running", remote, local, running)
}
// applyTasks reacts to background progress. Finished jobs trigger a data
// refresh so the table reflects the new image or container without the user
// having to press r.
func (m Model) applyTasks() (Model, tea.Cmd) {
m.taskList = m.tasks.Snapshots()
commands := []tea.Cmd{waitForTasks(m.tasks)}
for _, snapshot := range m.taskList {
previous, seen := m.taskStates[snapshot.ID]
if seen && previous == snapshot.State {
continue
}
m.taskStates[snapshot.ID] = snapshot.State
if !snapshot.State.Done() {
continue
}
switch snapshot.State {
case task.StateSucceeded:
m.status, m.statusLevel = snapshot.Title+" finished", levelOK
if m.sidebar.source == sourceTask && (m.focusTask == 0 || m.focusTask == snapshot.ID) {
m.sidebar.source = sourceLogs
m.focusTask = 0
}
case task.StateFailed:
m.status, m.statusLevel = snapshot.Title+" failed: "+errorText(snapshot.Err), levelError
case task.StateCanceled:
m.status, m.statusLevel = snapshot.Title+" canceled", levelWarn
if m.sidebar.source == sourceTask && (m.focusTask == 0 || m.focusTask == snapshot.ID) {
m.sidebar.source = sourceLogs
m.focusTask = 0
}
}
m.generation++
commands = append(commands, loadAll(m.generation, m.includeBots, true))
}
if m.tasks.Running() == 0 && m.sidebar.source == sourceTask && m.focusTask == 0 {
m.sidebar.source = sourceLogs
}
if focused, found := m.focusedTask(); found {
if command := m.progress.SetPercent(focused.Percent); command != nil {
commands = append(commands, command)
}
}
if clocks := m.animate(); clocks != nil {
commands = append(commands, clocks)
}
m.relayout()
if cmd := m.refreshSidebar(); cmd != nil {
commands = append(commands, cmd)
}
return m, tea.Batch(commands...)
}
func errorText(err error) string {
if err == nil {
return "unknown error"
}
return err.Error()
}
// focusedTask is the job the tray and sidebar follow: the one the user last
// started, falling back to the newest running job.
func (m Model) focusedTask() (task.Snapshot, bool) {
if m.focusTask > 0 {
if snapshot, found := m.tasks.Snapshot(m.focusTask); found {
return snapshot, true
}
}
for index := len(m.taskList) - 1; index >= 0; index-- {
if m.taskList[index].State == task.StateRunning {
return m.taskList[index], true
}
}
if len(m.taskList) > 0 {
return m.taskList[len(m.taskList)-1], true
}
return task.Snapshot{}, false
}
// rebuildRows recomputes both screens from the current data, keeping the
// selection anchored to the same logical row.
func (m *Model) rebuildRows() {
devKey := m.selectedDevKey()
instKey := m.selectedInstanceName()
m.devRows = applyContainers(buildDevRows(m.prs, m.images, m.tags, m.tagsKnown), m.containers)
m.instRows = buildInstanceRows(m.containers, m.volumes)
m.applyFilter()
m.restoreDevSelection(devKey)
m.restoreInstanceSelection(instKey)
}
func (m *Model) applyFilter() {
query := strings.ToLower(strings.TrimSpace(m.filter.Value()))
m.devFiltered = m.devFiltered[:0]
for _, row := range m.devRows {
if query == "" || strings.Contains(row.searchTerms(), query) {
m.devFiltered = append(m.devFiltered, row)
}
}
devCols := devColumns(m.tableWidth())
m.devTable.SetColumns(devCols)
m.devTable.SetRows(devTableRows(m.devFiltered, devCols))
clampCursor(&m.devTable, len(m.devFiltered))
m.instFiltered = m.instFiltered[:0]
for _, row := range m.instRows {
if query == "" || strings.Contains(row.searchTerms(), query) {
m.instFiltered = append(m.instFiltered, row)
}
}
instCols := instanceColumns(m.tableWidth())
m.instTable.SetColumns(instCols)
m.instTable.SetRows(instanceTableRows(m.instFiltered, instCols))
clampCursor(&m.instTable, len(m.instFiltered))
}
// clampCursor keeps the selection inside the row set. SetCursor clamps against
// the rows the table currently holds, so calling it while the table is empty
// parks the cursor at -1; this restores it as soon as rows exist again.
func clampCursor(model *table.Model, length int) {
if length == 0 {
return
}
if cursor := model.Cursor(); cursor < 0 || cursor >= length {
model.SetCursor(clampInt(cursor, 0, length-1))
}
}
func (m Model) selectedDevKey() string {
if row, found := m.selectedDev(); found {
return row.key()
}
return ""
}
func (m *Model) restoreDevSelection(key string) {
if key == "" {
return
}
for index, row := range m.devFiltered {
if row.key() == key {
m.devTable.SetCursor(index)
return
}
}
}
func (m Model) selectedInstanceName() string {
if row, found := m.selectedInstance(); found {
return row.container.Name
}
return ""
}
func (m *Model) restoreInstanceSelection(name string) {
if name == "" {
return
}
for index, row := range m.instFiltered {
if row.container.Name == name {
m.instTable.SetCursor(index)
return
}
}
}
func (m Model) selectedDev() (devRow, bool) {
index := m.devTable.Cursor()
if index < 0 || index >= len(m.devFiltered) {
return devRow{}, false
}
return m.devFiltered[index], true
}
func (m Model) selectedInstance() (instanceRow, bool) {
index := m.instTable.Cursor()
if index < 0 || index >= len(m.instFiltered) {
return instanceRow{}, false
}
return m.instFiltered[index], true
}
// The sidebar splits the screen side by side when there is room, and stacks
// under the table when there is not. Hiding it outright on a narrow terminal
// would make live logs unavailable exactly where they are most needed.
const sidebarSplitWidth = 96
func (m Model) tableWidth() int {
if m.sidebarCols > 0 {
return max(m.width-m.sidebarCols-1, 40)
}
return max(m.width, 40)
}
// mainHeight is the number of lines the table or an overlay may occupy.
func (m Model) mainHeight() int {
if m.sidebarStacked {
return max(m.bodyHeight-m.sidebar.height, 4)
}
return m.bodyHeight
}
func (m Model) detailVisible() bool {
if m.screen == screenInstances {
_, found := m.selectedInstance()
return found
}
_, found := m.selectedDev()
return found
}
// relayout recomputes every component's size from the terminal dimensions. The
// reserved count has to match what View actually emits line for line, or the
// bottom of the interface is pushed off screen.
func (m *Model) relayout() {
reserved := 2 // header + blank
if m.mode == modeFilter || m.filter.Value() != "" {
reserved += 2
}
if m.detailVisible() {
reserved += 3 // blank + title + meta
}
if m.tasks.Running() > 0 {
reserved += 1
}
switch m.mode {
case modeManage:
reserved += 2
case modeConfirm:
reserved += 3
case modeImageSelect:
reserved += 5
}
if m.status != "" {
reserved += 2
}
reserved += 3 // blank + two footer lines
m.bodyHeight = max(m.height-reserved, 6)
m.sidebarCols = 0
m.sidebarStacked = false
if m.sidebarRelevant() {
if m.width >= sidebarSplitWidth {
m.sidebarCols = clampInt(m.width*2/5, 34, 72)
m.sidebar.resize(m.sidebarCols, m.bodyHeight)
} else {
m.sidebarStacked = true
m.sidebar.resize(m.width, clampInt(m.bodyHeight/2, 6, 14))
}
}
// A table renders a header line plus one line per row, so its height is
// one less than the space it is given.
tableHeight := max(m.mainHeight()-1, 3)
m.devTable.SetWidth(m.tableWidth())
m.devTable.SetHeight(tableHeight)
m.instTable.SetWidth(m.tableWidth())
m.instTable.SetHeight(tableHeight)
m.applyFilter()
m.progress.SetWidth(clampInt(m.width/4, 12, 32))
}
// syncLogStreams drops followers whose container no longer exists. Attaching is
// deliberately left to refreshSidebar: following every container eagerly would
// thrash against the stream cap on a machine running more instances than the
// cap allows, killing and restarting `docker logs` every refresh.
func (m Model) syncLogStreams() tea.Cmd {
live := make([]string, 0, len(m.containers))
for _, container := range m.containers {
live = append(live, container.Name)
}
m.logs.Retain(live)
return nil
}
// refreshSidebar recomputes panel content from whichever source is selected.
func (m *Model) refreshSidebar() tea.Cmd {
if !m.sidebarRelevant() {
return nil
}
if m.sidebar.source == sourceTask {
snapshot, found := m.focusedTask()
if !found {
m.sidebar.title, m.sidebar.subtitle = "tasks", "no background work"
m.sidebar.setContent(ui.Help.Render("Press R to build locally or p to pull a pull-request image."))
return nil
}
title, subtitle, content := renderTaskSnapshot(snapshot, m.sidebar.textWidth())
m.sidebar.title, m.sidebar.subtitle = title, subtitle
m.sidebar.setContent(content)
return nil
}
if m.sidebar.source == sourceCI {
pr := m.selectedPRNumber()
state, found := m.ciChecks[pr]
var cmd tea.Cmd
if pr > 0 && (!found || (!state.loading && time.Since(state.updated) > 30*time.Second)) {
m.ciChecks[pr] = ciCheckState{loading: true, checks: state.checks, err: state.err, updated: state.updated}
cmd = fetchCIChecks(pr, false)
}
title, subtitle, content := renderCISnapshot(pr, state.checks, state.loading, state.err, m.sidebar.textWidth())
m.sidebar.title, m.sidebar.subtitle = title, subtitle
m.sidebar.setContent(content)
return cmd
}
name := m.sidebar.pinned
if name == "" {
name = m.logTarget()
}
if name == "" {
return nil
}
// Attaching here is what starts the stream, and it is a no-op once one
// exists. A stopped container is still worth following: `docker logs`
// replays why it died and then ends the stream.
m.logs.Attach(name)
snapshot, attached := m.logs.Snapshot(name)
title, subtitle, content := renderLogSnapshot(name, snapshot, attached)
if m.sidebar.pinned != "" {
subtitle = ui.IconPin + " pinned · " + subtitle
}
m.sidebar.title, m.sidebar.subtitle = title, subtitle
m.sidebar.setContent(content)
return nil
}
// logTarget is the container whose logs the sidebar shows by default.
func (m Model) logTarget() string {
if m.screen == screenInstances {
if row, found := m.selectedInstance(); found {
return row.container.Name
}
return ""
}
if row, found := m.selectedDev(); found {
if row.state != "" || row.running {
return row.containerName()
}
}
return ""
}
func (m Model) selectedPRNumber() int {
if m.screen == screenInstances {
if row, found := m.selectedInstance(); found {
return row.prNumber()
}
return 0
}
if row, found := m.selectedDev(); found {
if row.kind == rowRemote {
return row.pr.Number
}
if row.local.PRNumber > 0 {
return row.local.PRNumber
}
}
return 0
}
func (m Model) containerExists(name string) bool {
if name == "" {
return false
}
for _, c := range m.containers {
if c.Name == name {
return true
}
}
return false
}
// sidebarRelevant determines whether the right-hand panel has meaningful
// content to display (active tasks, CI checks on a PR, pinned logs, or an existing container).
func (m Model) sidebarRelevant() bool {
if !m.sidebar.visible {
return false
}
if m.sidebar.source == sourceTask {
_, found := m.focusedTask()
return found || m.tasks.Running() > 0
}
if m.sidebar.source == sourceCI {
return m.selectedPRNumber() > 0
}
if m.sidebar.pinned != "" && m.containerExists(m.sidebar.pinned) {
return true
}
return m.logTarget() != ""
}
func formatDuration(d time.Duration) string {
switch {
case d < time.Minute:
return fmt.Sprintf("%.0fs", d.Seconds())
case d < time.Hour:
return fmt.Sprintf("%dm%02ds", int(d.Minutes()), int(d.Seconds())%60)
default:
return fmt.Sprintf("%dh%02dm", int(d.Hours()), int(d.Minutes())%60)
}
}
func shortHelp(bindings []key.Binding, model help.Model) string {
return model.ShortHelpView(bindings)
}
+381
View File
@@ -0,0 +1,381 @@
package tui
import (
"fmt"
"path/filepath"
"strings"
"charm.land/bubbles/v2/table"
"charm.land/lipgloss/v2"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/docker"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/gh"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/registry"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/ui"
)
type rowKind int
const (
rowRemote rowKind = iota
rowLocal
)
// devRow is one line of the development screen: either an open pull request,
// or a local image that no open pull request accounts for.
type devRow struct {
kind rowKind
pr gh.PR
local docker.Image
image ui.ImageState
running bool
port string
state string
}
// hasCurrentLocalImage reports whether a local build matches the pull request's
// current head. Only an exact revision match counts: an image built from an
// older commit is a different thing and stays on its own row rather than
// silently shadowing the pull request.
func (r devRow) hasCurrentLocalImage() bool {
return r.kind == rowRemote && r.local.Tag != "" && r.pr.HeadSHA != "" && r.local.Revision == r.pr.HeadSHA
}
func (r devRow) containerName() string {
if r.kind == rowLocal {
return "homarr_" + r.local.Tag
}
return fmt.Sprintf("homarr_pr_%d", r.pr.Number)
}
func (r devRow) volumeName() string { return r.containerName() + "_data" }
// localReference is the local image this row would run, if one exists.
func (r devRow) localReference() string {
if r.local.Tag == "" {
return ""
}
return r.local.Reference()
}
func (r devRow) remoteReference() string {
if r.kind != rowRemote {
return ""
}
return registry.ImageReference(r.pr.Number)
}
func (r devRow) label() string {
if r.kind == rowLocal {
return r.local.Reference()
}
return fmt.Sprintf("PR #%d", r.pr.Number)
}
func (r devRow) key() string {
if r.kind == rowLocal {
return "local:" + r.local.Tag
}
return fmt.Sprintf("pr:%d", r.pr.Number)
}
// searchTerms is everything the filter matches against for this row.
func (r devRow) searchTerms() string {
terms := []string{
r.pr.Title, r.pr.Author, r.pr.HeadRef, r.pr.CIState,
r.local.Tag, r.local.Source, r.local.Revision, r.port,
}
if r.kind == rowRemote {
terms = append(terms, "remote", fmt.Sprint(r.pr.Number), fmt.Sprintf("#%d pr-%d", r.pr.Number, r.pr.Number))
if r.pr.IsDraft {
terms = append(terms, "draft")
}
} else {
terms = append(terms, "local", r.local.Reference())
}
if r.hasCurrentLocalImage() {
terms = append(terms, "local built")
}
if r.running {
terms = append(terms, "running started up")
}
return strings.ToLower(strings.Join(terms, " "))
}
// buildDevRows merges open pull requests with local images into a single list.
// A local image folds into its pull request only when the revisions match, so
// the row exposes both sources when the registry image is available too.
func buildDevRows(prs []gh.PR, images []docker.Image, tags map[string]bool, tagsKnown bool) []devRow {
rows := make([]devRow, 0, len(prs)+len(images))
indexByPR := make(map[int]int, len(prs))
for _, pr := range prs {
indexByPR[pr.Number] = len(rows)
rows = append(rows, devRow{kind: rowRemote, pr: pr})
}
for _, image := range images {
index, matched := indexByPR[image.PRNumber]
if matched && image.Revision != "" && image.Revision == rows[index].pr.HeadSHA {
if rows[index].local.Tag == "" {
rows[index].local = image
continue
}
}
rows = append(rows, devRow{kind: rowLocal, local: image, image: ui.ImageLocal})
}
for index := range rows {
if rows[index].kind != rowRemote {
continue
}
switch {
case rows[index].hasCurrentLocalImage():
rows[index].image = ui.ImageLocal
case rows[index].local.Tag != "":
rows[index].image = ui.ImageStale
case !tagsKnown:
rows[index].image = ui.ImageChecking
case registry.HasPRImage(tags, rows[index].pr.Number):
rows[index].image = ui.ImageRemote
default:
rows[index].image = ui.ImageMissing
}
}
return rows
}
// applyContainers annotates rows with the state of their container.
func applyContainers(rows []devRow, containers []docker.Container) []devRow {
byName := make(map[string]docker.Container, len(containers))
for _, container := range containers {
byName[container.Name] = container
}
for index := range rows {
container, found := byName[rows[index].containerName()]
rows[index].running = found && container.Running()
rows[index].state = ""
rows[index].port = ""
if found {
rows[index].state = container.State
rows[index].port = container.HostPort()
}
}
return rows
}
// flexWidth hands the leftover table width to one column. Every visible column
// costs its own width plus the two padding cells the table adds, and columns set
// to zero are skipped entirely, which is how the narrow layouts drop them.
func flexWidth(columns []table.Column, available, index, minimum int) int {
used := 0
for position, column := range columns {
if position == index || column.Width <= 0 {
continue
}
used += column.Width + 2
}
return max(available-used-2, minimum)
}
func devColumns(width int) []table.Column {
author, port := 15, 6
switch {
case width < 68:
author, port = 0, 0
case width < 92:
author = 0
case width < 108:
author = 10
}
columns := []table.Column{
{Title: "", Width: 1},
{Title: "SOURCE", Width: 6},
{Title: "REF", Width: 9},
{Title: "TITLE", Width: 0},
{Title: "AUTHOR", Width: author},
{Title: "IMG", Width: 3},
{Title: "CI", Width: 2},
{Title: "PORT", Width: port},
}
columns[3].Width = flexWidth(columns, width, 3, 18)
return columns
}
func devTableRows(rows []devRow, columns []table.Column) []table.Row {
titleWidth, authorWidth := columns[3].Width, columns[4].Width
rendered := make([]table.Row, 0, len(rows))
for _, row := range rows {
marker := " "
switch {
case row.running:
marker = ui.OK.Render(ui.IconRunning)
case row.state != "":
marker = ui.Dim.Render(ui.IconStopped)
}
// Cells are truncated as plain text and styled afterwards. Styling
// first would leave the table cutting through an escape sequence,
// because it measures width in bytes it cannot interpret.
source, reference, title, author := "remote", fmt.Sprint(row.pr.Number), row.pr.Title, row.pr.Author
ci := ui.CIBadge(row.pr.CIState, false)
draft := false
if row.kind == rowLocal {
source, reference, title = "local", row.local.Tag, row.local.Reference()
ci = ui.CIBadge("", false)
author = "untracked"
if row.local.Source != "" {
author = filepath.Base(row.local.Source)
}
} else if row.pr.IsDraft {
title, draft = "DRAFT · "+title, true
}
styledSource := ui.Dim.Render(source)
if row.kind == rowLocal {
styledSource = ui.Local.Render(source)
}
styledTitle := ui.Truncate(title, titleWidth)
if draft {
styledTitle = ui.Dim.Render(styledTitle)
}
port := ""
if row.port != "" {
port = ui.OK.Render(":" + row.port)
}
rendered = append(rendered, table.Row{
marker,
styledSource,
ui.Truncate(reference, columns[2].Width),
styledTitle,
ui.Help.Render(ui.Truncate(author, authorWidth)),
ui.ImageBadge(row.image, false),
ci,
port,
})
}
return rendered
}
// instanceRow is one line of the instances screen.
type instanceRow struct {
container docker.Container
volume string
health string
}
func (r instanceRow) prNumber() int {
var number int
if _, err := fmt.Sscanf(r.container.Name, "homarr_pr_%d", &number); err == nil {
return number
}
return 0
}
func (r instanceRow) url() string {
if !r.container.Running() || r.container.HostPort() == "" {
return ""
}
return "http://localhost:" + r.container.HostPort()
}
func (r instanceRow) searchTerms() string {
return strings.ToLower(strings.Join([]string{
r.container.Name, r.container.Image, r.container.State,
r.container.Status, r.container.HostPort(), r.health, r.url(),
}, " "))
}
var healthStatusMap = map[string]string{
"healthy": "healthy",
"unhealthy": "unhealthy",
"health: starting": "starting",
}
// parseHealth pulls the healthcheck verdict out of the status string Docker
// renders, for example "Up 3 minutes (healthy)".
func parseHealth(status string) string {
open := strings.Index(status, "(")
close := strings.LastIndex(status, ")")
if open < 0 || close <= open {
return ""
}
return healthStatusMap[status[open+1:close]]
}
func buildInstanceRows(containers []docker.Container, volumes []docker.Volume) []instanceRow {
byName := make(map[string]docker.Volume, len(volumes))
for _, volume := range volumes {
byName[volume.Name] = volume
}
rows := make([]instanceRow, 0, len(containers))
for _, container := range containers {
row := instanceRow{container: container, health: parseHealth(container.Status)}
if volume, found := byName[container.Name+"_data"]; found {
row.volume = volume.Name
}
rows = append(rows, row)
}
return rows
}
func instanceColumns(width int) []table.Column {
image, status := 24, 22
switch {
case width < 72:
image, status = 14, 0
case width < 100:
image, status = 18, 0
case width < 124:
status = 16
}
columns := []table.Column{
{Title: "", Width: 1},
{Title: "NAME", Width: 0},
{Title: "STATE", Width: 10},
{Title: "IMAGE", Width: image},
{Title: "PORT", Width: 6},
{Title: "STATUS", Width: status},
}
columns[1].Width = flexWidth(columns, width, 1, 16)
return columns
}
func instanceTableRows(rows []instanceRow, columns []table.Column) []table.Row {
nameWidth, imageWidth, statusWidth := columns[1].Width, columns[3].Width, columns[5].Width
rendered := make([]table.Row, 0, len(rows))
for _, row := range rows {
marker := ui.Dim.Render(ui.IconStopped)
if row.container.Running() {
marker = ui.OK.Render(ui.IconRunning)
}
port := ""
if value := row.container.HostPort(); value != "" {
port = ui.OK.Render(":" + value)
}
image := strings.TrimPrefix(row.container.Image, "ghcr.io/homarr-labs/")
rendered = append(rendered, table.Row{
marker,
ui.Body.Render(ui.Truncate(row.container.Name, nameWidth)),
ui.StateBadge(row.container.State),
ui.Help.Render(ui.Truncate(image, imageWidth)),
port,
prefixed(ui.HealthBadge(row.health), row.container.Status, statusWidth),
})
}
return rendered
}
// prefixed puts a rendered badge in front of plain text, truncating the text to
// whatever width the badge leaves behind.
func prefixed(badge, text string, width int) string {
if width <= 0 {
return ""
}
if badge == "" {
return ui.Help.Render(ui.Truncate(text, width))
}
remaining := width - lipgloss.Width(badge) - 1
if remaining <= 0 {
return badge
}
return badge + " " + ui.Help.Render(ui.Truncate(text, remaining))
}
+25
View File
@@ -0,0 +1,25 @@
package tui
import tea "charm.land/bubbletea/v2"
// Run starts the interactive application. showInstances opens directly on the
// instances screen instead of the development browser.
func Run(showInstances bool) error {
model := New(showInstances)
program := tea.NewProgram(model)
final, err := program.Run()
// Background work outlives the render loop unless it is stopped here, and a
// stray `docker logs --follow` would keep the terminal's child process alive
// after the CLI has exited.
if quit, ok := final.(Model); ok {
quit.tasks.CancelAll()
quit.logs.Close()
}
return err
}
// RunDev opens the development browser.
func RunDev() error { return Run(false) }
// RunDashboard opens the instances screen.
func RunDashboard() error { return Run(true) }
+382
View File
@@ -0,0 +1,382 @@
package tui
import (
"fmt"
"strings"
"charm.land/bubbles/v2/viewport"
"charm.land/lipgloss/v2"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/gh"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/logs"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/task"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/ui"
)
type sidebarSource int
const (
// sourceLogs follows the selected (or pinned) container.
sourceLogs sidebarSource = iota
// sourceTask follows a background pull or build.
sourceTask
// sourceCI follows the GitHub CI checks for the selected PR.
sourceCI
)
var sidebarTabNames = map[sidebarSource]string{
sourceLogs: "logs",
sourceTask: "build",
sourceCI: "ci",
}
var tabOrder = []sidebarSource{sourceLogs, sourceTask, sourceCI}
// sidebar is the right-hand panel. It has two jobs — live container output and
// live build output — and both are just text, so one scrollable viewport backs
// them and the source switch only changes what fills it.
type sidebar struct {
visible bool
source sidebarSource
viewport viewport.Model
follow bool
pinned string
taskID int
width int
height int
title string
subtitle string
}
func newSidebar() sidebar {
view := viewport.New(viewport.WithWidth(40), viewport.WithHeight(10))
view.SoftWrap = true
view.Style = lipgloss.NewStyle().Foreground(ui.Text)
return sidebar{visible: true, follow: true, viewport: view, width: 40, height: 10}
}
// resize sets the panel's outer dimensions; the viewport is inset for the
// border and the two header lines.
// resize sets the panel's outer size in terminal cells. In Lip Gloss v2 a
// style's Width includes its border, so the text inside loses two columns to
// the border and two more to the horizontal padding. Vertically the border
// costs two rows and the title and subtitle one each.
func (s *sidebar) resize(width, height int) {
s.width, s.height = width, height
s.viewport.SetWidth(s.textWidth())
s.viewport.SetHeight(max(height-4, 3))
}
// textWidth is the usable width inside the border and padding. Content wider
// than this soft-wraps, which turns a progress list into a ragged mess, so
// every renderer budgets against it.
func (s sidebar) textWidth() int { return max(s.width-4, 10) }
func (s *sidebar) setContent(content string) {
atBottom := s.viewport.AtBottom()
s.viewport.SetContent(content)
if s.follow || atBottom {
s.viewport.GotoBottom()
}
}
func (s *sidebar) toggleFollow() {
s.follow = !s.follow
if s.follow {
s.viewport.GotoBottom()
}
}
func (s *sidebar) pageUp() {
s.follow = false
s.viewport.PageUp()
}
func (s *sidebar) pageDown() {
s.viewport.PageDown()
s.follow = s.viewport.AtBottom()
}
// view renders the panel, or nothing when it is hidden.
func (s sidebar) view() string {
if !s.visible || s.width < 24 {
return ""
}
text := s.textWidth()
header := ui.Heading.Render(ui.Truncate(s.title, text))
mode := "paused"
if s.follow {
mode = "following"
}
subtitle := s.subtitle
if subtitle == "" {
subtitle = mode
} else {
subtitle += " · " + mode
}
body := lipgloss.JoinVertical(lipgloss.Left,
header,
ui.Help.Render(ui.Truncate(subtitle, text)),
s.viewport.View(),
)
return ui.Panel("", s.source == sourceTask).Width(s.width).Height(s.height - 2).Render(body)
}
var logStateLabels = map[logs.State]string{
logs.StateStarting: "attaching",
logs.StateStopped: "stream ended",
logs.StateFailed: "stream failed",
}
// renderLogSnapshot turns a live log buffer into panel content.
func renderLogSnapshot(name string, snapshot logs.Snapshot, attached bool) (title, subtitle, content string) {
title = ui.IconTerminal + " " + name
if name == "" {
return ui.IconTerminal + " logs", "no container selected", ui.Help.Render("Select a running instance to stream its logs.")
}
if !attached {
return title, "not streaming", ui.Help.Render("Container is not running.")
}
if snapshot.State == logs.StateStreaming {
subtitle = fmt.Sprintf("%d lines", len(snapshot.Lines))
} else if label, found := logStateLabels[snapshot.State]; found {
subtitle = label
}
content = tailLines(snapshot.Lines, len(snapshot.Lines))
if snapshot.Err != nil {
content += "\n" + ui.Alert.Render(snapshot.Err.Error())
}
if strings.TrimSpace(content) == "" {
content = ui.Help.Render("waiting for output…")
}
return title, subtitle, content
}
var taskKindIcons = map[task.Kind]string{
task.KindBuild: ui.IconBuild,
task.KindPull: ui.IconCloud,
}
// renderTaskSnapshot lays out a background job: a progress bar per unit of
// work, then the tail of its output. This is the panel that answers "what is my
// build doing right now" without leaving the interface.
func renderTaskSnapshot(snapshot task.Snapshot, width int) (title, subtitle, content string) {
kindIcon := taskKindIcons[snapshot.Kind]
if kindIcon == "" {
kindIcon = ui.IconBuild
}
title = kindIcon + " " + snapshot.Kind.String() + " · " + snapshot.Target
subtitle = snapshot.State.String()
if snapshot.Detail != "" {
subtitle += " · " + snapshot.Detail
}
subtitle += fmt.Sprintf(" · %s", formatDuration(snapshot.Elapsed()))
var out strings.Builder
labelWidth := stepLabelWidth(snapshot.Steps, width)
for _, step := range snapshot.Steps {
out.WriteString(renderStep(step, labelWidth, width))
out.WriteString("\n")
}
if snapshot.Kind == task.KindBuild {
if tail := tailLines(snapshot.Lines, 60); tail != "" {
if out.Len() > 0 {
out.WriteString(ui.Rule("output", width) + "\n")
}
// Left unstyled so the build tool's own colours survive.
out.WriteString(tail + "\n")
}
}
if snapshot.Err != nil {
out.WriteString("\n" + ui.Alert.Render(snapshot.Err.Error()))
}
if strings.TrimSpace(out.String()) == "" {
out.WriteString(ui.Help.Render("starting…"))
}
return title, subtitle, out.String()
}
// renderStep lays out one progress row inside an exact width. The panel wraps
// long lines, which would turn a layer list into a ragged mess, so each row is
// budgeted rather than trimmed after the fact.
// stepLabelWidth sizes the label column to the widest label, so a pull of
// twelve-character layer IDs does not leave a gap the width of a Dockerfile
// instruction.
func stepLabelWidth(steps []task.Step, width int) int {
longest := 0
for _, step := range steps {
longest = max(longest, lipgloss.Width(step.Label))
}
bar := clampInt(width/3, 6, 22)
available := max(width-bar-stepFixedWidth-8, 8)
return clampInt(longest, 8, available)
}
func renderStep(step task.Step, labelWidth, width int) string {
icon := ui.Pending.Render(ui.IconPending)
switch {
case step.Failed:
icon = ui.Alert.Render(ui.IconFail)
case step.Done:
icon = ui.OK.Render(ui.IconPass)
}
colour := ui.Warning
if step.Done {
colour = ui.Success
}
note := step.Note
if note == "" {
note = strings.ToLower(step.Status)
}
bar := clampInt(width/3, 6, 22)
noteWidth := max(width-bar-labelWidth-stepFixedWidth, 0)
rendered := fmt.Sprintf("%s %-*s %s %s",
icon,
labelWidth, ui.Truncate(step.Label, labelWidth),
ui.Bar(step.Percent, bar, colour),
ui.Percent(step.Percent),
)
if noteWidth > 1 && note != "" {
rendered += " " + ui.Help.Render(ui.Truncate(note, noteWidth-1))
}
return rendered
}
// stepFixedWidth is the icon, the percentage, and the three separating spaces.
const stepFixedWidth = 1 + 4 + 3
// tailLines keeps the last count meaningful lines of output.
func tailLines(lines []string, count int) string {
kept := make([]string, 0, min(len(lines), count))
for _, line := range lines {
if !ui.Blank(line) {
kept = append(kept, line)
}
}
if len(kept) > count {
kept = kept[len(kept)-count:]
}
return strings.Join(kept, "\n")
}
func clampInt(value, low, high int) int {
if value < low {
return low
}
if value > high {
return high
}
return value
}
type checkGlyphSpec struct {
symbol string
style lipgloss.Style
}
var checkGlyphs = map[string]checkGlyphSpec{
"pass": {ui.IconPass, ui.OK},
"fail": {ui.IconFail, ui.Alert},
"pending": {ui.IconPending, ui.Pending},
"skipping": {ui.IconStopped, ui.Dim},
"cancel": {ui.IconFail, ui.Dim},
}
func renderCheckLine(c gh.Check, width int) string {
spec, found := checkGlyphs[c.BucketKey()]
if !found {
spec = checkGlyphs["pending"]
}
icon := spec.style.Render(spec.symbol)
dur := c.Duration()
durStyle := ui.Dim
if dur == "" {
if c.IsSkipped() {
dur = "skipped"
} else if c.IsPending() {
dur = "running"
durStyle = ui.Pending
} else if c.IsFailure() {
dur = "failed"
durStyle = ui.Alert
} else {
dur = "—"
}
} else if c.IsFailure() {
durStyle = ui.Alert
} else if c.IsPending() {
durStyle = ui.Pending
}
styledDur := durStyle.Render(dur)
durLen := lipgloss.Width(styledDur)
name := c.Name
if c.Workflow != "" && c.Workflow != c.Name && c.Workflow != "CI" {
name += " " + ui.Dim.Render("("+c.Workflow+")")
}
maxNameWidth := max(width-durLen-4, 10)
styledName := ui.Truncate(name, maxNameWidth)
padding := max(width-lipgloss.Width(icon)-1-lipgloss.Width(styledName)-durLen, 1)
line := icon + " " + styledName + strings.Repeat(" ", padding) + styledDur
if c.Description != "" {
line += "\n " + ui.Help.Render(ui.Truncate(c.Description, max(width-6, 10)))
}
return line
}
func renderCISnapshot(pr int, checks []gh.Check, loading bool, err error, width int) (title, subtitle, content string) {
if pr <= 0 {
return "ci", "no PR selected", ui.Help.Render("Select a pull request to inspect its CI checks.")
}
title = fmt.Sprintf("ci · PR #%d", pr)
if loading && len(checks) == 0 {
return title, "fetching…", ui.Help.Render("Fetching CI checks from GitHub…")
}
if err != nil && len(checks) == 0 {
return title, "error", ui.Alert.Render(err.Error()) + "\n\n" + ui.Help.Render("Check `gh auth status` and internet connection.")
}
if len(checks) == 0 {
return title, "no checks", ui.Help.Render("No CI checks reported for this pull request.")
}
pass, fail, pending, skipping := 0, 0, 0, 0
for _, c := range checks {
switch {
case c.IsSuccess():
pass++
case c.IsFailure():
fail++
case c.IsPending():
pending++
default:
skipping++
}
}
var parts []string
if pass > 0 {
parts = append(parts, fmt.Sprintf("%s %d pass", ui.IconPass, pass))
}
if fail > 0 {
parts = append(parts, fmt.Sprintf("%s %d fail", ui.IconFail, fail))
}
if pending > 0 {
parts = append(parts, fmt.Sprintf("%s %d pending", ui.IconPending, pending))
}
if skipping > 0 {
parts = append(parts, fmt.Sprintf("%s %d skipped", ui.IconStopped, skipping))
}
subtitle = strings.Join(parts, " · ")
var out strings.Builder
for _, c := range checks {
out.WriteString(renderCheckLine(c, width))
out.WriteString("\n")
}
return title, subtitle, strings.TrimRight(out.String(), "\n")
}
+384
View File
@@ -0,0 +1,384 @@
package tui
import (
"fmt"
"strings"
tea "charm.land/bubbletea/v2"
"charm.land/lipgloss/v2"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/task"
"github.com/homarr-labs/homarr/tools/homarr-dev/internal/ui"
)
func (m Model) View() tea.View {
sections := []string{m.header(), ""}
if m.mode == modeFilter || m.filter.Value() != "" {
sections = append(sections, m.filter.View(), "")
}
sections = append(sections, m.body())
if detail := m.detail(); detail != "" {
sections = append(sections, "", detail)
}
if tray := m.taskTray(); tray != "" {
sections = append(sections, tray)
}
switch m.mode {
case modeManage:
sections = append(sections, "", m.manageBar())
case modeConfirm:
sections = append(sections, "", m.confirmBar())
case modeImageSelect:
sections = append(sections, "", m.imageSelectBar())
}
if m.status != "" {
sections = append(sections, "", m.statusView())
}
sections = append(sections, "", m.footer())
view := tea.NewView(strings.Join(sections, "\n"))
view.AltScreen = true
view.WindowTitle = ui.IconDocker + " Homarr"
return view
}
func (m Model) header() string {
title := ui.IconDocker + " homarr"
screen := "development"
if m.screen == screenInstances {
screen = "instances"
}
header := ui.Title.Render(title) + ui.Dim.Render(" · ") + ui.Heading.Render(screen)
if m.busy() {
header += " " + m.spinner.View()
}
badges := make([]string, 0, 4)
if m.screen == screenDev {
remote, local, running := 0, 0, 0
for _, row := range m.devRows {
if row.kind == rowLocal {
local++
} else {
remote++
if row.hasCurrentLocalImage() {
local++
}
}
if row.running {
running++
}
}
badges = append(badges, ui.Help.Render(fmt.Sprintf("%s %d PRs · %s %d local · %s %d running · %s %d shown", ui.IconPR, remote, ui.IconLocal, local, ui.IconRunning, running, ui.IconSearch, len(m.devFiltered))))
} else {
running := 0
for _, row := range m.instRows {
if row.container.Running() {
running++
}
}
badges = append(badges, ui.Help.Render(fmt.Sprintf("%s %d instances · %s %d running · %s %d shown", ui.IconDocker, len(m.instRows), ui.IconRunning, running, ui.IconSearch, len(m.instFiltered))))
}
if m.demo {
badges = append(badges, ui.ModeBadge("DEMO", ui.Warning))
}
if running := m.tasks.Running(); running > 0 {
badges = append(badges, ui.Pending.Render(fmt.Sprintf("%s %d working", ui.IconBuild, running)))
}
if !m.includeBots && m.screen == screenDev {
badges = append(badges, ui.Dim.Render("bots hidden"))
}
return clip(header+" "+strings.Join(badges, ui.Dim.Render(" · ")), m.width)
}
// clip trims a rendered line to the terminal width. The line already carries
// styling, so it is measured and cut by display width rather than by bytes.
func clip(line string, width int) string {
if width <= 0 || lipgloss.Width(line) <= width {
return line
}
return lipgloss.NewStyle().MaxWidth(width).Render(line)
}
// body joins the active screen with the sidebar. Overlays replace the table but
// keep the sidebar, so a build stays visible while the help is open.
func (m Model) body() string {
main := m.mainPane()
if !m.sidebarRelevant() {
return main
}
panel := m.sidebar.view()
if panel == "" {
return main
}
if m.sidebarStacked {
return main + "\n" + panel
}
return lipgloss.JoinHorizontal(lipgloss.Top, main, " ", panel)
}
func (m Model) mainPane() string {
width := m.tableWidth()
switch m.mode {
case modeHelp:
return m.helpOverlay(width)
case modeTasks:
return m.taskOverlay(width)
}
if m.screen == screenInstances {
if len(m.instFiltered) == 0 {
return m.emptyPane(width, len(m.instRows) > 0,
"no Homarr instances — press enter on a pull request to start one")
}
return m.instTable.View()
}
if len(m.devFiltered) == 0 {
return m.emptyPane(width, len(m.devRows) > 0,
"nothing to show — check `gh auth status` and that Docker is running")
}
return m.devTable.View()
}
func (m Model) emptyPane(width int, filtered bool, message string) string {
if filtered {
message = "nothing matches " + m.filter.Value()
}
block := lipgloss.NewStyle().Width(width).Height(m.mainHeight()).Padding(1, 2)
return block.Render(ui.Help.Render(message))
}
func (m Model) helpOverlay(width int) string {
body := lipgloss.JoinVertical(lipgloss.Left,
ui.Heading.Render("Keys"),
"",
m.helpView.FullHelpView(m.keys.FullHelp()),
"",
ui.Heading.Render("Manage mode"),
ui.Help.Render("m arms manage mode for the selected row, then:"),
m.helpView.ShortHelpView(m.keys.ManageHelp()),
"",
ui.Heading.Render("Legend"),
ui.Help.Render("CI "+ui.CIBadge("SUCCESS", true)+" "+ui.CIBadge("FAILURE", true)+" "+ui.CIBadge("PENDING", true)+" "+ui.CIBadge("", true)),
ui.Help.Render("IMAGE "+ui.ImageBadge(ui.ImageLocal, true)+" "+ui.ImageBadge(ui.ImageStale, true)+" "+ui.ImageBadge(ui.ImageRemote, true)+" "+ui.ImageBadge(ui.ImageMissing, true)),
ui.Help.Render("STATE "+ui.RunningBadge(true, "7575")+" "+ui.StateBadge("exited")+" "+ui.HealthBadge("healthy")),
"",
ui.Help.Render("press any key to close"),
)
return lipgloss.NewStyle().Width(width).Height(m.mainHeight()).Padding(0, 1).Render(body)
}
// taskOverlay lists background work with per-job progress, so a user who
// started three builds can see all of them without cycling the sidebar.
func (m Model) taskOverlay(width int) string {
if len(m.taskList) == 0 {
return m.emptyPane(width, false, "no background tasks yet — R builds locally, p pulls a pull-request image")
}
lines := []string{ui.Heading.Render(ui.IconBuild + " Background tasks"), ""}
barWidth := clampInt(width/4, 10, 26)
for index, snapshot := range m.taskList {
cursor := " "
if index == m.taskCursor {
cursor = ui.Local.Render("▸ ")
}
colour := ui.Warning
switch snapshot.State {
case task.StateSucceeded:
colour = ui.Success
case task.StateFailed:
colour = ui.Danger
case task.StateCanceled:
colour = ui.Faint
}
line := fmt.Sprintf("%s%s %s %s %s",
cursor,
ui.TaskBadge(snapshot.State.String(), snapshot.Kind.String()),
ui.Bar(snapshot.Percent, barWidth, colour),
ui.Percent(snapshot.Percent),
ui.Body.Render(ui.Truncate(snapshot.Title, max(width-barWidth-30, 12))),
)
lines = append(lines, line)
detail := snapshot.Detail
if snapshot.Err != nil {
detail = snapshot.Err.Error()
}
if detail != "" {
lines = append(lines, ui.Help.Render(" "+ui.Truncate(detail, max(width-8, 20))+" · "+formatDuration(snapshot.Elapsed())))
}
}
lines = append(lines, "", ui.Help.Render("enter watch · x cancel or clear · esc close"))
return lipgloss.NewStyle().Width(width).Height(m.mainHeight()).Padding(0, 1).Render(strings.Join(lines, "\n"))
}
// detail describes the selected row in full, including the things that are too
// wide for a table cell: branch, provenance, and the image source Enter can run.
func (m Model) detail() string {
if m.screen == screenInstances {
row, found := m.selectedInstance()
if !found {
return ""
}
meta := []string{
ui.StateBadge(row.container.State),
ui.Dim.Render(row.container.Image),
}
if health := ui.HealthBadge(row.health); health != "" {
meta = append(meta, health)
}
if url := row.url(); url != "" {
meta = append(meta, ui.OK.Render(ui.IconPort+" "+url))
}
if row.volume != "" {
meta = append(meta, ui.Help.Render(ui.IconData+" "+row.volume))
}
meta = append(meta, ui.Help.Render(row.container.Status))
return clip(ui.Heading.Render(ui.IconDocker+" "+row.container.Name), m.width) + "\n" +
clip(strings.Join(meta, ui.Dim.Render(" · ")), m.width)
}
row, found := m.selectedDev()
if !found {
return ""
}
if row.kind == rowLocal {
meta := []string{ui.Local.Render(ui.IconLocal + " local image")}
if row.local.Size != "" {
meta = append(meta, ui.Help.Render(row.local.Size))
}
if row.local.Created != "" {
meta = append(meta, ui.Help.Render(row.local.Created))
}
if row.local.Source != "" {
meta = append(meta, ui.Help.Render(row.local.Source))
} else {
meta = append(meta, ui.Pending.Render("no provenance · rebuild unavailable"))
}
if row.local.Revision != "" {
meta = append(meta, ui.Dim.Render(ui.IconBranch+" "+truncateRevision(row.local.Revision)))
}
if row.local.PRNumber > 0 {
meta = append(meta, ui.Help.Render(fmt.Sprintf("%s PR #%d", ui.IconPR, row.local.PRNumber)))
}
meta = append(meta, ui.RunningBadge(row.running, row.port))
return clip(ui.Heading.Render(ui.IconLocal+" "+row.local.Reference()), m.width) + "\n" +
clip(strings.Join(meta, ui.Dim.Render(" · ")), m.width)
}
branch := row.pr.HeadRef
if branch == "" {
branch = "unknown branch"
}
meta := []string{
ui.Help.Render(ui.IconUser + " @" + row.pr.Author),
ui.Dim.Render(ui.IconBranch + " " + branch),
ui.CIBadge(row.pr.CIState, true),
ui.ImageBadge(row.image, true),
}
switch {
case row.running:
meta = append(meta, ui.Help.Render("enter stops it"))
case row.hasCurrentLocalImage() && m.remoteImageAvailable(row):
meta = append(meta, ui.Help.Render("enter chooses local or remote"))
case row.hasCurrentLocalImage():
meta = append(meta, ui.Local.Render("enter runs "+row.localReference()))
case row.image == ui.ImageRemote:
meta = append(meta, ui.Help.Render("enter pulls "+remoteImageFor(row)))
case row.image == ui.ImageStale:
meta = append(meta, ui.Pending.Render(row.localReference()+" is behind the head commit"))
case row.image == ui.ImageMissing:
meta = append(meta, ui.Pending.Render("R builds it locally"))
}
meta = append(meta, ui.RunningBadge(row.running, row.port))
title := fmt.Sprintf("%s #%d %s", ui.IconPR, row.pr.Number, row.pr.Title)
return clip(ui.Heading.Render(ui.Truncate(title, max(m.width-2, 20))), m.width) + "\n" +
clip(strings.Join(meta, ui.Dim.Render(" · ")), m.width)
}
func (m Model) imageSelectBar() string {
row, found := m.selectedDev()
if !found {
return ui.Help.Render("image selection is no longer available")
}
title := fmt.Sprintf("%s choose image for PR #%d", ui.IconDocker, row.pr.Number)
local := m.imageChoiceLine(imageChoiceLocal, ui.IconLocal+" local", row.localReference())
remote := m.imageChoiceLine(imageChoiceRemote, ui.IconCloud+" remote", remoteImageFor(row))
hint := ui.Help.Render("↑/↓ choose · enter start · esc cancel")
return strings.Join([]string{ui.Heading.Render(title), local, remote, hint}, "\n")
}
func (m Model) imageChoiceLine(choice imageChoice, label, reference string) string {
marker := " "
style := ui.Help
if m.imageSelection.choice == choice {
marker = "▸ "
style = ui.Selected
}
return style.Render(ui.Truncate(marker+label+" "+reference, max(m.width-2, 20)))
}
// taskTray is the always-visible one-liner for the job being followed. It uses
// the springy bubbles progress bar because a single headline bar reads better
// when it eases towards its target.
func (m Model) taskTray() string {
if m.tasks.Running() == 0 {
return ""
}
snapshot, found := m.focusedTask()
if !found {
return ""
}
detail := snapshot.Detail
if detail == "" {
detail = snapshot.State.String()
}
title := ui.Truncate(snapshot.Title, clampInt(m.width/3, 12, 40))
head := fmt.Sprintf("%s %s %s %s",
ui.Pending.Render(m.spinner.View()),
ui.Body.Render(title),
m.progress.View(),
ui.Pending.Render(ui.Percent(snapshot.Percent)),
)
remaining := m.width - lipgloss.Width(head) - 1
if remaining < 8 {
return head
}
return head + " " + ui.Help.Render(ui.Truncate(detail+" · "+formatDuration(snapshot.Elapsed()), remaining))
}
var statusStyles = map[statusLevel]lipgloss.Style{
levelInfo: ui.Help,
levelOK: ui.OK,
levelWarn: ui.Pending,
levelError: ui.Alert,
}
var statusIcons = map[statusLevel]string{
levelInfo: ui.IconNone,
levelOK: ui.IconPass,
levelWarn: ui.IconPending,
levelError: ui.IconFail,
}
func (m Model) statusView() string {
style, found := statusStyles[m.statusLevel]
if !found {
style = ui.Help
}
icon := statusIcons[m.statusLevel]
text := m.status
if icon != "" && icon != ui.IconNone {
text = icon + " " + text
}
return style.Render(ui.Truncate(text, max(m.width-1, 20)))
}
// footer shows the bindings that apply to the current screen, so the hints
// never advertise a key that would do nothing here.
func (m Model) footer() string {
primary := m.keys.DevHelp()
if m.screen == screenInstances {
primary = m.keys.InstanceHelp()
}
return clip(m.helpView.ShortHelpView(primary), m.width) + "\n" +
clip(m.helpView.ShortHelpView(m.keys.CommonHelp()), m.width)
}