gunk-dev/the-valley

dashboard_select.go

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