package tui import ( "encoding/json" "fmt" "maps" "sort" "strings" "time" "git.a-wan.net/alan/pipelines/internal/protocol" "git.a-wan.net/alan/pipelines/internal/stage" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" "github.com/charmbracelet/x/ansi" "github.com/sahilm/fuzzy" ) func (m Model) selectedFailedRun() int64 { if !m.runOpen || m.runStartRequest != "" { return 0 } if m.runDetail != nil { if m.runDetail.Status == "failed" && m.runDetail.FinishedAt != "" && !m.runDetail.Executing { for _, step := range m.runDetail.Steps { if step.AgentActive { return 0 } } return m.runDetail.ID } return 0 } if m.requestedRunID > 0 { return 0 } runs := m.visibleRuns() if len(runs) > 0 { r := runs[min(m.runIndex, len(runs)-1)] if r.Status == "failed" && r.FinishedAt != "" && !r.Executing { return r.ID } } return 0 } func (m Model) retrySelectedRun() (tea.Model, tea.Cmd) { id := m.selectedFailedRun() if id <= 0 { m.runError = "Select a failed run to retry." return m, nil } return m.runRequest(protocol.Message{Type: protocol.RetryRun, RunID: id, RequestKey: fmt.Sprintf("retry-%d", time.Now().UnixNano())}) } func (m Model) selectedRunPipeline() (int64, int) { if !m.runOpen { return 0, 0 } if m.runDetail != nil { return m.runDetail.PipelineID, m.runDetail.Version } if m.requestedRunID > 0 || m.runStartRequest != "" { return 0, 0 } runs := m.visibleRuns() if len(runs) == 0 { return 0, 0 } r := runs[min(m.runIndex, len(runs)-1)] return r.PipelineID, r.Version } func (m Model) openRunPipeline() (tea.Model, tea.Cmd) { id, version := m.selectedRunPipeline() if id <= 0 || version <= 0 { m.runError = "Select a loaded run to open its pipeline." return m, nil } m.closeRuns() // Explicit navigation must not trigger the CLI's initial auto-run flow. if m.cliRun { m.cliStarted = true } return m.requestPipeline(id, version) } func (m *Model) closeRuns() { m.runOpen = false m.keys.runs = false m.requestedRunID = 0 m.runStartRequest = "" m.runDetail = nil m.runError = "" m.runTop = 0 m.runDetailFocus = false m.runPipelineID = 0 m.runFailedOnly = false m.runSearch = newInput() m.runSearchOpen = false m.runGraphFocus = false m.runGraphTop = 0 m.runGraphPan = 0 m.artifactsOpen = false m.artifactIndex = 0 m.artifactTop = 0 m.closeDecision() } func (m Model) visibleRuns() []protocol.RunSummary { query := strings.TrimSpace(m.runSearch.Value()) if m.runPipelineID == 0 && !m.runFailedOnly && query == "" { return m.runs } var runs []protocol.RunSummary for _, run := range m.runs { if (m.runPipelineID == 0 || run.PipelineID == m.runPipelineID) && (!m.runFailedOnly || run.Status == "failed") { runs = append(runs, run) } } if query != "" { if strings.HasPrefix(query, "#") { matched := make([]protocol.RunSummary, 0) for _, run := range runs { if strings.HasPrefix(fmt.Sprintf("#%d", run.ID), query) { matched = append(matched, run) } } return matched } labels := make([]string, len(runs)) for i, run := range runs { labels[i] = fmt.Sprintf("#%d %s v%d %s %s %s %s", run.ID, run.Label(), run.Version, run.Status, run.Outcome, run.CurrentStage, run.Diagnostic) } matched := make([]protocol.RunSummary, 0) for _, match := range fuzzy.Find(query, labels) { matched = append(matched, runs[match.Index]) } return matched } return runs } func (m *Model) selectRunStep(index int) { if m.runStepIndex != index { m.runStepIndex = index m.runTop = 0 } } // Run-detail section identity is defined once here and shared by rendering and // the search/navigation helpers, so the titles, shortcut markers and section // indices cannot drift apart. type runSection struct { Title string Shortcut string } // runSectionNone is the "no section to focus" sentinel used by search navigation. const runSectionNone = -1 // Run-detail section indices, in runSections order. Result and File changes // default open; the rest default collapsed. const ( runSectionProgress = iota runSectionInput runSectionResult runSectionEvidence runSectionDetails runSectionFiles runSectionCount ) var runSections = []runSection{ {"Progress", "s"}, {"Task & input", "i"}, {"Result", "o"}, {"Evidence", "t"}, {"Execution details", "m"}, {"File changes", "d"}, } // runSectionForShortcut maps a section shortcut key to its index. func runSectionForShortcut(key string) (int, bool) { for i, section := range runSections { if section.Shortcut == key { return i, true } } return runSectionNone, false } func (m Model) runSectionKey(index int) string { sequence := 0 if m.runDetail != nil && m.runStepIndex > 0 && m.runStepIndex <= len(m.runDetail.Steps) { sequence = m.runDetail.Steps[m.runStepIndex-1].Sequence } return fmt.Sprintf("%d:%d", sequence, index) } func (m Model) runSectionClosed(index int) bool { if closed, ok := m.runCollapsed[m.runSectionKey(index)]; ok { return closed } return index != runSectionResult && index != runSectionFiles } func (m *Model) toggleRunSection(index int) { closed := m.runSectionClosed(index) m.runCollapsed = maps.Clone(m.runCollapsed) if m.runCollapsed == nil { m.runCollapsed = map[string]bool{} } m.runCollapsed[m.runSectionKey(index)] = !closed } func (m Model) runDetailWidth() int { return max(1, m.width-4) } func (m Model) runPageSize() int { extra := 11 if m.width < 80 { extra = 7 } if m.runDetail != nil && m.height-4 >= 14 { graphHeight, _ := m.runPaneHeights(m.height - 4) extra += graphHeight } return max(1, m.height-extra) } func (m Model) openOpenCodeEvidence() (tea.Model, tea.Cmd) { if m.runDetail == nil { return m, nil } index := -1 for i, step := range m.runDetail.Steps { if step.SessionID != "" { index = i } if step.AgentActive { index = i break } } if index < 0 { m.runError = "No retained agent session for this run yet." return m, nil } m.selectRunStep(index + 1) m.runGraphFocus = false m.runDetailFocus = true m.runTop = 0 if m.runCollapsed == nil { m.runCollapsed = map[string]bool{} } for section := 0; section < runSectionFiles; section++ { m.runCollapsed[m.runSectionKey(section)] = section != runSectionEvidence } return m, nil } func runStatus(status string) string { color := themeMuted switch status { case "succeeded", "completed": color = themeSuccess case "failed": color = themeError case "running", "queued": color = themeAccent case protocol.RunStatusWaiting: color = themeAccent } return lipgloss.NewStyle().Foreground(color).Render(status) } func runDuration(start, end string) string { first, err := time.Parse(time.RFC3339, start) if err != nil { return "—" } last, err := time.Parse(time.RFC3339, end) if err != nil { if end != "" { return "—" } last = time.Now() } return max(time.Duration(0), last.Sub(first)).Round(time.Second).String() } // stageVerdictLines renders a completed stage visit's derived verdict for the // stage view: one line naming the chosen option and its concise reason, and a // second naming the recorded artifacts the reason refers to. It returns nil for a // nil verdict, so the view gains nothing rather than an empty heading, and it // always states the option even when the reason is absent, so the derived choice // is never hidden. func stageVerdictLines(verdict *protocol.StageVerdict) []string { if verdict == nil { return nil } option := strings.TrimSpace(verdict.Option) reason := strings.TrimSpace(verdict.Reason) line := "Verdict:" switch { case option != "" && reason != "": line += " " + option + " · " + reason case option != "": line += " " + option case reason != "": line += " " + reason default: return nil } lines := []string{line} if len(verdict.Artifacts) > 0 { lines = append(lines, "Referenced artifacts: "+strings.Join(verdict.Artifacts, ", ")) } return lines } func valueLines(values map[string]any) []string { if len(values) == 0 { return []string{"No data yet."} } keys := make([]string, 0, len(values)) for key := range values { keys = append(keys, key) } sort.Strings(keys) // Put human conclusions before duplicated handoff context and long evidence. priority := []string{"summary", "reason", "error", "diagnosis", "fix_plan", "diff_summary", "verification_results", "review_findings", "approval", "changed_files", "remaining_risks", "evidence"} ranks := map[string]int{} for i, key := range priority { ranks[key] = i } sort.SliceStable(keys, func(i, j int) bool { a, okA := ranks[keys[i]] b, okB := ranks[keys[j]] if okA != okB { return okA } return okA && a < b }) var lines []string for _, key := range keys { lines = append(lines, lipgloss.NewStyle().Foreground(themeMuted).Bold(true).Render(key)) if text, ok := values[key].(string); ok { lines = append(lines, strings.Split(ansi.Strip(text), "\n")...) } else { encoded, _ := json.MarshalIndent(values[key], "", " ") lines = append(lines, strings.Split(string(encoded), "\n")...) } lines = append(lines, "") } return lines } func evidenceLines(step protocol.RunStep) []string { lines := []string{"Session: " + step.SessionID, "Evidence is a bounded, redacted preview; full evidence remains in the retained configured-harness session."} if step.SessionID == "" { lines = []string{"Recorded result evidence"} } // The effective provider/model this visit ran with, for a model stage; it // reflects any launch-time override rather than the pinned model. if step.Provider != "" || step.Model != "" { lines = append(lines, "Ran with model: "+step.Provider+"/"+step.Model) } if step.Transcript == "" { return append(lines, "No captured tool evidence yet.") } var audit struct { Limits *struct { Timeout string `json:"timeout"` Retries int `json:"retries"` Budget stage.BudgetSnapshot `json:"budget"` } `json:"stage_limits"` Data []json.RawMessage `json:"data"` FormatRepairs []struct { Method string `json:"method"` Accepted bool `json:"accepted"` Diagnostic string `json:"diagnostic"` } `json:"format_repairs"` } if json.Unmarshal([]byte(step.Transcript), &audit) != nil { lines = append(lines, "Audit preview is truncated; showing complete captured messages only.") audit.Data = nil decoder := json.NewDecoder(strings.NewReader(step.Transcript)) if start, err := decoder.Token(); err == nil && start == json.Delim('{') { for decoder.More() { key, err := decoder.Token() if err != nil { break } if key != "data" { if key == "format_repairs" { if decoder.Decode(&audit.FormatRepairs) != nil { break } continue } var skip json.RawMessage if decoder.Decode(&skip) != nil { break } continue } start, err := decoder.Token() if err != nil || start != json.Delim('[') { break } for decoder.More() { var message json.RawMessage if decoder.Decode(&message) != nil { break } audit.Data = append(audit.Data, message) } break } } } for _, repair := range audit.FormatRepairs { lines = append(lines, fmt.Sprintf("JSON format repair: %s · accepted: %t", repair.Method, repair.Accepted), repair.Diagnostic) } if limits := audit.Limits; limits != nil { b := limits.Budget lines = append(lines, fmt.Sprintf("Timeout per attempt: %s · Retries: %d · Attempts: %d", limits.Timeout, limits.Retries, b.Attempts)) if b.LimitUSD > 0 { used := "unknown" if b.USDKnown { used = fmt.Sprintf("$%.6f", b.UsedUSD) } lines = append(lines, fmt.Sprintf("USD budget: %s / $%.6f", used, b.LimitUSD)) } if b.LimitTokens > 0 { used := "unknown" if b.TokensKnown { used = fmt.Sprint(b.UsedTokens) } lines = append(lines, fmt.Sprintf("Token budget: %s / %d", used, b.LimitTokens)) } } count := 0 for i := len(audit.Data) - 1; i >= 0; i-- { var message struct { Content []struct { Type string `json:"type"` Name string `json:"name"` State struct { Status string `json:"status"` Input map[string]any `json:"input"` Content []struct { Text string `json:"text"` } `json:"content"` } `json:"state"` } `json:"content"` } if json.Unmarshal(audit.Data[i], &message) != nil { continue } for _, part := range message.Content { if part.Type != "tool" { continue } count++ lines = append(lines, "", fmt.Sprintf("%d. %s · %s", count, part.Name, part.State.Status)) lines = append(lines, valueLines(part.State.Input)...) for _, result := range part.State.Content { lines = append(lines, strings.Split(ansi.Strip(result.Text), "\n")...) } } } if count == 0 { lines = append(lines, "No tool calls in this preview.") } return lines } func (m Model) runSectionLines(width int) []string { if m.runDetail == nil { return nil } r := m.runDetail titles := make([]string, len(runSections)) for i, section := range runSections { titles[i] = section.Title } summary := append(runResultLines(r), "", strings.Join(completedWorkLines(r), "\n")) if m.runError != "" { summary = append(summary, "Request error: "+m.runError) } editScope := "all files in run directory" if len(r.WritePaths) > 0 { editScope = strings.Join(r.WritePaths, ", ") } var output, input []string if !m.runSectionClosed(runSectionResult) { output = runOutputDocument(r, max(1, width-2)) } if !m.runSectionClosed(runSectionInput) { input = resultDocument(r.Input, max(1, width-2)) } content := [][]string{summary, input, output, {"Choose a stage with n/p to inspect its retained evidence."}, {"Started: " + dateLabel(r.CreatedAt), "Finished: " + dateLabel(r.FinishedAt), "Duration: " + runDuration(r.CreatedAt, r.FinishedAt), "Workspace: " + r.Workspace, "Source hash: " + r.ContentHash, "Stage tools: defined by the pinned pipeline version", "Edit scope: " + editScope}} if r.RetryOf > 0 { content[runSectionDetails] = append(content[runSectionDetails], fmt.Sprintf("Retry of run #%d", r.RetryOf)) } content = append(content, []string{"Select a recorded stage visit with n/p to inspect its retained file diff."}) if m.runStepIndex > 0 && m.runStepIndex <= len(r.Steps) { step := r.Steps[m.runStepIndex-1] titles[runSectionProgress] = "Stage progress" summary = []string{m.progress(m.stepProgressStatus(step)) + " · " + runDuration(step.StartedAt, step.FinishedAt), "Route: " + outcomeLabel(step.Outcome, step.Outcome) + " → " + step.Target} var stageOutput, stageInput, evidence []string if !m.runSectionClosed(runSectionResult) { stageOutput = resultDocument(step.Output, max(1, width-2)) } if !m.runSectionClosed(runSectionInput) { stageInput = resultDocument(step.Input, max(1, width-2)) } if !m.runSectionClosed(runSectionEvidence) { evidence = evidenceLines(step) } stageState := m.progress(m.stepProgressStatus(step)) if step.Outcome != "" && step.Target != "" { stageState += " · " + outcomeLabel(step.Outcome, step.Outcome) + " → " + step.Target } // The verdict leads the stage's result: it states the chosen option and its // concise reason and names the recorded artifacts the reason refers to, so // the derived choice is at the top of the stage view, complementing the // state and output below it without adding a section. head := []string{stageState, ""} if verdict := stageVerdictLines(step.Verdict); len(verdict) > 0 { head = append(head, verdict...) } stageOutput = append(head, stageOutput...) if step.Status == "running" { stageOutput = append([]string{m.loading("Working on " + step.Stage + " · result pending"), ""}, stageOutput...) } if step.Diagnostic != "" { stageOutput = append([]string{lipgloss.NewStyle().Foreground(themeError).Render("Stopped: " + step.Diagnostic), ""}, stageOutput...) } content = [][]string{summary, stageInput, stageOutput, evidence, {"Started: " + dateLabel(step.StartedAt), "Finished: " + dateLabel(step.FinishedAt), "Duration: " + runDuration(step.StartedAt, step.FinishedAt), "Session: " + step.SessionID, fmt.Sprintf("Agent active: %t", step.AgentActive), fmt.Sprintf("Step: %d", step.Sequence)}} if step.Control != nil { content[runSectionDetails] = append(content[runSectionDetails], fmt.Sprintf("Runner visit: %d / %d", step.Control.Visit, step.Control.MaxVisits)) if step.Control.LimitReached { content[runSectionDetails] = append(content[runSectionDetails], "Runtime limit stopped route: "+step.Control.ModelTarget) } for alias, read := range step.Control.Memory { content[runSectionDetails] = append(content[runSectionDetails], fmt.Sprintf("Shared memory %s ← %s (visit sequence %d)", alias, read.Source, read.Sequence)) } } if !m.runSectionClosed(runSectionResult) { content[runSectionResult] = append(content[runSectionResult], "", fileChangesSummary(step), artifactsSummary(step)) } var diff []string if !m.runSectionClosed(runSectionFiles) { // Artifacts have their own grouped view (A); this section is the // observed workspace diff only. diff = stageDiffLines(step) } content = append(content, diff) for _, receipt := range step.Notifications { line := "Notification: " + receipt.Destination + " · " + receipt.Status if receipt.Filename != "" { line += " · " + receipt.Filename } content[runSectionDetails] = append(content[runSectionDetails], line) if receipt.MessageID != "" { content[runSectionDetails] = append(content[runSectionDetails], "Message ID: "+receipt.MessageID) } if receipt.AttachmentURL != "" { content[runSectionDetails] = append(content[runSectionDetails], "Attachment: "+receipt.AttachmentURL) } if receipt.Diagnostic != "" { content[runSectionDetails] = append(content[runSectionDetails], "Notification diagnostic: "+receipt.Diagnostic) } } } var lines []string for _, i := range []int{runSectionResult, runSectionFiles, runSectionProgress, runSectionInput, runSectionEvidence, runSectionDetails} { title := titles[i] marker := "▾" if m.runSectionClosed(i) { marker = "▸" } lines = append(lines, bar(fmt.Sprintf("[%s] %s %s", runSections[i].Shortcut, marker, title), "", width, false)) if !m.runSectionClosed(i) { for _, line := range content[i] { for _, wrapped := range strings.Split(ansi.Wrap(line, max(1, width-2), ""), "\n") { lines = append(lines, " "+wrapped) } } } lines = append(lines, "") } if !m.runGraphFocus { row, _ := runFocusedSection(lines, m.runTop) lines[row] = runHighlight(lines[row], width) } return lines } // The section containing the top visible detail row is the scroll focus. func runFocusedSection(lines []string, top int) (int, string) { row, title := 0, runSections[runSectionResult].Title for i, line := range lines { plain := ansi.Strip(line) if i > top { break } if len(plain) > 4 && plain[0] == '[' && plain[2] == ']' { row = i fields := strings.Fields(plain) if len(fields) > 2 { title = strings.Join(fields[2:], " ") } } } return row, title } func runHighlight(text string, width int) string { text = ansi.Truncate(text, max(1, width), "…") text += strings.Repeat(" ", max(0, width-ansi.StringWidth(text))) return lipgloss.NewStyle().Foreground(themeAccent).Background(themeSelection).Bold(true). Render(surfaceContent(text, themeSelection)) } func runPaneTitle(title, right string, width int, focused bool) string { if focused { return runHighlight(bar("▸ "+title, right, width, true), width) } return bar(title, right, width, false) } func (m Model) runSelectionLabel() string { if m.runDetail != nil && m.runStepIndex > 0 && m.runStepIndex <= len(m.runDetail.Steps) { step := m.runDetail.Steps[m.runStepIndex-1] return fmt.Sprintf("%d. %s", step.Sequence, step.Stage) } return "Run overview" } func (m Model) runActions() string { text := "P pipeline" if m.runDetail != nil { text = "n/p next/prev stage · " + text } if m.selectedRunID() > 0 { text += " · D debug" } if m.runDetail != nil { text += " · a evidence · A artifacts" } if m.runDetail != nil && m.runDetail.Status == protocol.RunStatusWaiting { text += " · c decide" } if m.selectedFailedRun() > 0 { text += " · r retry failed" } return text } func (m Model) runsDetailsView(height int) string { if m.runDetail == nil { title := "Runs · Enter inspect · Esc close" if m.runPipelineID > 0 && m.detail != nil { title = "Runs · " + m.detail.Name + " · Esc back" } if m.runFailedOnly { title = "Failed runs · Esc back" } if m.requestedRunID > 0 || m.runStartRequest != "" { if m.runError != "" { return fitBlock([]string{"Run unavailable", m.runError, "Use :refresh to try again. Esc returns to runs."}, m.width, height) } return fitBlock([]string{m.loading("Loading run…"), m.runError, "Esc returns to runs"}, m.width, height) } rows := []string{} searching := m.runSearchOpen || strings.TrimSpace(m.runSearch.Value()) != "" if searching { m.runSearch.Width = max(1, m.width-12) rows = append(rows, "Search: "+m.runSearch.View()) } runs := m.visibleRuns() start, end := selectionWindow(len(runs), m.runIndex, max(1, (height-4-len(rows))/2)) for i := start; i < end; i++ { r := runs[i] text := fmt.Sprintf("#%d %s · v%d · %s · %s", r.ID, r.Label(), r.Version, m.progress(r.Status), dateLabel(r.FinishedAt)) rows = append(rows, menuOption(text, i == m.runIndex)) rows = append(rows, " "+ansi.Truncate(resultLabel(r), max(1, m.width-6), "…")) } if len(runs) == 0 { rows = append(rows, "No runs yet.") if m.runFailedOnly { rows[len(rows)-1] = "No failed runs." } if strings.TrimSpace(m.runSearch.Value()) != "" { rows[len(rows)-1] = "No matching runs." } } if m.runError != "" { rows = append(rows, strings.Split(ansi.Wrap(lipgloss.NewStyle().Foreground(themeError).Render(m.runError), max(1, m.width-4), ""), "\n")...) } footer := "/ fuzzy search · j/k select · Enter inspect · " + m.runActions() if m.runSearchOpen { footer = "Type to filter · Enter results · Esc clear" } return panel(m.width, height, []string{bar(title, fmt.Sprint(len(runs)), max(1, m.width-4), true)}, rows, footer, true) } r := m.runDetail header := bar(fmt.Sprintf("#%d %s · v%d", r.ID, r.Label(), r.Version), m.progress(r.Status)+" · "+runDuration(r.CreatedAt, r.FinishedAt), m.width, false) if height <= 6 { return fitBlock([]string{header, runHighlight(m.runSelectionLabel(), m.width), m.runActions() + " · Tab pane · Esc back"}, m.width, height) } if m.width < 80 { lines := m.runSectionLines(m.runDetailWidth()) page := max(0, height-3) top := max(0, min(m.runTop, max(0, len(lines)-page))) rows := []string{header, m.runVisitTabs(m.width)} rows = append(rows, lines[top:min(len(lines), top+page)]...) for len(rows) < height-1 { rows = append(rows, "") } continuation := "Details" if top+page < len(lines) { continuation = "↓ More result" } rows = append(rows, bar(continuation, fmt.Sprintf("%d–%d / %d", top+1, min(top+page, len(lines)), len(lines)), m.width, false)) return lipgloss.NewStyle().Background(themeSurface).Foreground(themeText).Render(surfaceContent(fitBlock(rows, m.width, height), themeSurface)) } innerHeight := height - 2 lines := m.runSectionLines(m.runDetailWidth()) page := max(0, innerHeight-5) top := max(0, min(m.runTop, max(0, len(lines)-page))) footerHint := "o result · d diff · s progress · i input · t evidence · m details · A artifacts" if r.Status == protocol.RunStatusWaiting { footerHint += " · c decide" } footer := bar(footerHint, fmt.Sprintf("%d–%d / %d", min(top+1, len(lines)), min(top+page, len(lines)), len(lines)), max(1, m.width-4), false) label := m.runSelectionLabel() if m.runStepIndex > 0 && m.runStepIndex <= len(r.Steps) { step := r.Steps[m.runStepIndex-1] label = fmt.Sprintf("Details · %s · step %d", step.Stage, step.Sequence) label += " · " + runDuration(step.StartedAt, step.FinishedAt) } focused := !m.runGraphFocus if focused { _, section := runFocusedSection(lines, top) label += " · " + section } body := panel(m.width, innerHeight, []string{runPaneTitle(label, "", m.runDetailWidth(), focused), m.runVisitTabs(m.runDetailWidth())}, lines[top:min(len(lines), top+page)], footer, focused) return fitBlock(strings.Split(header+"\n\n"+body, "\n"), m.width, height) }