gunk-dev/the-valley

dashboard.go

source6a7605f70901main's published tip history
38.6 KiB
1package cmd
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "log"
9 "log/slog"
10 "net/http"
11 "os"
12 "path/filepath"
13 "strings"
14 "syscall"
15 "time"
16
17 tea "github.com/charmbracelet/bubbletea"
18 "github.com/charmbracelet/lipgloss"
19 "github.com/charmbracelet/x/ansi"
20 "github.com/fsnotify/fsnotify"
21 "the-valley/flow/internal/config"
22 "the-valley/flow/internal/event"
23 "the-valley/flow/internal/git"
24 gh "the-valley/flow/internal/github"
25 "the-valley/flow/internal/integration"
26 "the-valley/flow/internal/jobs"
27 "the-valley/flow/internal/pipeline"
28 "the-valley/flow/internal/restack"
29 "the-valley/flow/internal/run"
30 "the-valley/flow/internal/tmux"
31 "the-valley/flow/internal/webhook"
32 "github.com/spf13/cobra"
33)
34
35// dashboardError holds a pipeline error for TUI display.
36type dashboardError struct {
37 Time time.Time
38 Message string
39}
40
41var dashboardCmd = &cobra.Command{
42 Use: "dashboard",
43 Short: "Live TUI dashboard for monitoring agents and PRs",
44 Long: `Shows a persistent, auto-refreshing terminal UI that monitors all active
45agent runs and their PR statuses: CI status, merge conflicts, and review
46decisions.
47
48Local state updates instantly via filesystem watching.
49GitHub state (CI, conflicts, reviews) polls every 30 seconds by default.
50
51When webhook config is present in .klaus/config.json, the dashboard starts
52an HTTP server to receive push events from github-relay instead of polling.
53Set "webhook": {"port": 9800} in config to enable. When another dashboard
54of the same user already holds the port, this one polls instead.
55
56In webhook-only mode (poll_fallback false), a slow reconcile heartbeat runs
57a full status re-fetch every 5 minutes by default (configurable via
58"reconcile_interval_seconds") so a dropped webhook can't strand a PR forever.
59
60Runs are listed by what they work on: the runs on a PR share its row, and
61so do the runs without a PR on its change (the same change ID in the same
62repo, the repo named by the valley's name or its short name, and by its
63GitHub owner where a run knows it, so alice/widget and bob/widget are two
64repos), as when a run that stopped before opening the PR was continued by
65one that opened it. Where the change stands apart from its PR keeps its own
66row: when a valley lists the change, or one of those runs pushed a branch
67that waits for integration, they share the change's row, as the runs
68without a PR on a change no PR carries do. A run with neither has a row of
69its own. A run that needs attention stops counting once a run of its
70change records taking its pushed work on (see valley flow launch) and is running
71or finished: that run carries the attention, and the row reads ATTN if it
72in turn ended needing attention or failing. Rows are grouped by whose move
73it is, most recent first within each group:
74 yours needs you or your coordinator: needs attention (ATTN), a
75 valley change to approve (READY), to review (REVIEW: a draft
76 awaiting the coordinator's review) or to look at (STALE,
77 REJECTED, FAILED, UNCERTAIN, DRAFT), a pushed branch to submit
78 (SUBMIT), or a PR that is ready to merge and not yet approved
79 agents an agent is running on it: a fix agent on a PR, a follow-up
80 (--resume-from, --pr or a pipeline fix) on a change
81 pipeline an open PR the pipeline is handling: CI running or failing,
82 conflicts, behind, approved and waiting to merge; or a valley
83 change that is approved and waiting on the integrator (APPROVED)
84 done merged, closed, integrated, gone, withdrawn, no access, or
85 exited
86Each row ends with how long ago its last activity was; a REVIEW row, with
87how long its draft has waited for review, as valley flow queue shows it.
88The line above the list counts each group (e.g. "2 yours") and shows the
89scroll position (e.g. "12–30 of 34").
90
91A pushed branch (a run that finished without a PR) shows SUBMIT until its
92work lands on the default branch. Every minute the dashboard checks the run's
93clone against origin: INTEGRATED means the pushed commit, or the branch's
94current tip, is on the default branch; INTEGRATED~ means a commit on the
95default branch carries the same change (equal patch-id), which is strong
96evidence rather than proof; GONE means the branch was deleted without
97landing. A PR the agent can no longer read on GitHub shows NO ACCESS and is
98re-checked every 30 minutes.
99
100A run whose repo delivers to a valley shows as its change: the repo (always
101shown), the change's handle and its title, then the version and head (e.g.
102v2@1a2b3c4). Finalize marked the pushed head ready, or, with
103"ready_at_finalize": false in config, left it a draft awaiting review. One
104"valley changes --all --json" for all such runs says where each stands. It
105runs at once when the valley host reports a decision or new evidence, and
106otherwise every minute: REVIEW (a draft finalize left that awaits review; approve refuses it,
107and the footer offers the 'valley flow ready <handle> --head <head>' that marks the
108head on screen ready once its review passes), READY (ready and waiting for you), APPROVED, INTEGRATED
109(landed), UNCERTAIN (no landing evidence: look), STALE, REJECTED or FAILED
110(the integrator's decision), WITHDRAWN, or DRAFT (returned to draft, as
111launch does when a follow-up run continues the change, and no run of it is
112running). If valley can't be asked, the git check above decides, and a change
113waiting on it reads READY, or REVIEW when finalize left it a draft. A run
114whose change finalize couldn't mark ready shows SUBMIT and the reason.
115A ready change's row shows its required checks as a PR row shows CI: CI …
116(pending), CI ✗ and the failed checks' names, or CI ✓. They don't change
117READY: you may approve before they finish. After each check the dashboard
118dispatches a run to fix a failed head of a change flow owns, as
119'valley flow failed-checks' does.
120
121A change's row is built like a PR's. It shows the valley's handle, else the
122first 8 characters of the change ID; the valley's title, else the subject
123of the head its latest run pushed; and where the valley says the change's
124active version stands, with that version's head to approve, wherever it
125was marked ready (for a change no valley lists, where its latest push
126stands). Earlier versions fold into the row. A newer push the valley
127doesn't hold as a version, as when its ready failed, doesn't take the row
128over: the footer notes it ("a newer push 1a2b3c4 isn't ready"). While an agent runs on a PR or a change, the row names it (e.g.
129"agent:1a2b running"), sorts with the agents and offers no approve command,
130and the footer says which agent is working on it. Once it exits, the row
131goes back to where the PR or change stands.
132
133Below the run rows, a jobs section lists the session's consults, reviews, and
134running prose passes, as valley flow status does: every running job, with how long it
135has run, and consults and reviews that finished in the last 3 hours, with how
136long they took and how they ended (SUCCEEDED, FAILED, TIMED OUT, INTERRUPTED, or
137DIED when the job's flow process was killed without recording its end). Finished prose
138passes in the last 3 hours are counted on the jobs header line (total and
139failed), and each selected run row's footer includes that row's own finished
140prose passes. It follows the job records as they change. Press tab to select a
141listed job: the footer says how it stands, with its error and where its raw
142output was saved, and enter opens its record and answer, as 'valley flow jobs show'
143prints them; esc goes back. On a short pane the jobs lines go before any run
144row does.
145
146Done rows older than an hour are hidden until you press h; the line above the
147list says how many are hidden. A row the dashboard watched finish stays for
148the full hour. Set "dashboard": {"hide_finished_after_minutes": N} in config
149to change the threshold, or a negative N to never hide them.
150
151When finalize failed to push a run's data ref to origin (push_data_ref on), a
152line above the footer names the newest such run, the failure's class and the
153remote's message, as finalize recorded them. The run's own row is unchanged.
154
155Set "dashboard": {"approve_command": "cd ~/hack/{repo} && valley approve {handle} --head {head}"}
156to show, in the footer, the command that approves the selected READY row
157(or submits a SUBMIT row). {repo} is the repo as the row names it, {branch}
158the pushed branch, {change} the full change ID, {handle} the change's handle
159and {head} the pushed head, so the approval binds the head you saw. A row
160with no value for a placeholder the template uses, such as {handle} on a
161branch no valley knows, shows no command, and neither does a DRAFT or
162REVIEW row or one with an agent running on it. The command is for you to run on your own
163machine; the dashboard never runs it. "submit_command" is the
164deprecated name of "approve_command", read only when approve_command is
165unset.
166
167Every 30 seconds the dashboard resolves the binary it was started as on PATH,
168symlinks and all. When it names a different file than the running binary, and
169that file runs --version, as after valley flow self-update, the footer says
170"flow updated to <version>; restarting". Once no key has been pressed for 10
171seconds, the dashboard shuts down as on q, releasing its webhook port, and
172execs the new binary with the same arguments and environment. If the exec
173fails, it keeps running on the old binary, shows the error, and leaves that
174file alone.
175
176Keyboard shortcuts:
177 j / k or ↑ / ↓ move the selection
178 PgUp / PgDn move a page
179 g / G jump to the top / bottom (also Home / End)
180 h show all runs / hide old done rows
181 a approve the selected PR
182 d discuss the selected PR with the coordinator
183 o open the selected PR in a browser
184 tab select a job / back to the runs
185 enter read the selected job's answer (esc to go back)
186 r refresh, and redraw the whole screen
187 q quit`,
188 RunE: func(cmd *cobra.Command, args []string) error {
189 bin := newBinCheck()
190 var notice string
191 for {
192 next, err := runDashboard(cmd, bin, notice)
193 if next == nil {
194 return err
195 }
196 // The dashboard has shut down and released its port: become the
197 // new klaus, with the same arguments and environment.
198 err = syscall.Exec(next.path, os.Args, os.Environ())
199 // Still here: keep running on this klaus, and leave that file be.
200 bin.failed[next.path] = true
201 notice = fmt.Sprintf("flow updated to %s, but restarting onto it failed: %v", next.version, err)
202 }
203 },
204}
205
206// runDashboard runs the dashboard until it quits. It returns the klaus to
207// restart onto when it quit for that, once everything is shut down. notice,
208// if set, starts in the footer as an error.
209func runDashboard(cmd *cobra.Command, bin *binCheck, notice string) (*binUpdateMsg, error) {
210 {
211 store, err := sessionStore()
212 if err != nil {
213 return nil, fmt.Errorf("KLAUS_SESSION_ID not set; run inside a flow session")
214 }
215
216 // Load config once — used for both the dashboard model and webhook setup.
217 repoRoot, _ := git.RepoRoot()
218 cfg, err := config.Load(repoRoot)
219 if err != nil {
220 fmt.Fprintf(os.Stderr, "warning: loading config: %v\n", err)
221 }
222
223 // Shared context for coordinating graceful shutdown of all subsystems.
224 ctx, cancel := context.WithCancel(cmd.Context())
225
226 ghClient := gh.NewGHCLIClient("")
227 model := newDashboardModel(store, cfg, ghClient)
228 model.shutdownCancel = cancel
229 model.bin = bin
230 model.binNotice, model.binNoticeErr = notice, notice != ""
231 defer logTo(model.logger)()
232
233 // Tail the session event log so klaus-internal commands (e.g.
234 // `klaus approve`) can wake the dashboard FSM without waiting for
235 // a GitHub webhook. The tail runs even when no webhook server is
236 // configured — it is the invalidation channel for our own CLI.
237 if model.eventsPath != "" {
238 internalCh := make(chan event.Event, 64)
239 model.internalEventCh = internalCh
240 go func() {
241 defer close(internalCh)
242 if err := event.Tail(ctx, model.eventsPath, internalCh); err != nil {
243 model.logger.Warn("event tail stopped", "err", err)
244 }
245 }()
246 }
247
248 webhookSrv, err := setupWebhook(&model, cfg)
249 if err != nil {
250 cancel()
251 return nil, err
252 }
253
254 model.waker = startValleyWaker(ctx, model.logger)
255
256 p := tea.NewProgram(model, tea.WithAltScreen(), tea.WithContext(ctx))
257 finalModel, err := p.Run()
258 cancel()
259
260 // BubbleTea has exited — centralize cleanup of watcher and log file.
261 var restart *binUpdateMsg
262 if m, ok := finalModel.(dashboardModel); ok {
263 if m.watcher != nil {
264 m.watcher.Close()
265 }
266 if m.logFile != nil {
267 m.logFile.Close()
268 }
269 if m.restarting && err == nil {
270 restart = m.restart
271 }
272 }
273
274 // Gracefully shut down the webhook server so the port is released promptly.
275 if webhookSrv != nil {
276 shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
277 defer shutdownCancel()
278 if err := webhookSrv.Shutdown(shutdownCtx); err != nil {
279 fmt.Fprintf(os.Stderr, "webhook server shutdown: %v\n", err)
280 }
281 }
282
283 return restart, err
284 }
285}
286
287// setupWebhook starts the webhook server when cfg asks for one and sets the
288// model's data source to match. When another dashboard already holds the
289// port, the model polls instead and says so; any other listen error is
290// returned. The returned server is nil when none runs.
291func setupWebhook(model *dashboardModel, cfg config.Config) (*webhook.Server, error) {
292 if cfg.Webhook == nil {
293 model.pollEnabled = true
294 return nil, nil
295 }
296 ch := make(chan webhook.Event, 64)
297 port := cfg.Webhook.Port
298 if port == 0 {
299 port = 9800
300 }
301 srv := webhook.NewServer(port, cfg.Webhook.Path, ch)
302 if err := srv.Listen(); err != nil {
303 if !errors.Is(err, syscall.EADDRINUSE) {
304 return nil, fmt.Errorf("webhook server: %w", err)
305 }
306 model.pollEnabled = true
307 model.webhookHeldNote = fmt.Sprintf("webhook port %d is held by another dashboard", port)
308 model.logger.Info("polling instead of receiving webhooks", "reason", model.webhookHeldNote)
309 return nil, nil
310 }
311
312 model.webhookCh = ch
313 model.useWebhook = true
314 model.pollEnabled = cfg.Webhook.PollFallback
315 model.webhookAddr = srv.Addr()
316 model.reconcileEvery = reconcileInterval(cfg.Webhook)
317
318 logger := model.logger
319 go func() {
320 if err := srv.Serve(); err != nil && err != http.ErrServerClosed {
321 logger.Error("webhook server", "err", err)
322 }
323 }()
324 return srv, nil
325}
326
327func init() {
328 rootCmd.AddCommand(dashboardCmd)
329}
330
331// logTo sends what slog's and log's default loggers write to logger until
332// the returned func restores them. Nothing may write to the terminal under
333// the dashboard: a line there scrolls the pane, and the renderer, which
334// redraws only the lines that changed, would leave the scrolled lines on
335// screen for good.
336func logTo(logger *slog.Logger) (restore func()) {
337 prev, out, flags := slog.Default(), log.Writer(), log.Flags()
338 slog.SetDefault(logger)
339 return func() {
340 slog.SetDefault(prev)
341 log.SetOutput(out)
342 log.SetFlags(flags)
343 }
344}
345
346// dashboardModel is the bubbletea model for the dashboard.
347type dashboardModel struct {
348 store run.StateStore
349 ghClient gh.Client
350 ghPoller *ghPoller
351 ghLimitedUntil time.Time // GitHub rate-limited PR polling until then
352 tmuxDeps run.TmuxDeps
353 tmux tmux.Client // for keyboard-driven actions (discuss)
354 cursor int // index into the displayed rows of the selected row
355 selKey string // dashRow.key of the selected row; survives reordering
356 offset int // index of the first row in the viewport
357 showAll bool // show old done rows that are hidden by default
358 hideAfter time.Duration
359 runningSnap map[string]bool // run ID -> agent running, see agentRunning
360 seenUnfinished map[string]bool // row keys seen before they finished
361 finishedAt map[string]time.Time // when a watched row was first seen finished
362 states []*run.State
363 ghStatus map[string]*prStatus // keyed by PR URL
364 sandboxHosts map[string]bool // host -> reachable
365 pipelineCtrl *pipeline.Controller
366 pipelineStates map[string]*pipeline.PRPipelineState
367 noAccessAt map[string]time.Time // PR URL -> when last found unreadable
368 checker integration.Checker
369 integration map[string]integration.Result // run ID -> latest check; nil before the first check
370 changes map[integration.ChangeKey]integration.Result // the valley's view of each change's active version
371 integrationOn bool // the integration check loop has started
372 valleyErr string // why the latest valley check failed; "" when it didn't
373 checking bool // an integration check is running
374 checkAgain bool // a wake came during the running check: run one more after it
375 wakeHeld bool // a wake waits wakeSettle for the rest of its burst
376 checkSeq int // the latest arming of the integration timer
377 waker *valleyWaker // follows valley hosts' telemetry; nil when not started
378 logger *slog.Logger // writes dashboard.log
379 changeLedger *pipeline.ChangeLedger // the valley change transitions seen and reported; nil outside a session
380 restackOn bool // each integration check runs a restack pass
381 restacks map[integration.ChangeKey]restack.View // where each restack conflict on a change klaus owns stands
382 approveTemplate string // dashboard.approve_command, or the deprecated submit_command
383 recentErrors []dashboardError // last N pipeline errors shown in TUI
384 jobsDir string // the session's job records; "" outside a session
385 jobs []*jobs.Job // every job record, newest first
386 jobFocus bool // a job is selected rather than a run
387 jobCursor int // index into the shown jobs of the selected job
388 jobSel string // ID of the selected job; survives reordering
389 detail *jobDetail // the job shown in place of the list, if any
390 width int
391 height int
392 err error
393 watcher *fsnotify.Watcher
394 logFile *os.File
395 shutdownCancel context.CancelFunc // cancels the shared shutdown context
396 webhookCh <-chan webhook.Event // non-nil when webhook mode is active
397 webhookHeldNote string // why polling replaced the webhook: another dashboard holds the port
398 webhookAddr string // e.g. "127.0.0.1:9800"
399 useWebhook bool // true when webhook server is running
400 pollEnabled bool // true when polling is active (default or poll_fallback)
401 reconcileEvery time.Duration // slow reconcile heartbeat interval (webhook-only mode)
402 // internalEventCh carries klaus-emitted invalidation events (e.g.
403 // PRApprovalChanged from `klaus approve`). It is symmetric to webhookCh
404 // but sourced from the local event log rather than an HTTP listener,
405 // so internal CLI commands can wake the FSM without waiting for a real
406 // GitHub webhook.
407 internalEventCh <-chan event.Event
408 eventsPath string // path to events.jsonl for the tail goroutine
409 // lastWebhookAt records the wall-clock time of the most recent webhook
410 // delivery (any event). The zero value means none received yet. It drives
411 // the footer freshness indicator; the existing 30s tick re-renders the view
412 // so the displayed age advances without a dedicated timer.
413 lastWebhookAt time.Time
414 // bin watches klaus on PATH; restart is the new klaus it found, which
415 // the dashboard restarts onto once the keyboard is quiet (lastKeyAt).
416 // restarting means it quit to do so. binNotice is the footer's line
417 // about it, an error if binNoticeErr.
418 bin *binCheck
419 restart *binUpdateMsg
420 restarting bool
421 lastKeyAt time.Time
422 binNotice string
423 binNoticeErr bool
424 // clearing is the clear the x key awaits confirmation of; nil when none.
425 clearing *dashClear
426 // jobsClearedAt is when the x key last cleared finished jobs from the
427 // jobs section.
428 jobsClearedAt time.Time
429 // cleared sums the runs cleanup removed, for the header's totals.
430 cleared run.Cleared
431 // clock dates REVIEW rows by the session's events, as valley flow
432 // queue dates them; nil before the first load.
433 clock *stateClock
434}
435
436func newDashboardModel(store run.StateStore, cfg config.Config, ghClient gh.Client) dashboardModel {
437 var eventLog *event.Log
438 var logWriter io.Writer = io.Discard
439 var logFile *os.File
440 var eventsPath, jobsDir, ledgerPath string
441 var changeLedger *pipeline.ChangeLedger
442 if hds, ok := store.(*run.HomeDirStore); ok {
443 eventLog = event.NewLog(hds.BaseDir())
444 eventsPath = eventLog.Path()
445 jobsDir = jobs.NewStore(hds.BaseDir()).Dir
446 ledgerPath = filepath.Join(hds.BaseDir(), pipeline.LedgerFile)
447 logPath := filepath.Join(hds.BaseDir(), "dashboard.log")
448 if f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644); err == nil {
449 logWriter = f
450 logFile = f
451 }
452 }
453 logger := slog.New(slog.NewTextHandler(logWriter, nil))
454 ctrl := pipeline.New(store, eventLog, logger)
455 ctrl.SetAutoMergeOnApproval(cfg.AutoMergesOnApproval())
456 if ledgerPath != "" {
457 // The ledger outlives the dashboard, so a restart doesn't report a
458 // PR's approval or merge again.
459 ledger, err := pipeline.LoadLedger(ledgerPath)
460 if err != nil {
461 logger.Error("reading the PR transition ledger", "err", err)
462 }
463 ctrl.SetLedger(ledger)
464 // The change ledger does the same for valley changes.
465 changeLedger, err = pipeline.LoadChangeLedger(filepath.Join(filepath.Dir(ledgerPath), pipeline.ChangeLedgerFile))
466 if err != nil {
467 logger.Error("reading the change transition ledger", "err", err)
468 }
469 }
470
471 return dashboardModel{
472 store: store,
473 ghClient: ghClient,
474 ghPoller: newGHPoller(ghClient, cfg.TrustedReviewers),
475 tmuxDeps: run.DefaultTmuxDeps(),
476 tmux: tmux.NewExecClient(),
477 ghStatus: make(map[string]*prStatus),
478 sandboxHosts: make(map[string]bool),
479 pipelineCtrl: ctrl,
480 pipelineStates: make(map[string]*pipeline.PRPipelineState),
481 noAccessAt: make(map[string]time.Time),
482 checker: integration.NewValleyChecker(logger),
483 changeLedger: changeLedger,
484 restackOn: ledgerPath != "", // a restack pass keeps its ledger in the session directory
485 approveTemplate: cfg.Dashboard.ApproveTemplate(),
486 hideAfter: hideFinishedAfter(cfg.Dashboard),
487 logFile: logFile,
488 eventsPath: eventsPath,
489 jobsDir: jobsDir,
490 logger: logger,
491 }
492}
493
494func (m dashboardModel) Init() tea.Cmd {
495 cmds := []tea.Cmd{
496 // Start on a clear screen, as after a restart onto a new klaus.
497 tea.ClearScreen,
498 loadStatesCmd(m.store),
499 loadJobsCmd(m.jobsDir),
500 startWatcherCmd(m.store, m.jobsDir),
501 tickCmd(), // always tick once on startup for initial fetch
502 }
503 if m.webhookCh != nil {
504 cmds = append(cmds, waitForWebhookCmd(m.webhookCh))
505 }
506 if shouldScheduleReconcile(m.useWebhook, m.pollEnabled, m.reconcileEvery) {
507 cmds = append(cmds, reconcileTickAfterCmd(m.reconcileEvery))
508 }
509 if m.internalEventCh != nil {
510 cmds = append(cmds, waitForInternalEventCmd(m.internalEventCh))
511 }
512 if m.waker != nil {
513 cmds = append(cmds, m.waker.waitCmd())
514 }
515 return tea.Batch(cmds...)
516}
517
518func (m dashboardModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
519 next, cmd := m.update(msg)
520 dm, ok := next.(dashboardModel)
521 if !ok {
522 return next, cmd
523 }
524 // Re-resolve the run list whenever it or the pane can have changed, so
525 // the selection stays on its row and in view.
526 switch msg.(type) {
527 case statesLoadedMsg, ghStatusMsg, tickMsg, integrationMsg:
528 dm.snapshotRunning()
529 dm.syncView(time.Now())
530 case tea.KeyMsg, tea.WindowSizeMsg, jobsLoadedMsg:
531 dm.syncView(time.Now())
532 }
533 return dm, cmd
534}
535
536func (m dashboardModel) update(msg tea.Msg) (tea.Model, tea.Cmd) {
537 switch msg := msg.(type) {
538 case tea.KeyMsg:
539 m.lastKeyAt = time.Now()
540 key := msg.String()
541 if m.detail != nil && key != "ctrl+c" {
542 return m.detailKey(key), nil
543 }
544 if c := m.clearing; c != nil {
545 m.clearing = nil
546 if key != "y" {
547 return m, nil
548 }
549 m.jobsClearedAt = m.lastKeyAt
550 return m, m.clearCmd(c)
551 }
552 if m.jobFocus {
553 if next, ok := m.jobKey(key, m.lastKeyAt); ok {
554 return next, nil
555 }
556 }
557 switch key {
558 case "q", "ctrl+c":
559 // Cancel the shared context to signal all subsystems to stop.
560 if m.shutdownCancel != nil {
561 m.shutdownCancel()
562 }
563 return m, tea.Quit
564 case "r":
565 // Redraw every line: the renderer redraws only the lines that
566 // changed, so whatever else wrote to the pane stays until then.
567 return m, tea.Batch(
568 tea.ClearScreen,
569 loadStatesCmd(m.store),
570 loadJobsCmd(m.jobsDir),
571 m.fetchGHStatusCmd(m.states),
572 )
573 case "tab":
574 // Select the top job: running ones come first.
575 m.jobFocus = m.resolve(m.lastKeyAt).jobsShown > 0
576 m.jobCursor, m.jobSel = 0, ""
577 case "up", "k":
578 m.moveSelection(-1, 0)
579 case "down", "j":
580 m.moveSelection(1, 0)
581 case "pgup":
582 m.moveSelection(0, -1)
583 case "pgdown":
584 m.moveSelection(0, 1)
585 case "g", "home":
586 m.selectEdge(false)
587 case "G", "end":
588 m.selectEdge(true)
589 case "h":
590 m.showAll = !m.showAll
591 case "x":
592 // Clear what's finished, as klaus cleanup --done does, once
593 // the operator confirms.
594 m.clearing = m.planClear(m.lastKeyAt)
595 case "a":
596 // Approve the selected PR immediately (no confirmation).
597 r, ok := m.selectedPR("approve")
598 if !ok {
599 break
600 }
601 if err := markApproved(r.state(), m.store); err != nil {
602 m.noteError(fmt.Sprintf("approve PR #%s: %v", r.prNum, err))
603 }
604 // Reload so the row reflects approval immediately; the fsnotify
605 // watcher also catches the save, but this avoids the round-trip lag.
606 return m, loadStatesCmd(m.store)
607 case "d":
608 // Discuss the selected PR with the coordinator: pre-fill a prompt
609 // in the coordinator pane and switch focus there.
610 r, ok := m.selectedPR("discuss")
611 if !ok {
612 break
613 }
614 pane := m.coordinatorPane()
615 if pane == "" {
616 m.noteError("coordinator pane unknown (older session; relaunch to enable discuss)")
617 break
618 }
619 if err := m.discussPR(r.prNum, pane); err != nil {
620 m.noteError(fmt.Sprintf("discuss PR #%s: %v", r.prNum, err))
621 }
622 case "o":
623 // Open the selected PR in the system browser.
624 r, ok := m.selectedPR("open")
625 if !ok {
626 break
627 }
628 s := r.state()
629 if s.PRURL == nil || *s.PRURL == "" {
630 break
631 }
632 url := *s.PRURL
633 prNum := r.prNum
634 // Fire-and-forget so Update stays clean and the UI never blocks on
635 // the browser launch. Surface a transient hint on failure.
636 return m, func() tea.Msg {
637 if err := openInBrowser(url); err != nil {
638 return errHintMsg{msg: fmt.Sprintf("open PR #%s: %v", prNum, err)}
639 }
640 return nil
641 }
642 }
643
644 case tea.WindowSizeMsg:
645 m.width = msg.Width
646 m.height = msg.Height
647
648 case clearedMsg:
649 if len(msg.failed) > 0 {
650 m.noteError(fmt.Sprintf("clear finished: couldn't remove %v", msg.failed))
651 }
652 return m, loadStatesCmd(m.store)
653
654 case statesLoadedMsg:
655 m.states = msg.states
656 m.cleared = msg.cleared
657 m.clock = msg.clock
658 // Detect and finalize stale (orphaned) runs so they stop appearing as active.
659 for _, s := range m.states {
660 if s.IsStaleWith(m.tmuxDeps) {
661 slog.Info("finalizing stale run", "id", s.ID)
662 markRunFailed(m.store, s)
663 }
664 }
665 // Follow the valley hosts of the changes the check asks about, so
666 // the host's decisions wake it.
667 m.waker.Track(valleyCheckouts(m.states))
668 cmd := m.fetchGHStatusCmd(m.states)
669 if !m.integrationOn {
670 // The first load starts the integration check loop; it then
671 // re-arms itself each time a check completes.
672 m.integrationOn = true
673 var check tea.Cmd
674 m, check = m.startIntegrationCheck()
675 cmd = tea.Batch(cmd, check)
676 }
677 return m, cmd
678
679 case integrationTickMsg:
680 if msg.seq != m.checkSeq || m.checking {
681 return m, nil // a woken check took this tick's place
682 }
683 return m.startIntegrationCheck()
684
685 case valleyWakeMsg:
686 cmd := m.waker.waitCmd()
687 if !m.wakeHeld {
688 m.wakeHeld = true
689 cmd = tea.Batch(cmd, tea.Tick(wakeSettle, func(time.Time) tea.Msg { return valleyWakeCheckMsg{} }))
690 }
691 return m, cmd
692
693 case valleyWakeCheckMsg:
694 m.wakeHeld = false
695 if m.checking {
696 m.checkAgain = true
697 return m, nil
698 }
699 if !m.integrationOn {
700 return m, nil // the first load's check is yet to start
701 }
702 return m.startIntegrationCheck()
703
704 case integrationMsg:
705 m.integration = keepValleyViews(m.integration, msg.results)
706 m.changes = keepChangeViews(m.changes, msg.changes)
707 m.valleyErr = msg.valleyErr
708 if msg.restacks != nil {
709 m.restacks = msg.restacks
710 }
711 m.checking = false
712 if m.checkAgain {
713 m.checkAgain = false
714 return m.startIntegrationCheck()
715 }
716 m.checkSeq++
717 return m, integrationTickAfterCmd(m.checkSeq)
718
719 case ghStatusMsg:
720 now := time.Now()
721 m.ghLimitedUntil = msg.rateLimitedUntil
722 for url, v := range msg.statuses {
723 m.ghStatus[url] = v
724 if v.State == gh.StateNoAccess {
725 m.noAccessAt[url] = now
726 } else {
727 delete(m.noAccessAt, url)
728 }
729 }
730 // Feed statuses to the pipeline controller, which keys PRs by number:
731 // the first run state for a number decides which PR it tracks. PRs the
732 // agent can't read are left out; the pipeline can't act on them.
733 pStatuses := make(map[string]*pipeline.PRStatus, len(msg.statuses))
734 claimed := make(map[string]bool)
735 for _, s := range m.states {
736 prNum, url := extractPRNumber(s), extractPRRef(s)
737 if prNum == "" || claimed[prNum] {
738 continue
739 }
740 claimed[prNum] = true
741 v, ok := msg.statuses[url]
742 if !ok || v.State == gh.StateNoAccess {
743 continue
744 }
745 ps := &pipeline.PRStatus{
746 PRNumber: v.PRNumber,
747 PRURL: url,
748 State: v.State,
749 CI: v.CI,
750 Conflicts: v.Conflicts,
751 BehindBy: v.BehindBy,
752 ReviewDecision: v.ReviewDecision,
753 HasNewTrustedComments: v.HasNewTrustedComments,
754 Labels: v.Labels,
755 HeadSHA: v.HeadSHA,
756 TrustedFeedbackAt: v.TrustedFeedbackAt,
757 }
758 if s.TargetRepo != nil {
759 ps.TargetRepo = *s.TargetRepo
760 }
761 pStatuses[prNum] = ps
762 }
763 actions := m.pipelineCtrl.HandleGHStatus(context.Background(), pStatuses, m.states)
764 m.pipelineStates = m.pipelineCtrl.PipelineStates()
765 if len(actions) > 0 {
766 return m, func() tea.Msg {
767 return pipelineActionMsg{actions: actions}
768 }
769 }
770
771 case pipelineActionMsg:
772 // Capture any error actions for TUI display.
773 for _, a := range msg.actions {
774 if a.Error != "" {
775 errMsg := a.Detail + " — " + a.Error
776 m.recentErrors = append(m.recentErrors, dashboardError{
777 Time: time.Now(),
778 Message: errMsg,
779 })
780 if len(m.recentErrors) > 3 {
781 m.recentErrors = m.recentErrors[len(m.recentErrors)-3:]
782 }
783 }
784 }
785 // Pipeline dispatched agents or merged PRs — refresh state.
786 return m, loadStatesCmd(m.store)
787
788 case fsEventMsg:
789 return m, tea.Batch(loadStatesCmd(m.store), watchFSCmd(m.watcher, m.jobsDir))
790
791 case jobsFSMsg:
792 return m, tea.Batch(loadJobsCmd(m.jobsDir), watchFSCmd(m.watcher, m.jobsDir))
793
794 case jobsLoadedMsg:
795 m.jobs = msg.jobs
796 m.refreshJobDetail(time.Now())
797
798 case sandboxStatusMsg:
799 for k, v := range msg.hosts {
800 m.sandboxHosts[k] = v
801 }
802
803 case webhookMsg:
804 // Webhooks are invalidation signals, not data sources. When a
805 // webhook arrives, trigger an immediate re-fetch of PR status
806 // via the same code path that polling uses. This eliminates
807 // the class of bugs where the webhook path diverges from polling.
808 ev := msg.event
809 // Record the delivery time for the footer freshness indicator. Every
810 // delivery counts, regardless of PRNumber/type.
811 m.lastWebhookAt = time.Now()
812 if ev.PRNumber != "" {
813 // Find run states that match this PR for a targeted fetch.
814 var matchedStates []*run.State
815 for _, s := range m.states {
816 if extractPRNumber(s) == ev.PRNumber {
817 matchedStates = append(matchedStates, s)
818 }
819 }
820 if len(matchedStates) > 0 {
821 return m, tea.Batch(
822 m.fetchGHStatusCmd(matchedStates),
823 waitForWebhookCmd(m.webhookCh),
824 )
825 }
826 } else if ev.EventType == "push" && ev.Repo != "" {
827 // Push to default branch — re-fetch all open PRs since
828 // conflicts may have changed.
829 return m, tea.Batch(
830 m.fetchGHStatusCmd(m.states),
831 waitForWebhookCmd(m.webhookCh),
832 )
833 }
834 return m, waitForWebhookCmd(m.webhookCh)
835
836 case webhookClosedMsg:
837 // Live webhook consumption has stopped. Do not re-arm (re-reading a
838 // closed channel busy-loops). Surface it non-fatally; the reconcile
839 // heartbeat, if active, still bounds staleness.
840 m.recentErrors = append(m.recentErrors, dashboardError{
841 Time: time.Now(),
842 Message: "webhook event channel closed; live webhook updates stopped (reconcile heartbeat still active)",
843 })
844 if len(m.recentErrors) > 3 {
845 m.recentErrors = m.recentErrors[len(m.recentErrors)-3:]
846 }
847 return m, nil
848
849 case internalEventMsg:
850 // Klaus-internal invalidation events are handled symmetrically to
851 // webhooks: a CLI command (e.g. `klaus approve`) signalled that the
852 // pipeline preconditions for a PR may have changed, so we trigger
853 // a targeted re-fetch of GitHub status. That re-fetch funnels into
854 // the same HandleGHStatus path that polling and webhooks use, so
855 // the FSM gets a fresh evaluation without any divergent code path.
856 ev := msg.event
857 prNum := internalEventPRNumber(ev)
858 if shouldInvalidate(ev.Type) && prNum != "" {
859 var matchedStates []*run.State
860 for _, s := range m.states {
861 if extractPRNumber(s) == prNum {
862 matchedStates = append(matchedStates, s)
863 }
864 }
865 if len(matchedStates) > 0 {
866 return m, tea.Batch(
867 m.fetchGHStatusCmd(matchedStates),
868 waitForInternalEventCmd(m.internalEventCh),
869 )
870 }
871 }
872 return m, waitForInternalEventCmd(m.internalEventCh)
873
874 case trustedCommentsMsg:
875 existing, ok := m.ghStatus[msg.prURL]
876 if ok {
877 existing.HasNewTrustedComments = msg.hasNewTrustedComments
878 }
879
880 case reconcileTickMsg:
881 // Slow reconcile heartbeat (webhook-only mode). Webhooks are the only
882 // reconcile trigger when poll_fallback is false, so a single dropped
883 // or missed event would strand a PR forever. This periodic full
884 // re-fetch bounds worst-case staleness (see issue #271). It re-arms
885 // itself; it is never scheduled when polling is active (which already
886 // re-fetches every 30s), so there is no double-fetch.
887 return m, tea.Batch(
888 m.fetchGHStatusCmd(m.states),
889 reconcileTickAfterCmd(m.reconcileEvery),
890 )
891
892 case tickMsg:
893 // Expire errors older than 3 minutes.
894 cutoff := time.Now().Add(-3 * time.Minute)
895 filtered := m.recentErrors[:0]
896 for _, e := range m.recentErrors {
897 if e.Time.After(cutoff) {
898 filtered = append(filtered, e)
899 }
900 }
901 m.recentErrors = filtered
902
903 cmds := []tea.Cmd{
904 checkSandboxCmd(m.states),
905 // Reloading the jobs judges again which running ones died.
906 loadJobsCmd(m.jobsDir),
907 tickAfterCmd(),
908 }
909 if m.bin != nil && m.restart == nil {
910 cmds = append(cmds, checkBinCmd(m.bin))
911 }
912 if m.pollEnabled {
913 cmds = append(cmds, m.fetchGHStatusCmd(m.states))
914 }
915 return m, tea.Batch(cmds...)
916
917 case *fsnotify.Watcher:
918 m.watcher = msg
919 return m, watchFSCmd(msg, m.jobsDir)
920
921 case binUpdateMsg:
922 if m.restart != nil {
923 break
924 }
925 m.restart = &msg
926 m.binNotice, m.binNoticeErr = "flow updated to "+msg.version+"; restarting", false
927 // Show the notice for a moment before restarting.
928 return m, restartWaitCmd()
929
930 case restartWaitMsg:
931 return m.restartWhenIdle(time.Now())
932
933 case restartTargetMsg:
934 return m.restartOnto(msg.target, time.Now())
935
936 case errHintMsg:
937 m.noteError(msg.msg)
938
939 case errMsg:
940 m.err = msg.err
941 }
942
943 return m, nil
944}
945
946func (m dashboardModel) View() string {
947 if m.err != nil {
948 return fmt.Sprintf("Error: %v\n\nPress q to quit.", m.err)
949 }
950 if m.states == nil {
951 return "Loading..."
952 }
953
954 now := time.Now()
955 width := m.width
956 if width <= 0 {
957 width = defaultDashboardWidth
958 }
959 if m.detail != nil {
960 return m.renderJobDetail(width)
961 }
962 v := m.resolve(now)
963
964 chrome := func(c chromeItem) string {
965 switch c.kind {
966 case chromeHeader:
967 title := " flow dashboard"
968 span := computeSessionDuration(m.states)
969 if first := m.cleared.FirstCreated; !first.IsZero() && now.Sub(first) > span {
970 span = now.Sub(first)
971 }
972 headerRight := fmt.Sprintf("Session: %s | Cost: $%.2f",
973 formatDuration(span), computeTotalCost(m.states)+m.cleared.CostUSD)
974 if now.Before(m.ghLimitedUntil) {
975 headerRight = "GitHub rate-limited until " + m.ghLimitedUntil.Format("15:04") + " | " + headerRight
976 }
977 pad := max(width-2-lipgloss.Width(title)-lipgloss.Width(headerRight), 1)
978 return headerStyle.Render(title + strings.Repeat(" ", pad) + headerRight)
979 case chromeSource:
980 return m.renderSourceLine()
981 case chromeSandbox:
982 return strings.TrimSuffix(renderSandboxStatus(m.sandboxHosts), "\n")
983 case chromeSummary:
984 return m.renderSummary(v, width)
985 case chromeError:
986 e := m.recentErrors[c.idx]
987 line := fmt.Sprintf(" %s ✗ %s", e.Time.Format("15:04"), e.Message)
988 return dimRedStyle.Render(truncateLine(line, max(width-1, 1)))
989 case chromeNotice:
990 style := yellowStyle
991 if m.binNoticeErr {
992 style = dimRedStyle
993 }
994 return style.Render(truncateLine(" "+m.binNotice, max(width-1, 1)))
995 case chromeValley:
996 return yellowStyle.Render(truncateLine(" "+integration.ValleyNote(m.valleyErr), max(width-1, 1)))
997 case chromeDataRef:
998 return yellowStyle.Render(truncateLine(" "+m.dataRefWarning(), max(width-1, 1)))
999 case chromeJobs:
1000 return renderJobsHeader(v)
1001 case chromeJob:
1002 return renderJobLine(v.jobs[c.idx], v.jobFocus && c.idx == v.jobCursor, now)
1003 case chromeFooter:
1004 if v.jobFocus {
1005 return renderJobsFooter(v, width)
1006 }
1007 return m.renderFooter(v, width)
1008 }
1009 return ""
1010 }
1011
1012 var lines []string
1013 for _, c := range v.chrome {
1014 if c.top {
1015 lines = append(lines, chrome(c))
1016 }
1017 }
1018 if len(v.rows) == 0 && (m.height <= 0 || m.height > len(v.chrome)) {
1019 msg := " No runs found."
1020 if v.hidden > 0 {
1021 msg = fmt.Sprintf(" No runs to show: %d done hidden (h to show all).", v.hidden)
1022 }
1023 lines = append(lines, dimStyle.Render(msg))
1024 }
1025 lay := newRowLayout(v.all, width)
1026 for i := v.offset; i < v.offset+v.bodyH && i < len(v.rows); i++ {
1027 lines = append(lines, m.renderRow(v.rows[i], i == v.cursor && !v.jobFocus, lay, now))
1028 }
1029 for _, c := range v.chrome {
1030 if !c.top {
1031 lines = append(lines, chrome(c))
1032 }
1033 }
1034
1035 // One line each, never wrapped: a line break or a wrapped line would
1036 // push rows off the bottom of the pane.
1037 for i, l := range lines {
1038 l, _, _ = strings.Cut(l, "\n")
1039 lines[i] = ansi.Truncate(l, width, "…")
1040 }
1041 return strings.Join(lines, "\n")
1042}