Add the TUI.

A table with one row per URL, a level-colored log pane and a status bar.
New alerts flash their row and ring the bell. Keys pause, force checks,
open the product page or cart link, and reload the config, which is
validated first and applied in place, keeping each URL's timing.
Headless mode and the TUI now share one watcher.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
OverlordandClaude Bot committed 2026-10-14 12:25:26 +02:00
1 parent 8f0eda5d4d
commit a19e6fa711
14 files changed
+1359 -105

No files matched your search

+358
View File
@@ -0,0 +1,358 @@
// Package tui is the interactive view of dibs: a table with one row per
// URL, a log pane and a status bar.
package tui
import (
"errors"
"fmt"
"io"
"os"
"strings"
"time"
"charm.land/bubbles/v2/viewport"
tea "charm.land/bubbletea/v2"
"github.com/pkg/browser"
"git.security-command.org/Overlord/dibs/internal/alert"
"git.security-command.org/Overlord/dibs/internal/config"
"git.security-command.org/Overlord/dibs/internal/fetch"
"git.security-command.org/Overlord/dibs/internal/plugin"
"git.security-command.org/Overlord/dibs/internal/watch"
)
const (
// tick is how often the table refreshes. It is also the flash rate.
tick = 500 * time.Millisecond
flashFor = 30 * time.Second
noteFor = 10 * time.Second
)
// maxLines is how many lines the log pane keeps.
const maxLines = 2000
// Controller is the running watcher.
type Controller interface {
Statuses() []watch.Status
Pause(item string, paused bool) bool
PauseAll(paused bool)
CheckNow(item string) bool
Reload() ([]string, error)
}
// CheckMsg is one finished check and what the alert engine made of it.
type CheckMsg struct {
Result watch.Result
Decision alert.Decision
PriceErr error
}
type (
tickMsg time.Time
logMsg LogLine
reloadMsg struct {
summary []string
err error
}
openMsg struct {
url string
err error
}
)
// Status texts, as the STATUS column shows them.
const (
statusWatching = "watching"
statusAvailable = "AVAILABLE"
statusBlocked = "blocked"
statusError = "error"
statusPaused = "paused"
)
// result is what the last check of a URL found.
type result struct {
status string
price string
seller string
cartLink string
flash time.Time // the row flashes until then
}
type Model struct {
ctl Controller
path string
lines <-chan LogLine
now time.Time
rows []watch.Status
results map[string]*result // by configured URL
cursor int
offset int // the first table row on screen
logs []LogLine
log viewport.Model
logFocus bool
width, height int
note string
noteError bool
noteTime time.Time
reloading bool
}
// New returns the TUI for ctl. path is the config file, and logs is the
// handler the watcher logs to.
func New(ctl Controller, path string, logs *LogHandler) *Model {
// The browser's own output would draw over the TUI.
browser.Stdout, browser.Stderr = io.Discard, io.Discard
if home, err := os.UserHomeDir(); err == nil && strings.HasPrefix(path, home+string(os.PathSeparator)) { path = "~" + path[len(home):] }
m := &Model{
ctl: ctl,
path: path,
lines: logs.sink.lines,
now: time.Now(),
results: map[string]*result{},
log: viewport.New(),
}
m.rows = ctl.Statuses()
return m
}
func (m *Model) Init() tea.Cmd {
return tea.Batch(m.tick(), m.nextLine())
}
func (m *Model) tick() tea.Cmd {
return tea.Tick(tick, func(t time.Time) tea.Msg { return tickMsg(t) })
}
func (m *Model) nextLine() tea.Cmd {
return func() tea.Msg { return logMsg(<-m.lines) }
}
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.layout()
case tickMsg:
m.now = time.Time(msg)
m.rows = m.ctl.Statuses()
m.clampCursor()
return m, m.tick()
case logMsg:
m.addLog(LogLine(msg))
return m, m.nextLine()
case CheckMsg:
return m, m.checked(msg)
case reloadMsg:
m.reloading = false
m.rows = m.ctl.Statuses()
m.clampCursor()
if msg.err != nil { m.setNote(reloadError(msg.err), true) } else { m.setNote(reloadNote(msg.summary), false) }
case openMsg:
if msg.err != nil { m.setNote("cannot open the browser: "+msg.err.Error(), true) } else { m.setNote("opened "+msg.url, false) }
case tea.KeyPressMsg:
return m, m.key(msg)
}
return m, nil
}
// checked records a check. A new alert flashes its row and rings the bell.
func (m *Model) checked(c CheckMsg) tea.Cmd {
r := m.results[c.Result.URL]
if r == nil {
r = &result{}
m.results[c.Result.URL] = r
}
r.status = statusOf(c)
if rep := c.Result.Report; rep != nil {
r.price, r.seller = "", ""
if res := rep.Result; res != nil {
if res.Price != nil { r.price = alert.Money(*res.Price, res.Currency) }
r.seller = sellerText(res.Seller)
}
if rep.CartLink != "" { r.cartLink = rep.CartLink }
}
m.rows = m.ctl.Statuses()
if c.Decision.Alert == nil { return nil }
r.flash = m.now.Add(flashFor)
return tea.Raw("\a")
}
func statusOf(c CheckMsg) string {
rep := c.Result.Report
switch {
case rep == nil:
return statusError
case rep.Verdict == fetch.Challenge.String() || rep.Verdict == fetch.Blocked.String():
return statusBlocked
case c.Result.Err != nil || rep.Verdict == fetch.HTTPError.String():
return statusError
case c.Decision.Qualifies:
return statusAvailable
default:
return statusWatching
}
}
func sellerText(seller string) string {
switch seller {
case plugin.SellerFirstParty:
return "first party"
case plugin.SellerFulfilled:
return "fulfilled"
case plugin.SellerThirdParty:
return "third party"
default:
return ""
}
}
func (m *Model) key(msg tea.KeyPressMsg) tea.Cmd {
k := msg.String()
switch k {
case "q", "ctrl+c":
return tea.Quit
case "l", "tab":
m.logFocus = !m.logFocus
return nil
case "r":
return m.reload()
}
if m.logFocus {
if k == "esc" {
m.logFocus = false
return nil
}
var cmd tea.Cmd
m.log, cmd = m.log.Update(msg)
return cmd
}
switch k {
case "up", "k":
m.cursor--
case "down", "j":
m.cursor++
case "home", "g":
m.cursor = 0
case "end", "G":
m.cursor = len(m.rows) - 1
case "P":
m.pauseAll()
default:
return m.rowKey(k)
}
m.clampCursor()
return nil
}
// rowKey handles the keys that act on the selected row.
func (m *Model) rowKey(k string) tea.Cmd {
if m.cursor >= len(m.rows) { return nil }
row := m.rows[m.cursor]
switch k {
case "p":
m.ctl.Pause(row.Item, !row.Paused)
if row.Paused { m.setNote("resumed "+row.Item, false) } else { m.setNote("paused "+row.Item, false) }
m.rows = m.ctl.Statuses()
case "c":
m.ctl.CheckNow(row.Item)
m.setNote("checking "+row.Item+" as soon as the rate limits allow", false)
m.rows = m.ctl.Statuses()
case "o":
return open(row.FetchURL)
case "enter":
if r := m.results[row.URL]; r != nil && r.cartLink != "" { return open(r.cartLink) }
m.setNote("no cart link yet, opening the product page", false)
return open(row.FetchURL)
}
return nil
}
// pauseAll pauses every URL, or resumes them all if all are paused.
func (m *Model) pauseAll() {
pause := false
for _, row := range m.rows {
if !row.Paused { pause = true }
}
m.ctl.PauseAll(pause)
m.rows = m.ctl.Statuses()
if pause { m.setNote("paused everything", false) } else { m.setNote("resumed everything", false) }
}
func (m *Model) reload() tea.Cmd {
if m.reloading { return nil }
m.reloading = true
m.setNote("reloading "+m.path, false)
return func() tea.Msg {
summary, err := m.ctl.Reload()
return reloadMsg{summary: summary, err: err}
}
}
func reloadNote(summary []string) string {
if len(summary) == 1 { return "reloaded: " + summary[0] }
return fmt.Sprintf("reloaded: %d changes (see log)", len(summary))
}
// reloadError shows the first problem in the config. The log has them all.
func reloadError(err error) string {
var errs config.Errors
if errors.As(err, &errs) && len(errs) > 0 {
msg := "reload failed, config unchanged: line " + errs[0].Brief()
if len(errs) > 1 { msg += fmt.Sprintf(" (+%d more)", len(errs)-1) }
return msg
}
return "reload failed, config unchanged: " + err.Error()
}
func open(url string) tea.Cmd {
return func() tea.Msg { return openMsg{url: url, err: browser.OpenURL(url)} }
}
func (m *Model) setNote(note string, isError bool) {
m.note, m.noteError, m.noteTime = note, isError, time.Now()
}
func (m *Model) addLog(l LogLine) {
follow := m.log.AtBottom()
m.logs = append(m.logs, l)
if len(m.logs) > maxLines { m.logs = m.logs[len(m.logs)-maxLines:] }
m.log.SetContentLines(m.logLines())
if follow { m.log.GotoBottom() }
}
func (m *Model) clampCursor() {
m.cursor = max(0, min(m.cursor, len(m.rows)-1))
}