gunk-dev/the-valley

dashboard_select.go

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