gunk-dev/the-valley

dashboard_render.go

sourceb8e46aa6aaccmain's published tip history
26.8 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 switch {
251 case r.review:
252 parts = append(parts, dimStyle.Render(formatAge(r.reviewSince, now)))
253 case !r.lastSeen.IsZero():
254 parts = append(parts, dimStyle.Render(humanizeDuration(now.Sub(r.lastSeen))))
255 }
256 return prefix + " " + strings.Join(parts, " ")
257}
258
259// prStatusParts returns the status labels for a PR row.
260func (m dashboardModel) prStatusParts(r dashRow) []string {
261 ps := r.ps
262 state := "OPEN"
263 for _, s := range r.runs {
264 if s.MergedAt != nil {
265 state = "MERGED"
266 }
267 }
268 if state != "MERGED" && ps != nil && ps.State != "" {
269 state = ps.State
270 }
271
272 parts := []string{stateLabel(state)}
273 if len(r.running) > 0 {
274 parts = append(parts, runningLabel(r.running))
275 }
276 if r.attention {
277 parts = append(parts, redStyle.Render("ATTN"))
278 }
279 if state == gh.StateNoAccess {
280 // Nothing else is known about a PR the agent can't read, and any
281 // pipeline stage is from before access was lost.
282 return parts
283 }
284
285 if ps != nil && state == "OPEN" {
286 parts = append(parts, ciLabel(ps.CI))
287 if ps.Conflicts == "yes" {
288 parts = append(parts, redStyle.Render("conflicts ✗"))
289 }
290 if ps.BehindBy > 0 {
291 parts = append(parts, dimStyle.Render(fmt.Sprintf("behind %d", ps.BehindBy)))
292 }
293 rd := ps.ReviewDecision
294 if strings.EqualFold(rd, "APPROVED") {
295 parts = append(parts, greenStyle.Render("ready"))
296 } else if strings.EqualFold(rd, "CHANGES_REQUESTED") {
297 parts = append(parts, redStyle.Render("changes requested"))
298 }
299 }
300
301 // Show klaus-internal approval if any run for this PR is approved.
302 if state == "OPEN" && isAnyRunApproved(r.runs) {
303 parts = append(parts, cyanStyle.Render("✓ approved"))
304 }
305
306 // Append pipeline stage if available.
307 if pps, ok := m.pipelineState(r); ok {
308 parts = append(parts, dimStyle.Render(pipeline.StageLabel(pps.Stage)))
309 }
310 return parts
311}
312
313// runningLabel names the agent running on a PR, e.g. a dispatched CI fix, or
314// on a change, e.g. a follow-up.
315func runningLabel(running []*run.State) string {
316 if len(running) > 1 {
317 return yellowStyle.Render(fmt.Sprintf("%d agents running", len(running)))
318 }
319 s := running[0]
320 return yellowStyle.Render("agent:"+shortRunID(s.ID)+" running") + sandboxTag(s)
321}
322
323// bareAgentParts returns the status labels for a row with no PR. A change
324// row, like a PR row, shows where the change stands (placeChange), then the
325// agent running on it; a bare agent reads RUNNING while it runs. A
326// valley change shows its version and head, any other pushed branch its
327// name and head. A valley verdict kept from an earlier check says so, and a
328// run whose change finalize couldn't mark ready says why. A restack conflict
329// on a change klaus owns says where its resolution stands.
330func bareAgentParts(r dashRow) []string {
331 s := r.state()
332 var parts []string
333 switch {
334 case len(r.running) > 0 && r.changeID == "":
335 parts = append(parts, yellowStyle.Render("RUNNING"))
336 case len(r.running) > 0 && !r.pushed:
337 // Nothing pushed to the change yet: its running agent says it all.
338 default:
339 parts = append(parts, changeStatus(r))
340 if r.outdated {
341 parts = append(parts, dimStyle.Render("(last known)"))
342 }
343 }
344 if r.changeID != "" && len(r.running) > 0 {
345 parts = append(parts, runningLabel(r.running))
346 }
347 if v := r.restack; v != nil {
348 parts = append(parts, redStyle.Render("restack conflict"), dimStyle.Render(v.Summary()))
349 }
350 if c := r.change; c != nil {
351 if ci := checksCI(c.Checks); ci != "" {
352 parts = append(parts, ciLabel(ci))
353 }
354 if names := c.Checks.FailedNames(); len(names) > 0 && checksCI(c.Checks) == "failing" {
355 parts = append(parts, redStyle.Render(truncateLine(strings.Join(names, ","), maxFailedChecksW)))
356 }
357 }
358 switch c := r.change; {
359 case c != nil && c.Version > 0:
360 parts = append(parts, fmt.Sprintf("v%d@%s", c.Version, shortSHA(c.Head)))
361 case c != nil:
362 parts = append(parts, shortSHA(c.Head))
363 case s.PushedBranch != nil && s.PushedSHA != nil:
364 parts = append(parts, *s.PushedBranch+"@"+shortSHA(*s.PushedSHA))
365 }
366 parts = append(parts, dimStyle.Render(formatCost(s)))
367 if tag := sandboxTag(s); tag != "" {
368 parts = append(parts, strings.TrimPrefix(tag, " "))
369 }
370 if v := s.Valley; v != nil && v.Error != "" && r.change == nil {
371 parts = append(parts, redStyle.Render(v.Error))
372 }
373 if s.Type != "track" {
374 parts = append(parts, dimStyle.Render(runBackendModel(s)))
375 }
376 return parts
377}
378
379// statusLabel is where a row without a PR stands: ATTN for salvaged work,
380// whichever of a change's runs holds it; for pushed work, what its verdict
381// says; else what its run's state says.
382func (r dashRow) statusLabel() string {
383 switch {
384 case r.attention:
385 return "ATTN"
386 case r.review:
387 return "REVIEW"
388 case r.pushed:
389 return pushedLabel(r.verdict, r.change != nil)
390 }
391 return agentStatusLabel(r.state(), r.verdict, r.change != nil)
392}
393
394// changeStatus is the styled label for where a row without a PR stands.
395func changeStatus(r dashRow) string {
396 label := r.statusLabel()
397 var status string
398 switch {
399 case r.attention || r.verdict == integration.Rejected || r.verdict == integration.Failed || r.verdict == integration.ChecksFailed:
400 status = redStyle.Render(label)
401 case r.verdict == integration.Stale || r.verdict == integration.Conflicting || r.verdict == integration.Uncertain:
402 status = yellowStyle.Render(label)
403 case r.category == catYours || r.verdict == integration.Approved || r.review:
404 status = cyanStyle.Render(label)
405 case r.verdict.Landed():
406 status = greenStyle.Render(label)
407 default:
408 status = dimStyle.Render(label)
409 }
410 return status
411}
412
413// shortSHA abbreviates a commit SHA to its first seven characters.
414func shortSHA(sha string) string {
415 if len(sha) > 7 {
416 return sha[:7]
417 }
418 return sha
419}
420
421// isAnyRunApproved returns true if any of the given run states has been
422// approved via `klaus approve`.
423func isAnyRunApproved(states []*run.State) bool {
424 for _, s := range states {
425 if s.Approved != nil && *s.Approved {
426 return true
427 }
428 }
429 return false
430}
431
432// renderSummary renders the line above the run list: the repo, counts per
433// category (always including yours), and on the right the scroll position and
434// how many runs are hidden.
435func (m dashboardModel) renderSummary(v dashView, width int) string {
436 var counts [catDone + 1]int
437 repos := make(map[string]bool)
438 for _, r := range v.all {
439 counts[r.category]++
440 repos[r.repo] = true
441 }
442 var left []string
443 switch len(repos) {
444 case 0:
445 case 1:
446 for repo := range repos {
447 left = append(left, repo)
448 }
449 default:
450 left = append(left, fmt.Sprintf("%d repos", len(repos)))
451 }
452 for c, n := range counts {
453 if n > 0 || (c == int(catYours) && len(v.all) > 0) {
454 left = append(left, fmt.Sprintf("%d %s", n, categoryNames[c]))
455 }
456 }
457
458 var right []string
459 if n := len(v.rows); n > 0 {
460 last := min(v.offset+v.bodyH, n)
461 first := min(v.offset+1, last)
462 right = append(right, fmt.Sprintf("%d–%d of %d", first, last, n))
463 }
464 if v.hidden > 0 {
465 right = append(right, yellowStyle.Render(fmt.Sprintf("%d hidden", v.hidden)))
466 } else if m.showAll {
467 right = append(right, "all shown")
468 }
469
470 // The right side wins on a narrow pane: cut the counts, not the position.
471 rightText := strings.Join(right, " · ")
472 rw := lipgloss.Width(rightText)
473 leftText := ansi.Truncate(" "+strings.Join(left, " · "), max(width-rw-2, 0), "…")
474 pad := max(width-lipgloss.Width(leftText)-rw-1, 1)
475 return dimStyle.Render(leftText) + strings.Repeat(" ", pad) + rightText
476}
477
478// renderFooter renders the agent count and key help, falling back to shorter
479// help on narrower panes. When the selected row is a change to approve or a
480// branch to submit and dashboard.approve_command is set, the footer leads
481// with that command. Otherwise, when an agent is running on the selected PR
482// or change, it leads with which one, and for a change awaiting review, with
483// the klaus ready that marks its head on screen ready. Then, for a change, it notes a newer
484// local push the valley doesn't hold as a version.
485func (m dashboardModel) renderFooter(v dashView, width int) string {
486 running, total := 0, 0
487 for _, r := range v.all {
488 running += len(r.running)
489 total += len(r.runs)
490 }
491 showKey := "h show all"
492 if m.showAll {
493 showKey = "h hide old"
494 }
495 jobsKey := ""
496 if v.jobsShown > 0 {
497 jobsKey = " · tab jobs"
498 }
499 variants := []string{
500 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",
501 running, total, showKey, jobsKey),
502 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),
503 fmt.Sprintf(" j/k pgup/pgdn g/G · %s · a approve · d discuss · o open%s · x clear · q quit", showKey, jobsKey),
504 }
505 if m.clearing != nil {
506 variants = m.clearing.prompts()
507 }
508 style := func(f string) string { return dimStyle.Render(f) }
509 // The notes on the selected row, each part in its style, go before the
510 // key help.
511 type part struct {
512 text string
513 style lipgloss.Style
514 }
515 var notes []part
516 if len(v.rows) > 0 && m.clearing == nil {
517 r := v.rows[v.cursor]
518 if verb, cmd := m.approveCommand(r); cmd != "" {
519 notes = append(notes, part{verb + ": ", dimStyle}, part{cmd, cyanStyle})
520 } else if len(r.running) > 0 && (r.prNum != "" || r.changeID != "") {
521 notes = append(notes, part{runningNote(r), yellowStyle})
522 } else if r.review {
523 notes = append(notes, part{"awaiting review: once it passes, ", dimStyle}, part{"valley flow ready " + r.change.Handle + " --head " + shortSHA(r.change.Head), cyanStyle})
524 }
525 if r.unplaced != "" {
526 if len(notes) > 0 {
527 notes = append(notes, part{" · ", dimStyle})
528 }
529 notes = append(notes, part{"a newer push " + shortSHA(r.unplaced) + " isn't ready", yellowStyle})
530 }
531 if p := m.rowProse(r); p.total > 0 {
532 if len(notes) > 0 {
533 notes = append(notes, part{" · ", dimStyle})
534 }
535 notes = append(notes, part{p.String(), dimStyle})
536 }
537 }
538 if len(notes) > 0 {
539 lead, styled := " ", dimStyle.Render(" ")
540 for _, p := range notes {
541 lead += p.text
542 styled += p.style.Render(p.text)
543 }
544 for i, f := range variants {
545 variants[i] = lead + " |" + strings.TrimPrefix(f, " ")
546 }
547 variants = append(variants, lead)
548 style = func(f string) string {
549 return styled + dimStyle.Render(strings.TrimPrefix(f, lead))
550 }
551 }
552 footer := variants[len(variants)-1]
553 for _, f := range variants {
554 if lipgloss.Width(f) <= width {
555 footer = f
556 break
557 }
558 }
559 return style(footer)
560}
561
562// runningNote names the agents running on a PR or change row, e.g.
563// "agent:1a2b is working on this change".
564func runningNote(r dashRow) string {
565 what := "change"
566 if r.prNum != "" {
567 what = "PR"
568 }
569 names := make([]string, len(r.running))
570 for i, s := range r.running {
571 names[i] = "agent:" + shortRunID(s.ID)
572 }
573 if len(names) == 1 {
574 return names[0] + " is working on this " + what
575 }
576 return strings.Join(names, ", ") + " are working on this " + what
577}
578
579// approveCommand expands dashboard.approve_command for a READY row (verb
580// "approve") or a SUBMIT row (verb "submit"). {repo} is the repo as the row
581// names it, {branch} the pushed branch, {change} the full change ID,
582// {handle} the valley's handle and {head} the pushed head, the one the
583// operator sees: for a valley change, its active version's. Each value is shell-quoted (shellWord): a branch name is
584// the agent's to choose, and the operator pastes the command into a shell.
585// It returns "" for any other row (DRAFT among them), for a row with an
586// agent running on it, when no command is configured, or when the template
587// uses a placeholder the row has no value for, such as {handle} on a branch
588// no valley knows.
589func (m dashboardModel) approveCommand(r dashRow) (verb, cmd string) {
590 if m.approveTemplate == "" || r.prNum != "" || r.category != catYours || r.attention || len(r.running) > 0 || !r.pushed {
591 return "", ""
592 }
593 switch r.statusLabel() {
594 case "READY":
595 verb = "approve"
596 case "SUBMIT":
597 verb = "submit"
598 default:
599 return "", ""
600 }
601 var change, handle, branch, head string
602 if s := r.pushedRun(); s != nil {
603 change, branch, head = s.ChangeID, *s.PushedBranch, *s.PushedSHA
604 }
605 if c := r.change; c != nil {
606 change, handle, head = c.ChangeID, c.Handle, c.Head
607 if branch == "" {
608 branch = c.Branch
609 }
610 }
611 values := [][2]string{
612 {"{repo}", strings.TrimSuffix(r.repoLabel(), ".git")},
613 {"{branch}", branch},
614 {"{change}", change},
615 {"{handle}", handle},
616 {"{head}", head},
617 }
618 var pairs []string
619 for _, kv := range values {
620 if kv[1] == "" && strings.Contains(m.approveTemplate, kv[0]) {
621 return "", ""
622 }
623 pairs = append(pairs, kv[0], shellWord(kv[1]))
624 }
625 return verb, strings.NewReplacer(pairs...).Replace(m.approveTemplate)
626}
627
628// shellWord makes s one word for a POSIX shell: as it is when it is only
629// [A-Za-z0-9._/:-], which a shell takes literally, so the common command
630// stays readable; else single-quoted (shellQuote).
631func shellWord(s string) string {
632 plain := s != ""
633 for _, c := range s {
634 plain = plain && (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune("._/:-", c))
635 }
636 if plain {
637 return s
638 }
639 return shellQuote(s)
640}
641
642// renderSourceLine renders the data source status line.
643func (m dashboardModel) renderSourceLine() string {
644 if !m.useWebhook {
645 if m.webhookHeldNote != "" {
646 return dimStyle.Render(" polling: 30s (" + m.webhookHeldNote + ")")
647 }
648 return dimStyle.Render(" polling: 30s")
649 }
650 addr := m.webhookAddr
651 if addr == "" {
652 addr = "starting..."
653 }
654 tag := fmt.Sprintf(" webhook: listening on %s", addr)
655 if m.pollEnabled {
656 tag += " + polling: 30s"
657 } else if m.reconcileEvery > 0 {
658 tag += fmt.Sprintf(" + reconcile: %s", formatDuration(m.reconcileEvery))
659 }
660 // Freshness indicator: humanized age of the last webhook delivery,
661 // color-coded so a long silence is visible. It re-renders on the
662 // existing 30s tick, so the displayed age advances without a new timer.
663 freshText, sev := webhookFreshnessText(m.lastWebhookAt, time.Now())
664 return dimStyle.Render(tag) + webhookSeverityStyle(sev).Render(" · "+freshText)
665}
666
667// sandboxTag returns a styled "[sandbox]" tag if the agent ran on a sandbox host.
668func sandboxTag(s *run.State) string {
669 if s.Host != nil {
670 return " " + sandboxStyle.Render("[sandbox]")
671 }
672 return ""
673}
674
675func renderSandboxStatus(hosts map[string]bool) string {
676 if len(hosts) == 0 {
677 return ""
678 }
679 var parts []string
680 for host, reachable := range hosts {
681 if reachable {
682 parts = append(parts, greenStyle.Render(fmt.Sprintf(" sandbox %s: ✓", host)))
683 } else {
684 parts = append(parts, redStyle.Render(fmt.Sprintf(" sandbox %s: ✗", host)))
685 }
686 }
687 sort.Strings(parts)
688 return strings.Join(parts, " ") + "\n"
689}
690
691// hyperlink wraps text in an OSC 8 terminal hyperlink escape sequence.
692// The escape bytes are invisible and stripped by lipgloss.Width(), so the
693// visible width of the returned string equals that of text.
694//
695// If url is empty or contains any byte outside printable ASCII (32–126), the
696// plain text is returned unwrapped. This guards against terminal escape
697// sequence injection when the URL originates from untrusted input.
698func hyperlink(url, text string) string {
699 if url == "" {
700 return text
701 }
702 for i := 0; i < len(url); i++ {
703 if url[i] < 32 || url[i] > 126 {
704 return text
705 }
706 }
707 return "\x1b]8;;" + url + "\x1b\\" + text + "\x1b]8;;\x1b\\"
708}
709
710func stateLabel(state string) string {
711 switch state {
712 case "MERGED":
713 return greenStyle.Render("MERGED")
714 case "CLOSED":
715 return dimStyle.Render("CLOSED")
716 case gh.StateNoAccess:
717 return dimStyle.Render("NO ACCESS")
718 default:
719 return yellowStyle.Render("OPEN")
720 }
721}
722
723func ciLabel(ci string) string {
724 switch ci {
725 case "passing":
726 return greenStyle.Render("CI ✓")
727 case "failing":
728 return redStyle.Render("CI ✗")
729 case "pending":
730 return yellowStyle.Render("CI …")
731 default:
732 return dimStyle.Render("CI ?")
733 }
734}
735
736func clamp(v, lo, hi int) int {
737 if v < lo {
738 return lo
739 }
740 if v > hi {
741 return hi
742 }
743 return v
744}
745
746func pluralS(n int) string {
747 if n == 1 {
748 return ""
749 }
750 return "s"
751}
752
753// shortRunID returns the last 4 chars of a run ID.
754func shortRunID(id string) string {
755 if len(id) < 4 {
756 return id
757 }
758 return id[len(id)-4:]
759}
760
761// webhookSeverity classifies how stale the last webhook delivery is, for the
762// dashboard freshness indicator.
763type webhookSeverity int
764
765const (
766 webhookFresh webhookSeverity = iota // normal/idle — quiet, not necessarily broken
767 webhookStale // moderately old — worth a glance
768 webhookDead // very old — likely a broken delivery path
769)
770
771// Webhook freshness thresholds. Deliberately generous: a quiet repo is not a
772// broken one, so only escalate once an absence of deliveries is unusually long.
773const (
774 webhookStaleAfter = 30 * time.Minute
775 webhookDeadAfter = 2 * time.Hour
776)
777
778// webhookFreshnessText returns the humanized indicator text and severity for
779// the last webhook delivery time, evaluated relative to now.
780//
781// Limitation: an absence of webhook events can mean either a genuinely quiet
782// repo or a broken delivery path (relay down, port firewalled, etc.). This
783// indicator only surfaces the AGE of the last delivery so a human can judge —
784// it is NOT a definitive health check.
785func webhookFreshnessText(lastWebhookAt, now time.Time) (string, webhookSeverity) {
786 if lastWebhookAt.IsZero() {
787 return "no events yet", webhookFresh
788 }
789 age := now.Sub(lastWebhookAt)
790 text := "last event " + humanizeDuration(age)
791 switch {
792 case age >= webhookDeadAfter:
793 return text, webhookDead
794 case age >= webhookStaleAfter:
795 return text, webhookStale
796 default:
797 return text, webhookFresh
798 }
799}
800
801// webhookSeverityStyle maps a freshness severity to its lipgloss style.
802func webhookSeverityStyle(sev webhookSeverity) lipgloss.Style {
803 switch sev {
804 case webhookDead:
805 return redStyle
806 case webhookStale:
807 return yellowStyle
808 default:
809 return dimStyle
810 }
811}
812
813// humanizeDuration renders a duration in a single compact unit, e.g. "12s",
814// "5m", "3h", "1d". Negative durations are clamped to "0s".
815func humanizeDuration(d time.Duration) string {
816 switch {
817 case d < time.Minute:
818 s := int(d.Seconds())
819 if s < 0 {
820 s = 0
821 }
822 return fmt.Sprintf("%ds", s)
823 case d < time.Hour:
824 return fmt.Sprintf("%dm", int(d.Minutes()))
825 case d < 24*time.Hour:
826 return fmt.Sprintf("%dh", int(d.Hours()))
827 default:
828 return fmt.Sprintf("%dd", int(d.Hours()/24))
829 }
830}
831
832// dataRefWarning names the newest run whose data ref push failed at finalize,
833// and how many did, or is "" when none did. It reads the runs' records, which
834// say what happened at finalize, not whether the ref has reached origin since.
835func (m dashboardModel) dataRefWarning() string {
836 failed := failedDataRefPushes(m.states)
837 if len(failed) == 0 {
838 return ""
839 }
840 latest := failed[0]
841 if len(failed) == 1 {
842 return "at finalize: " + latest.ID + " " + dataRefFailure(latest.DataRefPush)
843 }
844 return fmt.Sprintf("at finalize: %d runs failed to publish; newest %s %s", len(failed), latest.ID, dataRefFailure(latest.DataRefPush))
845}
846
847// formatDuration renders a duration as "Xh Ym" or "Xm Ys".
848func formatDuration(d time.Duration) string {
849 d = d.Round(time.Minute)
850 h := int(d.Hours())
851 m := int(d.Minutes()) % 60
852 if h > 0 {
853 return fmt.Sprintf("%dh %02dm", h, m)
854 }
855 return fmt.Sprintf("%dm", m)
856}