gunk-dev/the-valley

dashboard_render.go

source9ee95920e399main's published tip history
26.7 KiB
1package cmd
2
3import (
4 "fmt"
5 "sort"
6 "strings"
7 "time"
8
9 "github.com/charmbracelet/lipgloss"
10 "github.com/charmbracelet/x/ansi"
11 gh "the-valley/flow/internal/github"
12 "the-valley/flow/internal/integration"
13 "the-valley/flow/internal/pipeline"
14 "the-valley/flow/internal/run"
15)
16
17// Styling.
18
19var (
20 headerStyle = lipgloss.NewStyle().Bold(true)
21 greenStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("2"))
22 redStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("1"))
23 yellowStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("3"))
24 dimStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("8"))
25 cyanStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("6"))
26 sandboxStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("6"))
27 dimRedStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("9")).Faint(true)
28 selectedStyle = lipgloss.NewStyle().Bold(true).Background(lipgloss.Color("237"))
29)
30
31// defaultDashboardWidth is assumed until the terminal reports its size.
32const defaultDashboardWidth = 80
33
34// chromeKind is a line of the dashboard outside the scrolling run list.
35type chromeKind int
36
37const (
38 chromeHeader chromeKind = iota // title, session duration and cost
39 chromeSource // polling / webhook status
40 chromeSandbox // sandbox host reachability
41 chromeSummary // run counts, scroll position, hidden count
42 chromeBlank // spacing
43 chromeError // a recent pipeline error
44 chromeNotice // a new klaus to restart onto, or why that failed
45 chromeValley // the latest valley check failed; rows show git's view
46 chromeDataRef // finalize failed to push runs' data ref
47 chromeJobs // the jobs section's header line
48 chromeJob // a consult or review in the jobs section
49 chromeFooter // agent count and key help
50)
51
52// chromeItem is one chrome line. Top items render above the run list, the
53// rest below it.
54type chromeItem struct {
55 kind chromeKind
56 top bool
57 idx int // index into recentErrors for chromeError, or into the jobs for chromeJob
58}
59
60// dropRank orders chrome lines for removal on short panes: the highest rank
61// goes first. The summary line, which carries the scroll position, goes last.
62// The jobs section goes before the errors, and its header after its lines.
63func dropRank(k chromeKind) int {
64 switch k {
65 case chromeBlank:
66 return 7
67 case chromeSource, chromeSandbox:
68 return 6
69 case chromeJobs, chromeJob:
70 return 5
71 case chromeError:
72 return 4
73 case chromeFooter, chromeNotice, chromeValley, chromeDataRef:
74 return 3
75 case chromeHeader:
76 return 2
77 default:
78 return 1
79 }
80}
81
82// fitLayout picks the chrome lines to draw, the jobs section's among them,
83// and the number of run rows that fit in the pane. On a short pane it drops
84// chrome, least useful first, until a few rows fit, so rows are dropped
85// last. An unknown height (0) shows everything.
86func (m dashboardModel) fitLayout(nRows, nJobs int, jobsHeader bool) ([]chromeItem, int) {
87 items := []chromeItem{{kind: chromeHeader, top: true}, {kind: chromeSource, top: true}}
88 if len(m.sandboxHosts) > 0 {
89 items = append(items, chromeItem{kind: chromeSandbox, top: true})
90 }
91 items = append(items,
92 chromeItem{kind: chromeSummary, top: true},
93 chromeItem{kind: chromeBlank, top: true},
94 chromeItem{kind: chromeBlank},
95 )
96 if nJobs > 0 || jobsHeader {
97 items = append(items, chromeItem{kind: chromeJobs})
98 for i := 0; i < nJobs; i++ {
99 items = append(items, chromeItem{kind: chromeJob, idx: i})
100 }
101 }
102 for i := range m.recentErrors {
103 items = append(items, chromeItem{kind: chromeError, idx: i})
104 }
105 if m.binNotice != "" {
106 items = append(items, chromeItem{kind: chromeNotice})
107 }
108 if m.valleyErr != "" {
109 items = append(items, chromeItem{kind: chromeValley})
110 }
111 if m.dataRefWarning() != "" {
112 items = append(items, chromeItem{kind: chromeDataRef})
113 }
114 items = append(items, chromeItem{kind: chromeFooter})
115
116 if m.height <= 0 {
117 return items, nRows
118 }
119 // The body needs a line even with no rows, for the "no runs" message.
120 minBody := clamp(nRows, 1, 3)
121 for len(items) > 0 && m.height-len(items) < minBody {
122 // Drop the highest-ranked line; among equals the bottom-most, except
123 // errors, where the oldest goes first.
124 drop := 0
125 for i, it := range items {
126 r, best := dropRank(it.kind), dropRank(items[drop].kind)
127 if r > best || (r == best && it.kind != chromeError) {
128 drop = i
129 }
130 }
131 items = append(items[:drop], items[drop+1:]...)
132 }
133 return items, clamp(m.height-len(items), 0, nRows)
134}
135
136// rowLayout holds the column widths shared by every row, computed over all
137// rows so columns don't shift while scrolling.
138type rowLayout struct {
139 repoW int // 0 hides the repo column (single-repo lists without valley changes)
140 idW int
141 promptW int // 0 hides the prompt column
142}
143
144// maxHandleW caps the ID column for a valley change's handle.
145const maxHandleW = 12
146
147func newRowLayout(rows []dashRow, width int) rowLayout {
148 lay := rowLayout{idW: 6} // "#" plus a five-digit PR number
149 repos := make(map[string]bool)
150 changes := false
151 for _, r := range rows {
152 repos[r.repo] = true
153 switch {
154 case r.prNum != "":
155 case r.change != nil:
156 changes = true
157 lay.idW = max(lay.idW, min(len([]rune(r.change.Handle)), maxHandleW))
158 default:
159 lay.idW = max(lay.idW, 10) // "agent:" plus a four-character run ID
160 }
161 }
162 // A valley change is known by its repo and handle, so a list with one
163 // shows the repo even when it is the only one.
164 if len(repos) > 1 || changes {
165 for _, r := range rows {
166 lay.repoW = max(lay.repoW, len([]rune(r.repoLabel())))
167 }
168 lay.repoW = min(lay.repoW, 14)
169 if width < 60 {
170 lay.repoW = min(lay.repoW, 6)
171 }
172 }
173 fixed := 2 + lay.idW // gutter and ID
174 if lay.repoW > 0 {
175 fixed += lay.repoW + 2
176 }
177 lay.promptW = promptWidth(width, fixed+2)
178 return lay
179}
180
181// promptWidth shares a row between the prompt and the status labels after
182// it. The prompt grows on wide panes and shrinks first on narrow ones, so the
183// labels stay visible as long as possible; anything that still doesn't fit is
184// cut at the right edge rather than wrapped onto another line.
185func promptWidth(width, fixed int) int {
186 const statusRoom = 34 // e.g. "OPEN CI ✓ conflicts ✗ ready 2h"
187 const minPrompt, maxPrompt = 12, 48
188 if w := width - fixed - statusRoom; w >= minPrompt {
189 return min(w, maxPrompt)
190 }
191 // Narrow pane: keep room for a state label and squeeze the prompt.
192 w := clamp(width-fixed-10, 0, minPrompt)
193 if w < 4 {
194 return 0
195 }
196 return w
197}
198
199// shortRepoName drops the owner from "owner/repo".
200func shortRepoName(repo string) string {
201 if i := strings.LastIndex(repo, "/"); i >= 0 {
202 return repo[i+1:]
203 }
204 return repo
205}
206
207// renderRow renders one run-list row as a single line.
208func (m dashboardModel) renderRow(r dashRow, selected bool, lay rowLayout, now time.Time) string {
209 s := r.state()
210 var b strings.Builder
211 // Gutter marker for the cursor-selected row.
212 if selected {
213 b.WriteString("> ")
214 } else {
215 b.WriteString(" ")
216 }
217 if lay.repoW > 0 {
218 fmt.Fprintf(&b, "%-*s ", lay.repoW, truncateLine(r.repoLabel(), lay.repoW))
219 }
220 if r.prNum != "" {
221 // Pad the visible label first, then wrap only the visible text in a
222 // hyperlink so the OSC 8 escape bytes are not counted in the padding
223 // and column alignment is preserved.
224 label := fmt.Sprintf("#%-*s", lay.idW-1, r.prNum)
225 if s.PRURL != nil && *s.PRURL != "" {
226 label = hyperlink(*s.PRURL, label)
227 }
228 b.WriteString(label)
229 } else {
230 fmt.Fprintf(&b, "%-*s", lay.idW, truncateLine(r.idLabel(), lay.idW))
231 }
232 if lay.promptW > 0 {
233 fmt.Fprintf(&b, " %-*s", lay.promptW, truncateLine(r.description(), lay.promptW))
234 }
235
236 prefix := b.String()
237 switch {
238 case selected:
239 prefix = selectedStyle.Render(prefix)
240 case r.category == catDone:
241 prefix = dimStyle.Render(prefix)
242 }
243
244 var parts []string
245 if r.prNum != "" {
246 parts = m.prStatusParts(r)
247 } else {
248 parts = bareAgentParts(r)
249 }
250 if !r.lastSeen.IsZero() {
251 parts = append(parts, dimStyle.Render(humanizeDuration(now.Sub(r.lastSeen))))
252 }
253 return prefix + " " + strings.Join(parts, " ")
254}
255
256// prStatusParts returns the status labels for a PR row.
257func (m dashboardModel) prStatusParts(r dashRow) []string {
258 ps := r.ps
259 state := "OPEN"
260 for _, s := range r.runs {
261 if s.MergedAt != nil {
262 state = "MERGED"
263 }
264 }
265 if state != "MERGED" && ps != nil && ps.State != "" {
266 state = ps.State
267 }
268
269 parts := []string{stateLabel(state)}
270 if len(r.running) > 0 {
271 parts = append(parts, runningLabel(r.running))
272 }
273 if r.attention {
274 parts = append(parts, redStyle.Render("ATTN"))
275 }
276 if state == gh.StateNoAccess {
277 // Nothing else is known about a PR the agent can't read, and any
278 // pipeline stage is from before access was lost.
279 return parts
280 }
281
282 if ps != nil && state == "OPEN" {
283 parts = append(parts, ciLabel(ps.CI))
284 if ps.Conflicts == "yes" {
285 parts = append(parts, redStyle.Render("conflicts ✗"))
286 }
287 if ps.BehindBy > 0 {
288 parts = append(parts, dimStyle.Render(fmt.Sprintf("behind %d", ps.BehindBy)))
289 }
290 rd := ps.ReviewDecision
291 if strings.EqualFold(rd, "APPROVED") {
292 parts = append(parts, greenStyle.Render("ready"))
293 } else if strings.EqualFold(rd, "CHANGES_REQUESTED") {
294 parts = append(parts, redStyle.Render("changes requested"))
295 }
296 }
297
298 // Show klaus-internal approval if any run for this PR is approved.
299 if state == "OPEN" && isAnyRunApproved(r.runs) {
300 parts = append(parts, cyanStyle.Render("✓ approved"))
301 }
302
303 // Append pipeline stage if available.
304 if pps, ok := m.pipelineState(r); ok {
305 parts = append(parts, dimStyle.Render(pipeline.StageLabel(pps.Stage)))
306 }
307 return parts
308}
309
310// runningLabel names the agent running on a PR, e.g. a dispatched CI fix, or
311// on a change, e.g. a follow-up.
312func runningLabel(running []*run.State) string {
313 if len(running) > 1 {
314 return yellowStyle.Render(fmt.Sprintf("%d agents running", len(running)))
315 }
316 s := running[0]
317 return yellowStyle.Render("agent:"+shortRunID(s.ID)+" running") + sandboxTag(s)
318}
319
320// bareAgentParts returns the status labels for a row with no PR. A change
321// row, like a PR row, shows where the change stands (placeChange), then the
322// agent running on it; a bare agent reads RUNNING while it runs. A
323// valley change shows its version and head, any other pushed branch its
324// name and head. A valley verdict kept from an earlier check says so, and a
325// run whose change finalize couldn't mark ready says why. A restack conflict
326// on a change klaus owns says where its resolution stands.
327func bareAgentParts(r dashRow) []string {
328 s := r.state()
329 var parts []string
330 switch {
331 case len(r.running) > 0 && r.changeID == "":
332 parts = append(parts, yellowStyle.Render("RUNNING"))
333 case len(r.running) > 0 && !r.pushed:
334 // Nothing pushed to the change yet: its running agent says it all.
335 default:
336 parts = append(parts, changeStatus(r))
337 if r.outdated {
338 parts = append(parts, dimStyle.Render("(last known)"))
339 }
340 }
341 if r.changeID != "" && len(r.running) > 0 {
342 parts = append(parts, runningLabel(r.running))
343 }
344 if v := r.restack; v != nil {
345 parts = append(parts, redStyle.Render("restack conflict"), dimStyle.Render(v.Summary()))
346 }
347 if c := r.change; c != nil {
348 if ci := checksCI(c.Checks); ci != "" {
349 parts = append(parts, ciLabel(ci))
350 }
351 if names := c.Checks.FailedNames(); len(names) > 0 && checksCI(c.Checks) == "failing" {
352 parts = append(parts, redStyle.Render(truncateLine(strings.Join(names, ","), maxFailedChecksW)))
353 }
354 }
355 switch c := r.change; {
356 case c != nil && c.Version > 0:
357 parts = append(parts, fmt.Sprintf("v%d@%s", c.Version, shortSHA(c.Head)))
358 case c != nil:
359 parts = append(parts, shortSHA(c.Head))
360 case s.PushedBranch != nil && s.PushedSHA != nil:
361 parts = append(parts, *s.PushedBranch+"@"+shortSHA(*s.PushedSHA))
362 }
363 parts = append(parts, dimStyle.Render(formatCost(s)))
364 if tag := sandboxTag(s); tag != "" {
365 parts = append(parts, strings.TrimPrefix(tag, " "))
366 }
367 if v := s.Valley; v != nil && v.Error != "" && r.change == nil {
368 parts = append(parts, redStyle.Render(v.Error))
369 }
370 if s.Type != "track" {
371 parts = append(parts, dimStyle.Render(runBackendModel(s)))
372 }
373 return parts
374}
375
376// statusLabel is where a row without a PR stands: ATTN for salvaged work,
377// whichever of a change's runs holds it; for pushed work, what its verdict
378// says; else what its run's state says.
379func (r dashRow) statusLabel() string {
380 switch {
381 case r.attention:
382 return "ATTN"
383 case r.review:
384 return "REVIEW"
385 case r.pushed:
386 return pushedLabel(r.verdict, r.change != nil)
387 }
388 return agentStatusLabel(r.state(), r.verdict, r.change != nil)
389}
390
391// changeStatus is the styled label for where a row without a PR stands.
392func changeStatus(r dashRow) string {
393 label := r.statusLabel()
394 var status string
395 switch {
396 case r.attention || r.verdict == integration.Rejected || r.verdict == integration.Failed || r.verdict == integration.ChecksFailed:
397 status = redStyle.Render(label)
398 case r.verdict == integration.Stale || r.verdict == integration.Conflicting || r.verdict == integration.Uncertain:
399 status = yellowStyle.Render(label)
400 case r.category == catYours || r.verdict == integration.Approved || r.review:
401 status = cyanStyle.Render(label)
402 case r.verdict.Landed():
403 status = greenStyle.Render(label)
404 default:
405 status = dimStyle.Render(label)
406 }
407 return status
408}
409
410// shortSHA abbreviates a commit SHA to its first seven characters.
411func shortSHA(sha string) string {
412 if len(sha) > 7 {
413 return sha[:7]
414 }
415 return sha
416}
417
418// isAnyRunApproved returns true if any of the given run states has been
419// approved via `klaus approve`.
420func isAnyRunApproved(states []*run.State) bool {
421 for _, s := range states {
422 if s.Approved != nil && *s.Approved {
423 return true
424 }
425 }
426 return false
427}
428
429// renderSummary renders the line above the run list: the repo, counts per
430// category (always including yours), and on the right the scroll position and
431// how many runs are hidden.
432func (m dashboardModel) renderSummary(v dashView, width int) string {
433 var counts [catDone + 1]int
434 repos := make(map[string]bool)
435 for _, r := range v.all {
436 counts[r.category]++
437 repos[r.repo] = true
438 }
439 var left []string
440 switch len(repos) {
441 case 0:
442 case 1:
443 for repo := range repos {
444 left = append(left, repo)
445 }
446 default:
447 left = append(left, fmt.Sprintf("%d repos", len(repos)))
448 }
449 for c, n := range counts {
450 if n > 0 || (c == int(catYours) && len(v.all) > 0) {
451 left = append(left, fmt.Sprintf("%d %s", n, categoryNames[c]))
452 }
453 }
454
455 var right []string
456 if n := len(v.rows); n > 0 {
457 last := min(v.offset+v.bodyH, n)
458 first := min(v.offset+1, last)
459 right = append(right, fmt.Sprintf("%d–%d of %d", first, last, n))
460 }
461 if v.hidden > 0 {
462 right = append(right, yellowStyle.Render(fmt.Sprintf("%d hidden", v.hidden)))
463 } else if m.showAll {
464 right = append(right, "all shown")
465 }
466
467 // The right side wins on a narrow pane: cut the counts, not the position.
468 rightText := strings.Join(right, " · ")
469 rw := lipgloss.Width(rightText)
470 leftText := ansi.Truncate(" "+strings.Join(left, " · "), max(width-rw-2, 0), "…")
471 pad := max(width-lipgloss.Width(leftText)-rw-1, 1)
472 return dimStyle.Render(leftText) + strings.Repeat(" ", pad) + rightText
473}
474
475// renderFooter renders the agent count and key help, falling back to shorter
476// help on narrower panes. When the selected row is a change to approve or a
477// branch to submit and dashboard.approve_command is set, the footer leads
478// with that command. Otherwise, when an agent is running on the selected PR
479// or change, it leads with which one, and for a change awaiting review, with
480// the klaus ready that marks its head on screen ready. Then, for a change, it notes a newer
481// local push the valley doesn't hold as a version.
482func (m dashboardModel) renderFooter(v dashView, width int) string {
483 running, total := 0, 0
484 for _, r := range v.all {
485 running += len(r.running)
486 total += len(r.runs)
487 }
488 showKey := "h show all"
489 if m.showAll {
490 showKey = "h hide old"
491 }
492 jobsKey := ""
493 if v.jobsShown > 0 {
494 jobsKey = " · tab jobs"
495 }
496 variants := []string{
497 fmt.Sprintf(" %d/%d agents running | j/k move · pgup/pgdn page · g/G top/bottom · %s · a approve · d discuss · o open%s · x clear finished | r refresh · q quit",
498 running, total, showKey, jobsKey),
499 fmt.Sprintf(" j/k pgup/pgdn g/G move · %s · a approve · d discuss · o open%s · x clear finished · r refresh · q quit", showKey, jobsKey),
500 fmt.Sprintf(" j/k pgup/pgdn g/G · %s · a approve · d discuss · o open%s · x clear · q quit", showKey, jobsKey),
501 }
502 if m.clearing != nil {
503 variants = m.clearing.prompts()
504 }
505 style := func(f string) string { return dimStyle.Render(f) }
506 // The notes on the selected row, each part in its style, go before the
507 // key help.
508 type part struct {
509 text string
510 style lipgloss.Style
511 }
512 var notes []part
513 if len(v.rows) > 0 && m.clearing == nil {
514 r := v.rows[v.cursor]
515 if verb, cmd := m.approveCommand(r); cmd != "" {
516 notes = append(notes, part{verb + ": ", dimStyle}, part{cmd, cyanStyle})
517 } else if len(r.running) > 0 && (r.prNum != "" || r.changeID != "") {
518 notes = append(notes, part{runningNote(r), yellowStyle})
519 } else if r.review {
520 notes = append(notes, part{"awaiting review: once it passes, ", dimStyle}, part{"valley flow ready " + r.change.Handle + " --head " + shortSHA(r.change.Head), cyanStyle})
521 }
522 if r.unplaced != "" {
523 if len(notes) > 0 {
524 notes = append(notes, part{" · ", dimStyle})
525 }
526 notes = append(notes, part{"a newer push " + shortSHA(r.unplaced) + " isn't ready", yellowStyle})
527 }
528 if p := m.rowProse(r); p.total > 0 {
529 if len(notes) > 0 {
530 notes = append(notes, part{" · ", dimStyle})
531 }
532 notes = append(notes, part{p.String(), dimStyle})
533 }
534 }
535 if len(notes) > 0 {
536 lead, styled := " ", dimStyle.Render(" ")
537 for _, p := range notes {
538 lead += p.text
539 styled += p.style.Render(p.text)
540 }
541 for i, f := range variants {
542 variants[i] = lead + " |" + strings.TrimPrefix(f, " ")
543 }
544 variants = append(variants, lead)
545 style = func(f string) string {
546 return styled + dimStyle.Render(strings.TrimPrefix(f, lead))
547 }
548 }
549 footer := variants[len(variants)-1]
550 for _, f := range variants {
551 if lipgloss.Width(f) <= width {
552 footer = f
553 break
554 }
555 }
556 return style(footer)
557}
558
559// runningNote names the agents running on a PR or change row, e.g.
560// "agent:1a2b is working on this change".
561func runningNote(r dashRow) string {
562 what := "change"
563 if r.prNum != "" {
564 what = "PR"
565 }
566 names := make([]string, len(r.running))
567 for i, s := range r.running {
568 names[i] = "agent:" + shortRunID(s.ID)
569 }
570 if len(names) == 1 {
571 return names[0] + " is working on this " + what
572 }
573 return strings.Join(names, ", ") + " are working on this " + what
574}
575
576// approveCommand expands dashboard.approve_command for a READY row (verb
577// "approve") or a SUBMIT row (verb "submit"). {repo} is the repo as the row
578// names it, {branch} the pushed branch, {change} the full change ID,
579// {handle} the valley's handle and {head} the pushed head, the one the
580// operator sees: for a valley change, its active version's. Each value is shell-quoted (shellWord): a branch name is
581// the agent's to choose, and the operator pastes the command into a shell.
582// It returns "" for any other row (DRAFT among them), for a row with an
583// agent running on it, when no command is configured, or when the template
584// uses a placeholder the row has no value for, such as {handle} on a branch
585// no valley knows.
586func (m dashboardModel) approveCommand(r dashRow) (verb, cmd string) {
587 if m.approveTemplate == "" || r.prNum != "" || r.category != catYours || r.attention || len(r.running) > 0 || !r.pushed {
588 return "", ""
589 }
590 switch r.statusLabel() {
591 case "READY":
592 verb = "approve"
593 case "SUBMIT":
594 verb = "submit"
595 default:
596 return "", ""
597 }
598 var change, handle, branch, head string
599 if s := r.pushedRun(); s != nil {
600 change, branch, head = s.ChangeID, *s.PushedBranch, *s.PushedSHA
601 }
602 if c := r.change; c != nil {
603 change, handle, head = c.ChangeID, c.Handle, c.Head
604 if branch == "" {
605 branch = c.Branch
606 }
607 }
608 values := [][2]string{
609 {"{repo}", strings.TrimSuffix(r.repoLabel(), ".git")},
610 {"{branch}", branch},
611 {"{change}", change},
612 {"{handle}", handle},
613 {"{head}", head},
614 }
615 var pairs []string
616 for _, kv := range values {
617 if kv[1] == "" && strings.Contains(m.approveTemplate, kv[0]) {
618 return "", ""
619 }
620 pairs = append(pairs, kv[0], shellWord(kv[1]))
621 }
622 return verb, strings.NewReplacer(pairs...).Replace(m.approveTemplate)
623}
624
625// shellWord makes s one word for a POSIX shell: as it is when it is only
626// [A-Za-z0-9._/:-], which a shell takes literally, so the common command
627// stays readable; else single-quoted (shellQuote).
628func shellWord(s string) string {
629 plain := s != ""
630 for _, c := range s {
631 plain = plain && (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune("._/:-", c))
632 }
633 if plain {
634 return s
635 }
636 return shellQuote(s)
637}
638
639// renderSourceLine renders the data source status line.
640func (m dashboardModel) renderSourceLine() string {
641 if !m.useWebhook {
642 if m.webhookHeldNote != "" {
643 return dimStyle.Render(" polling: 30s (" + m.webhookHeldNote + ")")
644 }
645 return dimStyle.Render(" polling: 30s")
646 }
647 addr := m.webhookAddr
648 if addr == "" {
649 addr = "starting..."
650 }
651 tag := fmt.Sprintf(" webhook: listening on %s", addr)
652 if m.pollEnabled {
653 tag += " + polling: 30s"
654 } else if m.reconcileEvery > 0 {
655 tag += fmt.Sprintf(" + reconcile: %s", formatDuration(m.reconcileEvery))
656 }
657 // Freshness indicator: humanized age of the last webhook delivery,
658 // color-coded so a long silence is visible. It re-renders on the
659 // existing 30s tick, so the displayed age advances without a new timer.
660 freshText, sev := webhookFreshnessText(m.lastWebhookAt, time.Now())
661 return dimStyle.Render(tag) + webhookSeverityStyle(sev).Render(" · "+freshText)
662}
663
664// sandboxTag returns a styled "[sandbox]" tag if the agent ran on a sandbox host.
665func sandboxTag(s *run.State) string {
666 if s.Host != nil {
667 return " " + sandboxStyle.Render("[sandbox]")
668 }
669 return ""
670}
671
672func renderSandboxStatus(hosts map[string]bool) string {
673 if len(hosts) == 0 {
674 return ""
675 }
676 var parts []string
677 for host, reachable := range hosts {
678 if reachable {
679 parts = append(parts, greenStyle.Render(fmt.Sprintf(" sandbox %s: ✓", host)))
680 } else {
681 parts = append(parts, redStyle.Render(fmt.Sprintf(" sandbox %s: ✗", host)))
682 }
683 }
684 sort.Strings(parts)
685 return strings.Join(parts, " ") + "\n"
686}
687
688// hyperlink wraps text in an OSC 8 terminal hyperlink escape sequence.
689// The escape bytes are invisible and stripped by lipgloss.Width(), so the
690// visible width of the returned string equals that of text.
691//
692// If url is empty or contains any byte outside printable ASCII (32–126), the
693// plain text is returned unwrapped. This guards against terminal escape
694// sequence injection when the URL originates from untrusted input.
695func hyperlink(url, text string) string {
696 if url == "" {
697 return text
698 }
699 for i := 0; i < len(url); i++ {
700 if url[i] < 32 || url[i] > 126 {
701 return text
702 }
703 }
704 return "\x1b]8;;" + url + "\x1b\\" + text + "\x1b]8;;\x1b\\"
705}
706
707func stateLabel(state string) string {
708 switch state {
709 case "MERGED":
710 return greenStyle.Render("MERGED")
711 case "CLOSED":
712 return dimStyle.Render("CLOSED")
713 case gh.StateNoAccess:
714 return dimStyle.Render("NO ACCESS")
715 default:
716 return yellowStyle.Render("OPEN")
717 }
718}
719
720func ciLabel(ci string) string {
721 switch ci {
722 case "passing":
723 return greenStyle.Render("CI ✓")
724 case "failing":
725 return redStyle.Render("CI ✗")
726 case "pending":
727 return yellowStyle.Render("CI …")
728 default:
729 return dimStyle.Render("CI ?")
730 }
731}
732
733func clamp(v, lo, hi int) int {
734 if v < lo {
735 return lo
736 }
737 if v > hi {
738 return hi
739 }
740 return v
741}
742
743func pluralS(n int) string {
744 if n == 1 {
745 return ""
746 }
747 return "s"
748}
749
750// shortRunID returns the last 4 chars of a run ID.
751func shortRunID(id string) string {
752 if len(id) < 4 {
753 return id
754 }
755 return id[len(id)-4:]
756}
757
758// webhookSeverity classifies how stale the last webhook delivery is, for the
759// dashboard freshness indicator.
760type webhookSeverity int
761
762const (
763 webhookFresh webhookSeverity = iota // normal/idle — quiet, not necessarily broken
764 webhookStale // moderately old — worth a glance
765 webhookDead // very old — likely a broken delivery path
766)
767
768// Webhook freshness thresholds. Deliberately generous: a quiet repo is not a
769// broken one, so only escalate once an absence of deliveries is unusually long.
770const (
771 webhookStaleAfter = 30 * time.Minute
772 webhookDeadAfter = 2 * time.Hour
773)
774
775// webhookFreshnessText returns the humanized indicator text and severity for
776// the last webhook delivery time, evaluated relative to now.
777//
778// Limitation: an absence of webhook events can mean either a genuinely quiet
779// repo or a broken delivery path (relay down, port firewalled, etc.). This
780// indicator only surfaces the AGE of the last delivery so a human can judge —
781// it is NOT a definitive health check.
782func webhookFreshnessText(lastWebhookAt, now time.Time) (string, webhookSeverity) {
783 if lastWebhookAt.IsZero() {
784 return "no events yet", webhookFresh
785 }
786 age := now.Sub(lastWebhookAt)
787 text := "last event " + humanizeDuration(age)
788 switch {
789 case age >= webhookDeadAfter:
790 return text, webhookDead
791 case age >= webhookStaleAfter:
792 return text, webhookStale
793 default:
794 return text, webhookFresh
795 }
796}
797
798// webhookSeverityStyle maps a freshness severity to its lipgloss style.
799func webhookSeverityStyle(sev webhookSeverity) lipgloss.Style {
800 switch sev {
801 case webhookDead:
802 return redStyle
803 case webhookStale:
804 return yellowStyle
805 default:
806 return dimStyle
807 }
808}
809
810// humanizeDuration renders a duration in a single compact unit, e.g. "12s",
811// "5m", "3h", "1d". Negative durations are clamped to "0s".
812func humanizeDuration(d time.Duration) string {
813 switch {
814 case d < time.Minute:
815 s := int(d.Seconds())
816 if s < 0 {
817 s = 0
818 }
819 return fmt.Sprintf("%ds", s)
820 case d < time.Hour:
821 return fmt.Sprintf("%dm", int(d.Minutes()))
822 case d < 24*time.Hour:
823 return fmt.Sprintf("%dh", int(d.Hours()))
824 default:
825 return fmt.Sprintf("%dd", int(d.Hours()/24))
826 }
827}
828
829// dataRefWarning names the newest run whose data ref push failed at finalize,
830// and how many did, or is "" when none did. It reads the runs' records, which
831// say what happened at finalize, not whether the ref has reached origin since.
832func (m dashboardModel) dataRefWarning() string {
833 failed := failedDataRefPushes(m.states)
834 if len(failed) == 0 {
835 return ""
836 }
837 latest := failed[0]
838 if len(failed) == 1 {
839 return "at finalize: " + latest.ID + " " + dataRefFailure(latest.DataRefPush)
840 }
841 return fmt.Sprintf("at finalize: %d runs failed to publish; newest %s %s", len(failed), latest.ID, dataRefFailure(latest.DataRefPush))
842}
843
844// formatDuration renders a duration as "Xh Ym" or "Xm Ys".
845func formatDuration(d time.Duration) string {
846 d = d.Round(time.Minute)
847 h := int(d.Hours())
848 m := int(d.Minutes()) % 60
849 if h > 0 {
850 return fmt.Sprintf("%dh %02dm", h, m)
851 }
852 return fmt.Sprintf("%dm", m)
853}