gunk-dev/the-valley

dashboard_commands.go

source30e24c82839bmain's published tip history
15.2 KiB
1package cmd
2
3import (
4 "context"
5 "fmt"
6 "log/slog"
7 "os"
8 "path/filepath"
9 "time"
10
11 tea "github.com/charmbracelet/bubbletea"
12 "github.com/fsnotify/fsnotify"
13 "the-valley/flow/internal/config"
14 "the-valley/flow/internal/event"
15 "the-valley/flow/internal/integration"
16 "the-valley/flow/internal/pipeline"
17 "the-valley/flow/internal/restack"
18 "the-valley/flow/internal/run"
19 "the-valley/flow/internal/webhook"
20)
21
22// Messages for the bubbletea event loop.
23
24type statesLoadedMsg struct {
25 states []*run.State
26 cleared run.Cleared // the runs cleanup removed
27}
28
29type ghStatusMsg struct {
30 statuses map[string]*prStatus // keyed by PR URL
31 // rateLimitedUntil is when GitHub lets polling resume; zero when it
32 // isn't rate-limited.
33 rateLimitedUntil time.Time
34}
35
36// integrationTickMsg starts an integration check of pushed runs, unless a
37// later check re-armed the timer: seq is the arming it came from.
38type integrationTickMsg struct{ seq int }
39
40// integrationMsg carries the results of an integration check, by run ID.
41type integrationMsg struct {
42 results map[string]integration.Result
43 changes map[integration.ChangeKey]integration.Result
44 // restacks is where each restack conflict on a change klaus owns
45 // stands after the check's restack pass; nil when none ran.
46 restacks map[integration.ChangeKey]restack.View
47 // valleyErr is why the check couldn't ask the valley; "" when it could.
48 valleyErr string
49}
50
51type fsEventMsg struct{}
52
53type tickMsg struct{}
54
55// reconcileTickMsg fires the slow reconcile heartbeat in webhook-only mode.
56type reconcileTickMsg struct{}
57
58type sandboxStatusMsg struct {
59 hosts map[string]bool // host -> reachable
60}
61
62type pipelineActionMsg struct {
63 actions []pipeline.Action
64}
65
66type errMsg struct {
67 err error
68}
69
70// errHintMsg carries a transient, non-fatal hint to surface in the dashboard
71// (via the recentErrors strip) without triggering the fatal error screen that
72// errMsg does. Used by best-effort background actions like opening a browser.
73type errHintMsg struct {
74 msg string
75}
76
77type webhookMsg struct {
78 event webhook.Event
79}
80
81// webhookClosedMsg signals that the webhook event channel was closed, so live
82// webhook consumption has stopped. Surfaced as a non-fatal error in the TUI.
83type webhookClosedMsg struct{}
84
85// internalEventMsg delivers a klaus-emitted event (e.g. PRApprovalChanged
86// from `klaus approve`) into the dashboard's Update loop. Internal events
87// are treated as invalidation signals — the dashboard reacts by re-fetching
88// PR status, mirroring how it reacts to a real GitHub webhook.
89type internalEventMsg struct {
90 event event.Event
91}
92
93type trustedCommentsMsg struct {
94 prURL string
95 hasNewTrustedComments bool
96}
97
98// prStatus holds the GitHub-fetched status for a single PR.
99type prStatus struct {
100 PRNumber string
101 State string // OPEN, MERGED, CLOSED or NOACCESS (gh.StateNoAccess)
102 Draft bool
103 HeadSHA string
104 CI string // passing, failing, pending, unknown
105 Conflicts string // yes, none, unknown
106 BehindBy int // commits base has that head lacks; >0 = stale-but-mergeable
107 ReviewDecision string // APPROVED, CHANGES_REQUESTED, etc.
108 HasNewTrustedComments bool // unaddressed comments from trusted reviewers
109 TrustedFeedbackAt time.Time // when trusted reviewers last left feedback
110 Labels []string // applied PR labels (used to surface klaus:budget-paused)
111}
112
113// Commands for the bubbletea event loop.
114
115func loadStatesCmd(store run.StateStore) tea.Cmd {
116 return func() tea.Msg {
117 states, err := store.List()
118 if err != nil {
119 return errMsg{err: err}
120 }
121 cleared, _ := clearedOf(store, states)
122 return statesLoadedMsg{states: states, cleared: cleared}
123 }
124}
125
126// noAccessRecheck is how long a PR the agent can't read goes without being
127// queried again, so a fixed credential recovers on its own without the
128// dashboard asking GitHub about it on every poll.
129const noAccessRecheck = 30 * time.Minute
130
131// fetchGHStatusCmd fetches the GitHub status of every PR the states refer
132// to, keyed by PR URL so equal PR numbers in different repos don't collide.
133// PRs last found unreadable less than noAccessRecheck ago are skipped; their
134// NOACCESS status stays in place. A PR the pipeline's ledger has seen merged
135// or closed isn't asked about again, even after a restart; its status comes
136// from the ledger.
137func (m dashboardModel) fetchGHStatusCmd(states []*run.State) tea.Cmd {
138 skip := make(map[string]bool)
139 now := time.Now()
140 for url, at := range m.noAccessAt {
141 if now.Sub(at) < noAccessRecheck {
142 skip[url] = true
143 }
144 }
145 settled := func(string) string { return "" }
146 if m.pipelineCtrl != nil {
147 settled = m.pipelineCtrl.Settled
148 }
149 return fetchGHStatusCmd(m.ghPoller, settled, states, skip)
150}
151
152func fetchGHStatusCmd(p *ghPoller, settled func(prURL string) string, states []*run.State, skip map[string]bool) tea.Cmd {
153 var prs []trackedPR
154 done := make(map[string]*prStatus)
155 seen := make(map[string]bool)
156 for _, s := range states {
157 url := extractPRRef(s)
158 if url == "" || skip[url] || seen[url] {
159 continue
160 }
161 seen[url] = true
162 if state := settled(url); state != "" {
163 done[url] = &prStatus{PRNumber: extractPRNumber(s), State: state}
164 continue
165 }
166 prs = append(prs, trackedPR{url: url, number: extractPRNumber(s)})
167 }
168 return func() tea.Msg {
169 statuses, until := p.poll(context.TODO(), prs)
170 for url, ps := range done {
171 statuses[url] = ps
172 }
173 return ghStatusMsg{statuses: statuses, rateLimitedUntil: until}
174 }
175}
176
177// integrationInterval is how often the dashboard checks whether pushed runs
178// have landed. It is independent of GitHub polling. Where a valley host's
179// telemetry can be followed, a check also starts as soon as the host reports
180// a decision or new evidence (valleyWaker), and the interval is the fallback.
181const integrationInterval = time.Minute
182
183// integrationTimeout bounds one integration check.
184const integrationTimeout = 5 * time.Minute
185
186// checkIntegrationCmd checks, in the background, the runs that are waiting
187// for their pushed branch to be integrated, and the tracked valley changes.
188// With a ValleyChecker that is at most one `valley changes` for all of them. Then, with a store, it settles
189// the knots of runs whose change the check found landed (settleKnots).
190// With a change ledger and a session directory, it emits the transitions
191// the valley's listing shows for those runs' changes (reportChangeTransitions).
192// With restacks and a session directory, it then runs a restack pass, as
193// klaus restack-conflicts does, dispatching resolution runs for the restack
194// conflicts on changes klaus owns: on the check's valley listing, or, when
195// the check asked no valley, listing each repo itself; a valley the check
196// couldn't ask isn't asked again. With a listing it then runs a checks
197// pass, as klaus failed-checks does, dispatching fix runs for the failed
198// checks of ready changes klaus owns. The next
199// check starts only once this one is done, so no two settle a knot, or
200// dispatch, at once.
201func checkIntegrationCmd(checker integration.Checker, states []*run.State, store run.StateStore, ledger *pipeline.ChangeLedger, restacks bool) tea.Cmd {
202 if checker == nil {
203 return nil
204 }
205 var pushed []*run.State
206 for _, s := range states {
207 if awaitsIntegration(s) || integration.TracksChange(s) {
208 cp := *s // the check runs off the Update goroutine
209 pushed = append(pushed, &cp)
210 }
211 }
212 return func() tea.Msg {
213 ctx, cancel := context.WithTimeout(context.Background(), integrationTimeout)
214 defer cancel()
215 rep := checker.Check(ctx, pushed)
216 if store != nil {
217 settleKnots(ctx, store, pushed, rep.Runs, rep.Changes)
218 }
219 hds, ok := store.(*run.HomeDirStore)
220 if ok && ledger != nil && rep.Listing != nil {
221 reportChangeTransitions(hds, ledger, pushed, rep.Listing)
222 }
223 msg := integrationMsg{results: rep.Runs, changes: rep.Changes, valleyErr: rep.ValleyErr}
224 if ok && restacks && (rep.Listing != nil || !rep.Asked) {
225 views, err := restackPass(ctx, hds, rep.Listing, true)
226 if err != nil {
227 slog.Warn("restack pass failed", "err", err)
228 }
229 msg.restacks = restackViews(views)
230 }
231 if ok && restacks && rep.Listing != nil {
232 if _, err := checksPass(ctx, hds, rep.Listing); err != nil {
233 slog.Warn("checks pass failed", "err", err)
234 }
235 }
236 return msg
237 }
238}
239
240// startIntegrationCheck starts an integration check of the model's runs. The
241// model notes it runs until its integrationMsg arrives, so a wake meanwhile
242// asks for one more check after it rather than one beside it.
243func (m dashboardModel) startIntegrationCheck() (dashboardModel, tea.Cmd) {
244 cmd := checkIntegrationCmd(m.checker, m.states, m.store, m.changeLedger, m.restackOn)
245 m.checking = cmd != nil
246 return m, cmd
247}
248
249// keepValleyViews returns a check's results, except where the valley placed
250// a run before and git judged it now (the valley couldn't be asked, or
251// couldn't read the repo): unless git found it landed, the run keeps the
252// valley's last view, marked Outdated. A valley outage then leaves an
253// uncertain or rejected change where it was instead of showing it as ready
254// to approve, or as done because its branch went away.
255func keepValleyViews(prev, next map[string]integration.Result) map[string]integration.Result {
256 for id, r := range next {
257 if old, ok := prev[id]; ok && old.Change != nil && r.Change == nil && !r.Verdict.Landed() {
258 old.Outdated = true
259 next[id] = old
260 }
261 }
262 return next
263}
264
265// keepChangeViews does for the valley's views of changes what keepValleyViews
266// does for runs': a change the latest check has no view of (the valley
267// couldn't be asked, or couldn't read its repo) keeps its last view, marked
268// Outdated.
269func keepChangeViews(prev, next map[integration.ChangeKey]integration.Result) map[integration.ChangeKey]integration.Result {
270 if next == nil {
271 next = make(map[integration.ChangeKey]integration.Result)
272 }
273 for k, old := range prev {
274 if _, ok := next[k]; !ok {
275 old.Outdated = true
276 next[k] = old
277 }
278 }
279 return next
280}
281
282func integrationTickAfterCmd(seq int) tea.Cmd {
283 return tea.Tick(integrationInterval, func(time.Time) tea.Msg {
284 return integrationTickMsg{seq: seq}
285 })
286}
287
288func waitForWebhookCmd(ch <-chan webhook.Event) tea.Cmd {
289 if ch == nil {
290 return nil
291 }
292 return func() tea.Msg {
293 ev, ok := <-ch
294 if !ok {
295 // The webhook channel was closed. Re-reading it would return
296 // immediately forever (a busy-loop), so we do NOT re-arm.
297 // Surface a visible (non-fatal) error instead of going silently
298 // dark — in webhook-only mode this would otherwise permanently
299 // kill all reconcile triggers except the slow heartbeat (see
300 // issue #271).
301 return webhookClosedMsg{}
302 }
303 return webhookMsg{event: ev}
304 }
305}
306
307func waitForInternalEventCmd(ch <-chan event.Event) tea.Cmd {
308 if ch == nil {
309 return nil
310 }
311 return func() tea.Msg {
312 ev, ok := <-ch
313 if !ok {
314 return nil
315 }
316 return internalEventMsg{event: ev}
317 }
318}
319
320// shouldInvalidate reports whether an event type should trigger a refetch
321// of GitHub PR status. Most klaus events (agent:started, pr:merged, …) are
322// pure notifications and either reflect state the dashboard already learned
323// from the pipeline FSM, or are observational. Only events that signal an
324// external precondition change need an active invalidation.
325func shouldInvalidate(eventType string) bool {
326 switch eventType {
327 case event.PRApprovalChanged:
328 return true
329 }
330 return false
331}
332
333// internalEventPRNumber returns the PR number associated with an event,
334// or empty if none. The event Data is map[string]interface{}; JSON decodes
335// numbers as float64, but events constructed in-process may carry int /
336// int64, so all common numeric forms are tolerated.
337func internalEventPRNumber(ev event.Event) string {
338 if ev.Data == nil {
339 return ""
340 }
341 switch v := ev.Data["pr_number"].(type) {
342 case string:
343 return v
344 case int:
345 return fmt.Sprintf("%d", v)
346 case int64:
347 return fmt.Sprintf("%d", v)
348 case float64:
349 if v == float64(int64(v)) {
350 return fmt.Sprintf("%d", int64(v))
351 }
352 }
353 return ""
354}
355
356func tickCmd() tea.Cmd {
357 return func() tea.Msg {
358 return tickMsg{}
359 }
360}
361
362func tickAfterCmd() tea.Cmd {
363 return tea.Tick(30*time.Second, func(time.Time) tea.Msg {
364 return tickMsg{}
365 })
366}
367
368// defaultReconcileInterval is the slow reconcile heartbeat interval used in
369// webhook-only mode when no override is configured.
370const defaultReconcileInterval = 5 * time.Minute
371
372// shouldScheduleReconcile reports whether the slow reconcile heartbeat should
373// run. It runs only in webhook mode when polling is NOT active: poll mode
374// already re-fetches every 30s (tickMsg), so the heartbeat would be redundant.
375// A non-positive interval disables the heartbeat entirely.
376func shouldScheduleReconcile(useWebhook, pollEnabled bool, interval time.Duration) bool {
377 return useWebhook && !pollEnabled && interval > 0
378}
379
380// reconcileInterval resolves the heartbeat interval from config. A zero value
381// means "use the default"; a negative value disables the heartbeat.
382func reconcileInterval(cfg *config.WebhookConfig) time.Duration {
383 if cfg == nil || cfg.ReconcileIntervalSeconds == 0 {
384 return defaultReconcileInterval
385 }
386 if cfg.ReconcileIntervalSeconds < 0 {
387 return 0 // disabled
388 }
389 return time.Duration(cfg.ReconcileIntervalSeconds) * time.Second
390}
391
392func reconcileTickAfterCmd(interval time.Duration) tea.Cmd {
393 // Defensive guard: tea.Tick fires immediately for a non-positive duration,
394 // so re-arming with interval <= 0 (the disabled-heartbeat sentinel) would
395 // spin an infinite loop of reconcileTickMsg messages and peg the CPU.
396 // Returning nil cleanly disables the heartbeat (bubbletea ignores nil cmds).
397 if interval <= 0 {
398 return nil
399 }
400 return tea.Tick(interval, func(time.Time) tea.Msg {
401 return reconcileTickMsg{}
402 })
403}
404
405// startWatcherCmd watches the run state directory and, when jobsDir is set,
406// the job records.
407func startWatcherCmd(store run.StateStore, jobsDir string) tea.Cmd {
408 return func() tea.Msg {
409 stateDir := store.StateDir()
410 // Ensure the directory exists before watching
411 os.MkdirAll(stateDir, 0o755)
412
413 w, err := fsnotify.NewWatcher()
414 if err != nil {
415 return errMsg{err: fmt.Errorf("creating file watcher: %w", err)}
416 }
417 if err := w.Add(stateDir); err != nil {
418 w.Close()
419 return errMsg{err: fmt.Errorf("watching state dir: %w", err)}
420 }
421 if jobsDir != "" {
422 os.MkdirAll(jobsDir, 0o700)
423 if err := w.Add(jobsDir); err != nil {
424 w.Close()
425 return errMsg{err: fmt.Errorf("watching jobs dir: %w", err)}
426 }
427 }
428 return w
429 }
430}
431
432// watchFSCmd waits for a record to change: a job's in jobsDir (jobsFSMsg),
433// else a run's (fsEventMsg).
434func watchFSCmd(w *fsnotify.Watcher, jobsDir string) tea.Cmd {
435 return func() tea.Msg {
436 for {
437 select {
438 case event, ok := <-w.Events:
439 if !ok {
440 return nil
441 }
442 if filepath.Ext(event.Name) != ".json" {
443 continue
444 }
445 if jobsDir != "" && filepath.Dir(event.Name) == filepath.Clean(jobsDir) {
446 return jobsFSMsg{}
447 }
448 return fsEventMsg{}
449 case _, ok := <-w.Errors:
450 if !ok {
451 return nil
452 }
453 // Ignore watcher errors and keep watching
454 }
455 }
456 }
457}
458
459func checkSandboxCmd(states []*run.State) tea.Cmd {
460 return func() tea.Msg {
461 hosts := make(map[string]bool)
462 for _, s := range states {
463 if s.Host != nil && *s.Host != "" {
464 if _, ok := hosts[*s.Host]; !ok {
465 hosts[*s.Host] = CheckSandboxReachable(*s.Host)
466 }
467 }
468 }
469 if len(hosts) == 0 {
470 return nil
471 }
472 return sandboxStatusMsg{hosts: hosts}
473 }
474}