gunk-dev/the-valley

dashboard_select.go

sourcecaaa5bee5e11main's published tip history
31.2 KiB
1package cmd
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "regexp"
8 "slices"
9 "sort"
10 "strings"
11 "time"
12
13 "the-valley/flow/internal/config"
14 gh "the-valley/flow/internal/github"
15 "the-valley/flow/internal/integration"
16 "the-valley/flow/internal/jobs"
17 "the-valley/flow/internal/pipeline"
18 "the-valley/flow/internal/restack"
19 "the-valley/flow/internal/run"
20)
21
22// rowCategory groups dashboard rows by whose move it is; the operator's come
23// first.
24type rowCategory int
25
26const (
27 catYours rowCategory = iota // the operator's or the coordinator's move: needs attention, a change to approve, review or look at, a draft, a branch to submit, a PR ready to approve
28 catAgents // an agent is running on it
29 catPipeline // an open PR the pipeline is moving (CI, conflicts, behind, approved and waiting), or a change the integrator has to decide
30 catDone // merged, closed, integrated, gone, withdrawn, no access, or an agent that exited
31)
32
33// categoryNames label the categories in the summary line.
34var categoryNames = [...]string{catYours: "yours", catAgents: "agents", catPipeline: "pipeline", catDone: "done"}
35
36// defaultHideFinishedAfter is how long a done row stays on the dashboard
37// before it is hidden behind "show all".
38const defaultHideFinishedAfter = time.Hour
39
40// hideFinishedAfter resolves the hide threshold from config. A zero value
41// means "use the default"; a negative value means never hide (returns 0).
42func hideFinishedAfter(cfg *config.DashboardConfig) time.Duration {
43 if cfg == nil || cfg.HideFinishedAfterMinutes == 0 {
44 return defaultHideFinishedAfter
45 }
46 if cfg.HideFinishedAfterMinutes < 0 {
47 return 0
48 }
49 return time.Duration(cfg.HideFinishedAfterMinutes) * time.Minute
50}
51
52// dashRow is one line of the dashboard run list: a PR, with every agent
53// that worked on it and every run of its change that has no PR; a change
54// no PR carries, with every run on it and its klaus track record, if any;
55// or a bare agent run with neither.
56type dashRow struct {
57 key string // stable identity, so the selection survives reordering
58 repo string
59 prNum string // "" for a change or a bare agent
60 changeID string // the change a change row groups; "" for a PR or a bare agent
61 runs []*run.State // a PR's agents, then its change's runs without a PR; runs on this change (newest first); or the single bare agent
62 running []*run.State // the subset of runs whose agent is running
63 ps *prStatus // GitHub status, nil until fetched or for bare agents
64 category rowCategory
65 lastSeen time.Time // most recent activity across runs, for ordering and hiding
66 hideable bool // merged, closed, integrated, gone, no access or cleaned up: may be hidden once old
67 // finished is merged, closed, integrated, withdrawn or gone once the
68 // row's PR or change is finished; "" otherwise.
69 finished string
70 // attention is set when the row is the operator's because something
71 // needs attention (salvaged work, a stalled or budget-paused PR).
72 attention bool
73 // pushed is set when the row shows where pushed work stands: a bare
74 // pushed run, or a change with a version, the valley's or a local push.
75 pushed bool
76 // current is the run that pushed a change row's state: the local run that
77 // pushed the active version of a change the valley lists, or, for a
78 // change it doesn't, the latest run that pushed. nil when none did, as
79 // when the active version was marked ready elsewhere.
80 current *run.State
81 // verdict is the latest integration check of a bare pushed run; for a
82 // change row, the valley's view of the change's active version, or else
83 // the check of its current run.
84 verdict integration.Verdict
85 // change is how a valley knows a bare pushed run, or a change row's
86 // active version: the latest check's view, or else what finalize
87 // recorded. nil for a branch no valley knows.
88 change *integration.Change
89 // unplaced is the head of a change's latest local push when the valley
90 // lists the change but doesn't hold that head as a version of it, as
91 // when its ready failed. The row doesn't show it; the footer notes it.
92 unplaced string
93 // provisional marks a SUBMIT or READY row with no definite integration
94 // verdict yet: it may turn out to have landed long ago.
95 provisional bool
96 // outdated marks a verdict and change kept from an earlier check because
97 // the latest couldn't ask the valley (integration.Result.Outdated).
98 outdated bool
99 // restack is where a restack conflict the valley reports on the change
100 // stands, when klaus owns the change; nil for none.
101 restack *restack.View
102 // review marks a valley change whose version finalize left a draft
103 // awaiting review (awaitsReview): it reads REVIEW, not DRAFT.
104 review bool
105 // reviewSince is when a REVIEW row's draft was left for review, as
106 // valley flow queue dates it; zero when no event says.
107 reviewSince time.Time
108}
109
110// state returns the run that speaks for the row: a PR's first agent, which
111// carries the PR URL and is the one marked by approve; a change's current
112// run, or else its latest; or the bare agent. Where a change stands comes
113// from the row (pushed, verdict, change), not from this run.
114func (r dashRow) state() *run.State {
115 if r.current != nil {
116 return r.current
117 }
118 return r.runs[0]
119}
120
121// repoLabel names the row's repo: the valley's name for a valley change,
122// else the short project name.
123func (r dashRow) repoLabel() string {
124 if r.change != nil && r.change.Repo != "" {
125 return r.change.Repo
126 }
127 return shortRepoName(r.repo)
128}
129
130// idLabel names a row without a PR: a valley change's handle, else the
131// first 8 characters of its change ID, or for a bare agent "agent:" and the
132// tail of the run ID.
133func (r dashRow) idLabel() string {
134 switch {
135 case r.change != nil:
136 return r.change.Handle
137 case r.changeID != "":
138 return r.changeID[:min(8, len(r.changeID))]
139 }
140 return "agent:" + shortRunID(r.state().ID)
141}
142
143// pushedRun is the run whose push the row shows: a change's current run, or
144// a bare pushed run. nil for a row with none, as for a change whose active
145// version was marked ready elsewhere.
146func (r dashRow) pushedRun() *run.State {
147 switch {
148 case r.changeID != "":
149 return r.current
150 case r.pushed:
151 return r.runs[0]
152 }
153 return nil
154}
155
156// description is what the row is about: a valley change's title, else the
157// subject of the head its current run pushed, else the prompt.
158func (r dashRow) description() string {
159 if r.change != nil && r.change.Title != "" {
160 return r.change.Title
161 }
162 if r.current != nil && r.current.PushedSubject != "" {
163 return r.current.PushedSubject
164 }
165 return r.state().Prompt
166}
167
168// buildRows turns the run states into dashboard rows, sorted by category
169// (yours, agents, pipeline, done) and most recent first within each
170// category. Sessions are excluded; agents on the same PR share a row, a PR
171// named by the owner/repo of its URL and its number (prKey), so
172// alice/widget#7 and bob/widget#7 never share one, whatever the project
173// registry calls their repos. The
174// runs without a PR on one change (changeKeys) share a row across repo
175// groups: the row of the change's PR, the PR of the newest run on the
176// change that has one, after the PR's own agents, unless where the change
177// stands is the operator's to act on by itself (changeStandsAlone); else
178// the change's own row.
179func (m dashboardModel) buildRows() []dashRow {
180 var rows []dashRow
181 groups := groupByRepo(m.states)
182 changeOf := changeKeys(m.states)
183 prOfChange := make(map[integration.ChangeKey]int) // the row of a change's PR
184 prOwner := make(map[integration.ChangeKey]*run.State) // the newest run with a PR on each change
185 prIndex := make(map[string]int) // the row of each PR, by its key
186 for _, g := range groups {
187 for _, s := range g.Runs {
188 prNum := extractPRNumber(s)
189 if prNum == "" {
190 continue
191 }
192 key := prKey(s, g.Repo, prNum)
193 i, ok := prIndex[key]
194 if ok {
195 rows[i].runs = append(rows[i].runs, s)
196 } else {
197 i = len(rows)
198 prIndex[key] = i
199 rows = append(rows, dashRow{
200 key: key,
201 repo: g.Repo,
202 prNum: prNum,
203 runs: []*run.State{s},
204 ps: m.ghStatus[extractPRRef(s)],
205 })
206 }
207 if k, ok := changeOf(s); ok && (prOwner[k] == nil || createdBefore(prOwner[k], s)) {
208 prOfChange[k], prOwner[k] = i, s
209 }
210 }
211 }
212 // The runs without a PR on each change, and the repo group of each
213 // change's first.
214 var changeKeys []integration.ChangeKey
215 changeRuns := make(map[integration.ChangeKey][]*run.State)
216 changeRepo := make(map[integration.ChangeKey]string)
217 for _, g := range groups {
218 for _, s := range g.Runs {
219 if extractPRNumber(s) != "" {
220 continue
221 }
222 k, ok := changeOf(s)
223 if !ok {
224 rows = append(rows, dashRow{key: "run:" + s.ID, repo: g.Repo, runs: []*run.State{s}})
225 continue
226 }
227 if _, seen := changeRuns[k]; !seen {
228 changeKeys = append(changeKeys, k)
229 changeRepo[k] = g.Repo
230 }
231 changeRuns[k] = append(changeRuns[k], s)
232 }
233 }
234 for _, k := range changeKeys {
235 if i, ok := prOfChange[k]; ok && !m.changeStandsAlone(changeRuns[k]) {
236 rows[i].runs = append(rows[i].runs, changeRuns[k]...)
237 continue
238 }
239 rows = append(rows, dashRow{
240 key: "change:" + k.Repo + "#" + k.ChangeID,
241 repo: changeRepo[k],
242 changeID: k.ChangeID,
243 runs: changeRuns[k],
244 })
245 }
246 superseded := supersededRuns(m.states, m.agentRunning)
247 for i := range rows {
248 if rows[i].changeID != "" {
249 runs := rows[i].runs
250 sort.SliceStable(runs, func(a, b int) bool { return createdBefore(runs[b], runs[a]) })
251 }
252 m.classify(&rows[i], superseded)
253 }
254 sort.SliceStable(rows, func(i, j int) bool {
255 a, b := rows[i], rows[j]
256 if a.category != b.category {
257 return a.category < b.category
258 }
259 if !a.lastSeen.Equal(b.lastSeen) {
260 return a.lastSeen.After(b.lastSeen)
261 }
262 return a.key < b.key
263 })
264 return rows
265}
266
267// prKey is the row key of the PR numbered prNum that run s has: "pr:", the
268// owner/repo of its URL, lowercased as GitHub matches them, "#" and the
269// number. A URL without an owner/repo falls back on the run's repo group.
270func prKey(s *run.State, group, prNum string) string {
271 repo := strings.ToLower(gh.OwnerRepoFromPRURL(extractPRRef(s)))
272 if repo == "" {
273 repo = group
274 }
275 return "pr:" + repo + "#" + prNum
276}
277
278// changeStandsAlone reports whether where a change stands, apart from its
279// PR, is the operator's to act on by itself, so its runs without a PR keep
280// the change's own row rather than folding into the PR's: a valley lists
281// the change and its active version hasn't settled (a version to approve,
282// or one the integrator turned down), or one of those runs pushed a branch
283// that waits for integration, as far as its latest check knows. A push
284// that landed or is gone folds in. runs are the change's runs without a PR.
285func (m dashboardModel) changeStandsAlone(runs []*run.State) bool {
286 if view, ok := m.changes[valleyKey(runs[0])]; ok && view.Change != nil && !view.Verdict.Settled() {
287 return true
288 }
289 for _, s := range runs {
290 if awaitsIntegration(s) && !m.integration[s.ID].Verdict.Settled() {
291 return true
292 }
293 }
294 return false
295}
296
297// classify fills in a row's running agents, category, recency and whether
298// it may be hidden once old. A change row is judged by where the change
299// stands (placeChange). A run's need for attention (needsAttention) stops
300// counting once a later run took its work on (superseded): that run
301// carries it, and shows it if it in turn ended needing attention.
302// Precedence: a running agent makes it the agents'; then salvaged work no
303// PR holds (any on a change, a run without a PR on a PR's row), or
304// attention a run on a PR's row took on with other runs' work (TookOver),
305// makes it yours; then merged, closed, no access, integrated, gone,
306// withdrawn or superseded make it done; then needs attention (a run's, a
307// stalled PR's, or a restack conflict klaus stopped short of resolving), a pushed
308// branch (to approve, review or submit, a draft, or whose change the
309// integrator turned down or the valley is unsure of) or a PR ready to
310// approve make it yours, except a change already approved, which is the
311// pipeline's like any other open PR; an exited agent is done.
312func (m dashboardModel) classify(r *dashRow, superseded map[string]bool) {
313 merged, attention, owed := false, false, false
314 if r.changeID != "" {
315 m.placeChange(r)
316 if v, ok := m.restacks[valleyKey(r.runs[0])]; ok {
317 r.restack = &v
318 // klaus stopped short of resolving it: the operator's.
319 attention = v.State == restack.StateStopped || v.State == restack.StateRefused || v.State == restack.StateHeld
320 }
321 }
322 for _, s := range r.runs {
323 if m.agentRunning(s) {
324 r.running = append(r.running, s)
325 }
326 if s.MergedAt != nil {
327 merged = true
328 }
329 if needsAttention(s) && !superseded[s.ID] {
330 attention = true
331 owed = owed || r.prNum != "" && (s.PRURL == nil || len(s.TookOver) > 0)
332 }
333 if t := runLastActivity(s); t.After(r.lastSeen) {
334 r.lastSeen = t
335 }
336 }
337 owed = owed || r.changeID != "" && attention
338 closed, noAccess := false, false
339 if r.ps != nil {
340 merged = merged || r.ps.State == "MERGED"
341 closed = r.ps.State == "CLOSED"
342 noAccess = r.ps.State == gh.StateNoAccess
343 }
344 if pps, ok := m.pipelineState(*r); ok {
345 merged = merged || pps.Stage == pipeline.StageMerged
346 attention = attention || pps.Stage == pipeline.StageStalled || pps.Stage == pipeline.StageBudgetPaused
347 }
348 if r.prNum == "" && r.changeID == "" && awaitsIntegration(r.runs[0]) {
349 r.pushed = true
350 r.verdict, r.change, r.outdated = m.runView(r.runs[0])
351 }
352 r.review = r.pushed && r.change != nil && awaitsReview(r.pushedRun(), r.verdict)
353 if r.review {
354 r.reviewSince = m.clock.since(r.pushedRun(), "awaiting-review", r.change.Head)
355 }
356
357 switch {
358 case len(r.running) > 0:
359 r.category = catAgents
360 case owed:
361 // Salvaged work that no later run took on, and that no PR holds,
362 // is the operator's, whatever became of the change's PR or
363 // version. So is the attention a run took on with other runs'
364 // work and didn't hand on: its PR merged, closed or out of reach
365 // settles nothing about it.
366 r.category = catYours
367 r.attention = true
368 case merged || closed || noAccess || r.verdict.Settled():
369 r.category = catDone
370 r.hideable = true
371 switch {
372 case merged:
373 r.finished = "merged"
374 case closed:
375 r.finished = "closed"
376 default:
377 r.finished = finishedVerdict(r.verdict)
378 }
379 case attention:
380 r.category = catYours
381 r.attention = true
382 case r.pushed && r.verdict == integration.Approved && !r.review:
383 // Approved, and approved with its checks pending, wait on the
384 // integrator.
385 r.category = catPipeline
386 case r.pushed:
387 // A pushed branch waits for the operator to approve or submit it, or
388 // to look at what became of it, as far as anyone knows: Unknown (or
389 // no check yet) is provisional. A draft awaiting review waits on
390 // the coordinator, who reviews it and marks it ready with valley
391 // flow ready, as valley flow queue lists it.
392 r.category = catYours
393 r.provisional = r.verdict == integration.Unknown && !r.review
394 case r.prNum == "":
395 r.category = catDone
396 // A bare agent or change is hideable once its worktrees have been
397 // cleaned up.
398 r.hideable = true
399 for _, s := range r.runs {
400 r.hideable = r.hideable && s.Worktree == ""
401 }
402 case r.readyToApprove():
403 r.category = catYours
404 default:
405 r.category = catPipeline
406 }
407}
408
409// changeKeys returns changeOf for the runs among states: the change a run
410// belongs to, named by its repo and its change ID; a tracked valley change
411// (integration.TracksChange) belongs to the change it names. ok is false for
412// a session or tracked PR, and for a run without a change ID or a known
413// repo: such a run shares its change with none.
414//
415// The repo is the name the ValleyChecker places runs with
416// (integration.RepoName: the valley's name for a valley's repo, else the
417// short name of the target repo), qualified by the GitHub owner the run's
418// repo is known by (repoOwner), so the same change ID in alice/widget and
419// bob/widget names two changes. A run whose owner isn't known (a valley's
420// repo, or a target named by its short name) takes the owner the other runs
421// of its change are known by when there is exactly one, and none otherwise.
422// A valley's listing names the change by the valley's repo name alone
423// (valleyKey).
424func changeKeys(states []*run.State) func(*run.State) (integration.ChangeKey, bool) {
425 owners := make(map[integration.ChangeKey]map[string]bool) // the owners each change's runs are known by
426 for _, s := range states {
427 k, ok := nameChange(s)
428 if o := repoOwner(s); ok && o != "" {
429 if owners[k] == nil {
430 owners[k] = make(map[string]bool)
431 }
432 owners[k][o] = true
433 }
434 }
435 return func(s *run.State) (integration.ChangeKey, bool) {
436 k, ok := nameChange(s)
437 if !ok {
438 return k, false
439 }
440 o := repoOwner(s)
441 if o == "" && len(owners[k]) == 1 {
442 for only := range owners[k] {
443 o = only
444 }
445 }
446 if o != "" {
447 k.Repo = o + "/" + k.Repo
448 }
449 return k, true
450 }
451}
452
453// nameChange is a run's change by its repo's name alone, as a valley's
454// listing names it; ok as for changeKeys.
455func nameChange(s *run.State) (integration.ChangeKey, bool) {
456 if s.Type == "session" || s.Type == "track" && !integration.TracksChange(s) || s.ChangeID == "" {
457 return integration.ChangeKey{}, false
458 }
459 k := valleyKey(s)
460 return k, k.Repo != ""
461}
462
463// repoOwner is the GitHub owner a run's repo is known by, lowercased: from
464// its PR's URL, else from its RepoKey or its target repo when either is
465// owner/repo. "" when none is, as for a valley's repo.
466func repoOwner(s *run.State) string {
467 slug := ""
468 if s.PRURL != nil {
469 slug = gh.OwnerRepoFromPRURL(*s.PRURL)
470 }
471 for _, ref := range []string{s.RepoKey, deref(s.TargetRepo)} {
472 if slug == "" && ownerRepoRegex.MatchString(ref) {
473 slug = ref
474 }
475 }
476 owner, _, _ := strings.Cut(slug, "/")
477 return strings.ToLower(owner)
478}
479
480// ownerRepoRegex matches a GitHub owner/repo, and not a path, a URL or a
481// valley:<name> key.
482var ownerRepoRegex = regexp.MustCompile(`^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$`)
483
484// deref is *p, or "" for nil.
485func deref(p *string) string {
486 if p == nil {
487 return ""
488 }
489 return *p
490}
491
492// valleyKey is how a valley's listing names a run's change: by the repo
493// name the ValleyChecker places runs with (integration.RepoName).
494func valleyKey(s *run.State) integration.ChangeKey {
495 return integration.ChangeKey{Repo: integration.RepoName(s), ChangeID: s.ChangeID}
496}
497
498// needsAttention reports whether a run ended needing the operator: finalize
499// salvaged its work, or it failed after taking on the work of runs that
500// needed attention (TookOver), whose attention is now its own.
501func needsAttention(s *run.State) bool {
502 return s.NeedsAttention != nil || s.FailureReason != nil && len(s.TookOver) > 0
503}
504
505// supersededRuns returns the IDs of the runs whose need for attention was
506// handed off: a run of the same change records that it took their pushed
507// work on (TookOver), and it is running or finished, so it carries that
508// attention from then on. A successor that ended needing attention or
509// failing is flagged itself (needsAttention); one that never finished and
510// isn't running hands nothing off. Creation times play no part. Two runs
511// that each record taking the other's work on hand nothing off to each
512// other. The superseded runs' records stay as they are.
513func supersededRuns(states []*run.State, running func(*run.State) bool) map[string]bool {
514 changeOf := changeKeys(states)
515 byID := make(map[string]*run.State, len(states))
516 for _, s := range states {
517 byID[s.ID] = s
518 }
519 out := make(map[string]bool)
520 for _, b := range states {
521 bk, ok := changeOf(b)
522 if !ok || len(b.TookOver) == 0 || !(running(b) || b.CostUSD != nil || b.DurationMS != nil) {
523 continue
524 }
525 for _, id := range b.TookOver {
526 a := byID[id]
527 if a == nil || a == b || !needsAttention(a) || slices.Contains(a.TookOver, b.ID) {
528 continue
529 }
530 if ak, ok := changeOf(a); ok && ak == bk {
531 out[id] = true
532 }
533 }
534 }
535 return out
536}
537
538// runView is where a pushed run stands by its latest check: the verdict, the
539// valley's view of its version (else what finalize recorded), and whether
540// that view is from an earlier check.
541func (m dashboardModel) runView(s *run.State) (integration.Verdict, *integration.Change, bool) {
542 res := m.integration[s.ID]
543 if res.Change == nil {
544 return res.Verdict, integration.RecordedChange(s), res.Outdated
545 }
546 return res.Verdict, res.Change, res.Outdated
547}
548
549// placeChange fills in where a change row stands. When the valley lists the
550// change, its view of the change's active version decides: the verdict, the
551// version, and the head to approve, wherever that version was marked ready.
552// The current run is then the local run that pushed that head, if any; a
553// later local push the valley doesn't hold as a version is only noted
554// (unplaced). When the valley doesn't list the change (a repo with no
555// valley, or an outage before the dashboard got a view), the latest run
556// that pushed holds the state, as it would on its own; with none, a tracked
557// change stands as klaus track found it, provisionally. runs are newest
558// first.
559func (m dashboardModel) placeChange(r *dashRow) {
560 var latest, tracked *run.State
561 for _, s := range r.runs {
562 if latest == nil && awaitsIntegration(s) {
563 latest = s
564 }
565 if tracked == nil && integration.TracksChange(s) {
566 tracked = s
567 }
568 }
569 view, ok := m.changes[valleyKey(r.runs[0])]
570 if !ok || view.Change == nil {
571 if r.current = latest; latest != nil {
572 r.pushed = true
573 r.verdict, r.change, r.outdated = m.runView(latest)
574 } else if tracked != nil {
575 r.pushed, r.change = true, integration.TrackedChange(tracked)
576 }
577 return
578 }
579 r.pushed = true
580 r.verdict, r.change, r.outdated = view.Verdict, view.Change, view.Outdated
581 for _, s := range r.runs {
582 if awaitsIntegration(s) && *s.PushedSHA == view.Change.Head {
583 r.current = s
584 break
585 }
586 }
587 if latest != nil && latest != r.current {
588 if res, checked := m.integration[latest.ID]; checked && res.Change == nil && integration.RecordedChange(latest) == nil {
589 r.unplaced = *latest.PushedSHA
590 }
591 }
592 // A view kept through an outage gives way to git finding the active
593 // version landed, as a run's own view does (keepValleyViews).
594 if r.outdated && r.current != nil {
595 if res := m.integration[r.current.ID]; res.Change == nil && res.Verdict.Landed() {
596 r.verdict, r.outdated = res.Verdict, false
597 }
598 }
599}
600
601// pipelineState returns the pipeline's state for a PR row. The pipeline
602// keys PRs by number alone, so a state counts only if it tracks this row's
603// PR, not a same-numbered PR in another repo.
604func (m dashboardModel) pipelineState(r dashRow) (*pipeline.PRPipelineState, bool) {
605 pps, ok := m.pipelineStates[r.prNum]
606 if !ok || r.prNum == "" {
607 return nil, false
608 }
609 for _, s := range r.runs {
610 if extractPRRef(s) == pps.PRURL {
611 return pps, true
612 }
613 }
614 return nil, false
615}
616
617// readyToApprove reports whether a PR row waits on the operator's approval:
618// open, not a draft, ready to merge, and not yet approved with klaus approve.
619func (r dashRow) readyToApprove() bool {
620 ps := r.ps
621 return ps != nil && ps.State == "OPEN" && !ps.Draft &&
622 computeMergeStatus(ps.CI, ps.Conflicts, ps.ReviewDecision, ps.BehindBy) == "ready" &&
623 !isAnyRunApproved(r.runs)
624}
625
626// awaitsIntegration reports whether a run finished by pushing its branch,
627// with nothing else (a running agent aside) deciding how it is shown: no PR,
628// no merge and nothing needing attention. Only such runs get an integration
629// check.
630func awaitsIntegration(s *run.State) bool {
631 return s.Type != "session" && s.Type != "track" && integration.Applies(s) &&
632 s.PRURL == nil && s.MergedAt == nil && s.NeedsAttention == nil
633}
634
635// runLastActivity returns the latest time known for a run: its creation,
636// finish (creation plus duration), approval or merge.
637func runLastActivity(s *run.State) time.Time {
638 var latest time.Time
639 consider := func(t time.Time) {
640 if t.After(latest) {
641 latest = t
642 }
643 }
644 if t, err := time.Parse(time.RFC3339, s.CreatedAt); err == nil {
645 consider(t)
646 if s.DurationMS != nil && *s.DurationMS > 0 {
647 consider(t.Add(time.Duration(*s.DurationMS) * time.Millisecond))
648 }
649 }
650 for _, ts := range []*string{s.ApprovedAt, s.MergedAt} {
651 if ts == nil {
652 continue
653 }
654 if t, err := time.Parse(time.RFC3339, *ts); err == nil {
655 consider(t)
656 }
657 }
658 return latest
659}
660
661// noteFinished records when a row the dashboard watched while it was still in
662// progress is first seen done. A PR merged on GitHub has no local merge time,
663// and a branch integrated on origin has no local time at all, so this keeps
664// such a row visible for the full threshold after the dashboard saw it finish
665// instead of hiding it at once. A SUBMIT row without a definite integration
666// verdict doesn't count as watched: until the first check it may be work
667// that landed long ago.
668func (m *dashboardModel) noteFinished(rows []dashRow, now time.Time) {
669 if m.seenUnfinished == nil {
670 m.seenUnfinished = make(map[string]bool)
671 }
672 if m.finishedAt == nil {
673 m.finishedAt = make(map[string]time.Time)
674 }
675 for _, r := range rows {
676 if r.category != catDone {
677 if !r.provisional {
678 m.seenUnfinished[r.key] = true
679 }
680 delete(m.finishedAt, r.key)
681 continue
682 }
683 if _, ok := m.finishedAt[r.key]; !ok && m.seenUnfinished[r.key] {
684 m.finishedAt[r.key] = now
685 }
686 }
687}
688
689// isHidden reports whether a row is an old done row that the dashboard hides
690// until "show all" is toggled. Rows in yours, agents and pipeline are never
691// hidden.
692func (m dashboardModel) isHidden(r dashRow, now time.Time) bool {
693 if m.showAll || m.hideAfter <= 0 || r.category != catDone || !r.hideable {
694 return false
695 }
696 finished := r.lastSeen
697 if t, ok := m.finishedAt[r.key]; ok && t.After(finished) {
698 finished = t
699 }
700 return now.Sub(finished) > m.hideAfter
701}
702
703// dashView is the resolved state of the run list for one render: the rows on
704// display, how many fit, and which one is selected and scrolled to.
705type dashView struct {
706 all []dashRow // every row, including hidden ones
707 rows []dashRow // rows on display, in order
708 hidden int // rows hidden as old done rows
709 chrome []chromeItem
710 bodyH int // rows that fit in the viewport
711 cursor int // index into rows of the selected row
712 offset int // index into rows of the first row in the viewport
713 // jobs are the jobs section's listed jobs; the first jobsShown fit the
714 // pane. prose counts finished prose passes in the window. jobFocus says
715 // one of those listed jobs is selected, jobs[jobCursor], rather than a
716 // row.
717 jobs []*jobs.Job
718 prose proseSummary
719 jobsShown int
720 jobCursor int
721 jobFocus bool
722}
723
724// resolve builds the rows, fits the layout to the pane and resolves the
725// selection and scroll position.
726func (m dashboardModel) resolve(now time.Time) dashView {
727 return m.resolveRows(m.buildRows(), now)
728}
729
730func (m dashboardModel) resolveRows(all []dashRow, now time.Time) dashView {
731 v := dashView{all: all}
732 for _, r := range all {
733 if m.isHidden(r, now) {
734 v.hidden++
735 continue
736 }
737 v.rows = append(v.rows, r)
738 }
739 v.jobs, v.prose = m.recentJobView(now)
740 v.chrome, v.bodyH = m.fitLayout(len(v.rows), len(v.jobs), v.prose.total > 0)
741 for _, c := range v.chrome {
742 if c.kind == chromeJob {
743 v.jobsShown++
744 }
745 }
746 v.jobCursor = clampCursor(m.jobCursor, v.jobsShown)
747 for i := 0; i < v.jobsShown; i++ {
748 if v.jobs[i].ID == m.jobSel {
749 v.jobCursor = i
750 break
751 }
752 }
753 v.jobFocus = m.jobFocus && v.jobsShown > 0
754
755 v.cursor = clampCursor(m.cursor, len(v.rows))
756 for i, r := range v.rows {
757 if r.key == m.selKey {
758 v.cursor = i
759 break
760 }
761 }
762 v.offset = scrollOffset(m.offset, v.cursor, len(v.rows), v.bodyH)
763 return v
764}
765
766// syncView re-resolves the list after anything that can change it, so the
767// selection stays on the same row and in view when rows reorder, appear or
768// disappear. If the selected row is gone, the selection stays at the same
769// position, clamped to the list.
770func (m *dashboardModel) syncView(now time.Time) {
771 all := m.buildRows()
772 m.noteFinished(all, now)
773 v := m.resolveRows(all, now)
774 m.setSelection(v, v.cursor, v.offset)
775 // The selected job likewise, while one is.
776 m.jobFocus, m.jobCursor, m.jobSel = v.jobFocus, v.jobCursor, ""
777 if v.jobsShown > 0 {
778 m.jobSel = v.jobs[v.jobCursor].ID
779 }
780}
781
782// setSelection selects rows[cursor] and scrolls from offset just enough to
783// keep it visible.
784func (m *dashboardModel) setSelection(v dashView, cursor, offset int) {
785 if len(v.rows) == 0 {
786 m.cursor, m.offset, m.selKey = 0, 0, ""
787 return
788 }
789 m.cursor = clampCursor(cursor, len(v.rows))
790 m.selKey = v.rows[m.cursor].key
791 m.offset = scrollOffset(offset, m.cursor, len(v.rows), v.bodyH)
792}
793
794// moveSelection moves the selection by delta rows plus pages viewport pages,
795// turning the viewport by the same number of pages.
796func (m *dashboardModel) moveSelection(delta, pages int) {
797 v := m.resolve(time.Now())
798 page := pages * max(v.bodyH, 1)
799 m.setSelection(v, v.cursor+delta+page, v.offset+page)
800}
801
802// selectEdge selects the first or last row.
803func (m *dashboardModel) selectEdge(last bool) {
804 v := m.resolve(time.Now())
805 if last {
806 m.setSelection(v, len(v.rows)-1, len(v.rows))
807 return
808 }
809 m.setSelection(v, 0, 0)
810}
811
812// scrollOffset returns the first row to show so that the cursor row is
813// visible, starting from offset and moving as little as possible. A
814// non-positive height means the pane height is unknown and everything shows.
815func scrollOffset(offset, cursor, n, height int) int {
816 if height <= 0 || n <= height {
817 return 0
818 }
819 if cursor < offset {
820 offset = cursor
821 }
822 if cursor >= offset+height {
823 offset = cursor - height + 1
824 }
825 return clamp(offset, 0, n-height)
826}
827
828// clampCursor keeps a cursor index within [0, n-1]; it returns 0 when the list
829// is empty.
830func clampCursor(cursor, n int) int {
831 if n <= 0 {
832 return 0
833 }
834 if cursor < 0 {
835 return 0
836 }
837 if cursor >= n {
838 return n - 1
839 }
840 return cursor
841}
842
843// selectedRow returns the currently selected row.
844func (m dashboardModel) selectedRow() (dashRow, bool) {
845 v := m.resolve(time.Now())
846 if len(v.rows) == 0 {
847 return dashRow{}, false
848 }
849 return v.rows[v.cursor], true
850}
851
852// selectedPR returns the selected row if it is a PR, noting a hint when the
853// selection is a bare agent that has no PR to act on.
854func (m *dashboardModel) selectedPR(action string) (dashRow, bool) {
855 r, ok := m.selectedRow()
856 if !ok {
857 return dashRow{}, false
858 }
859 if r.prNum == "" {
860 m.noteError(fmt.Sprintf("%s: %s has no PR", action, r.idLabel()))
861 return dashRow{}, false
862 }
863 return r, true
864}
865
866// coordinatorPane returns the tmux pane id of the coordinator (Claude) session
867// for the current dashboard, or "" if it can't be determined (e.g. an older
868// session that predates the persisted coordinator pane).
869func (m dashboardModel) coordinatorPane() string {
870 sessionID := os.Getenv(sessionIDEnv)
871 if sessionID == "" {
872 return ""
873 }
874 st, err := m.store.Load(sessionID)
875 if err != nil || st == nil || st.CoordinatorPane == nil {
876 return ""
877 }
878 return *st.CoordinatorPane
879}
880
881// discussPR sends a literal "WRT PR#<num>: " prompt prefix to the coordinator
882// pane and switches tmux focus there. It deliberately does not send a newline —
883// the user finishes and submits the prompt manually.
884func (m dashboardModel) discussPR(prNum, pane string) error {
885 ctx := context.Background()
886 if err := m.tmux.SendKeys(ctx, pane, fmt.Sprintf("WRT PR#%s: ", prNum)); err != nil {
887 return err
888 }
889 return m.tmux.SelectPane(ctx, pane)
890}
891
892// noteError appends a transient error line to the dashboard, keeping only the
893// most recent few.
894func (m *dashboardModel) noteError(msg string) {
895 m.recentErrors = append(m.recentErrors, dashboardError{Time: time.Now(), Message: msg})
896 if len(m.recentErrors) > 3 {
897 m.recentErrors = m.recentErrors[len(m.recentErrors)-3:]
898 }
899}