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