package tui import ( "encoding/json" "fmt" "maps" "sort" "strings" "time" "git.a-wan.net/alan/pipelines/internal/protocol" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" "github.com/charmbracelet/x/ansi" ) 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.runGraphFocus = false m.runGraphTop = 0 m.runGraphPan = 0 } func (m Model) visibleRuns() []protocol.RunSummary { if m.runPipelineID == 0 && !m.runFailedOnly { 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) } } return runs } func (m *Model) selectRunStep(index int) { if m.runStepIndex != index { m.runStepIndex = index m.runTop = 0 } } 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 == 1 || index >= 3 } 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) runSidebarWidth() int { if m.width < 64 { return 0 } return min(30, max(22, m.width/4)) } func (m Model) runDetailWidth() int { if sidebar := m.runSidebarWidth(); sidebar > 0 { return max(1, m.width-sidebar-5) } return max(1, m.width-4) } func (m Model) runPageSize() int { extra := 10 if m.runSidebarWidth() == 0 { extra = 11 } if m.runDetail != nil && m.height-4 >= 14 { extra += (m.height - 4) / 2 } 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 OpenCode 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 < 5; section++ { m.runCollapsed[m.runSectionKey(section)] = section != 3 } 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 } 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() } 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, "Full evidence remains in the retained OpenCode session."} if step.SessionID == "" { lines = []string{"Recorded result evidence"} } if step.Transcript == "" { return append(lines, "No captured tool evidence yet.") } var audit struct { 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) } 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 := []string{"Summary", "Input", "Output", "Tool evidence", "Metadata"} shortcuts := []string{"s", "i", "o", "t", "m"} summary := []string{"Status: " + m.progress(r.Status), "Outcome: " + r.Outcome, fmt.Sprintf("Stages: %d · Current: %s", len(r.Steps), r.CurrentStage), "Started: " + dateLabel(r.CreatedAt), "Finished: " + dateLabel(r.FinishedAt), "Duration: " + runDuration(r.CreatedAt, r.FinishedAt)} if r.Diagnostic != "" { summary = append(summary, lipgloss.NewStyle().Foreground(themeError).Render(r.Diagnostic)) } 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, ", ") } content := [][]string{summary, valueLines(r.Input), valueLines(r.Output), {"Select a stage to inspect its tool calls."}, {"Workspace: " + r.Workspace, "Source hash: " + r.ContentHash, fmt.Sprintf("Shell/edit enabled: %t", r.AllowTools), "Stage tools: defined by the pinned pipeline version", "Edit scope: " + editScope}} if r.RetryOf > 0 { content[4] = append(content[4], fmt.Sprintf("Retry of run #%d", r.RetryOf)) } if m.runStepIndex > 0 && m.runStepIndex <= len(r.Steps) { step := r.Steps[m.runStepIndex-1] summary = []string{"Status: " + m.progress(m.stepProgressStatus(step)), "Route: " + outcomeLabel(step.Outcome, step.Outcome) + " → " + step.Target, "Started: " + dateLabel(step.StartedAt), "Finished: " + dateLabel(step.FinishedAt), "Duration: " + runDuration(step.StartedAt, step.FinishedAt)} if step.Diagnostic != "" { summary = append(summary, lipgloss.NewStyle().Foreground(themeError).Render(step.Diagnostic)) } content = [][]string{summary, valueLines(step.Input), valueLines(step.Output), evidenceLines(step), {"Session: " + step.SessionID, fmt.Sprintf("Agent active: %t", step.AgentActive), fmt.Sprintf("Attempt sequence: %d", step.Sequence)}} for _, receipt := range step.Notifications { line := "Notification: " + receipt.Destination + " · " + receipt.Status if receipt.Filename != "" { line += " · " + receipt.Filename } content[4] = append(content[4], line) if receipt.MessageID != "" { content[4] = append(content[4], "Message ID: "+receipt.MessageID) } if receipt.AttachmentURL != "" { content[4] = append(content[4], "Attachment: "+receipt.AttachmentURL) } if receipt.Diagnostic != "" { content[4] = append(content[4], "Notification diagnostic: "+receipt.Diagnostic) } } } var lines []string for i, title := range titles { marker := "▾" if m.runSectionClosed(i) { marker = "▸" } lines = append(lines, bar(fmt.Sprintf("[%s] %s %s", shortcuts[i], 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, "") } return lines } 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.selectedRunID() > 0 { text += " · D debug" } if m.runDetail != nil { text += " · a OpenCode evidence" } 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 != "" { return fitBlock([]string{"Loading run…", m.runError, "Esc returns to runs"}, m.width, height) } rows := []string{} runs := m.visibleRuns() start, end := selectionWindow(len(runs), m.runIndex, max(1, height-4)) for i := start; i < end; i++ { r := runs[i] text := fmt.Sprintf("#%d %s · v%d · %s · %s", r.ID, r.Name, r.Version, m.progress(r.Status), dateLabel(r.FinishedAt)) rows = append(rows, menuOption(text, i == m.runIndex)) } if len(rows) == 0 { rows = append(rows, "No runs yet.") if m.runFailedOnly { rows[0] = "No failed runs." } } if m.runError != "" { rows = append(rows, m.runError) } return panel(m.width, height, []string{bar(title, fmt.Sprint(len(runs)), max(1, m.width-4), true)}, rows, "j/k select · Enter inspect · "+m.runActions(), true) } r := m.runDetail header := bar(fmt.Sprintf("#%d %s · v%d", r.ID, r.Name, r.Version), m.progress(r.Status)+" · "+runDuration(r.CreatedAt, r.FinishedAt), m.width, false) if height <= 6 { return fitBlock([]string{header, m.runSelectionLabel(), m.runActions() + " · Tab pane · Esc back"}, m.width, height) } innerHeight := height - 2 sidebar := m.runSidebarWidth() rightWidth := m.width var left string if sidebar > 0 { rightWidth = m.width - sidebar - 1 labels := []string{"Run overview"} for _, step := range r.Steps { status := m.progress(m.stepProgressStatus(step)) name := fmt.Sprintf("%d. %s", step.Sequence, step.Stage) budget := max(1, sidebar-6-ansi.StringWidth(status)-3) labels = append(labels, ansi.Truncate(name, budget, "…")+" · "+status) } start, end := selectionWindow(len(labels), m.runStepIndex, max(1, innerHeight-4)) var body []string for i := start; i < end; i++ { prefix := " " if i == m.runStepIndex { prefix = "▸ " } text := ansi.Truncate(prefix+labels[i], sidebar-4, "…") if i == m.runStepIndex { text = bar(text, "", sidebar-4, true) } body = append(body, text) } label := "Stages" if !m.runDetailFocus { label = "▸ " + label } left = panel(sidebar, innerHeight, []string{bar(label, fmt.Sprint(len(r.Steps)), sidebar-4, !m.runDetailFocus)}, body, "1–9 stage · 0 overview", !m.runDetailFocus) } else { innerHeight-- header += "\n" + ansi.Truncate(m.runSelectionLabel()+" · h/l pane · j/k select/scroll", m.width, "…") } lines := m.runSectionLines(max(1, rightWidth-4)) page := max(0, innerHeight-4) top := max(0, min(m.runTop, max(0, len(lines)-page))) footer := fmt.Sprintf("%d–%d / %d · s/i/o/t/m sections · %s · PgUp/Dn · Esc back", min(top+1, len(lines)), min(top+page, len(lines)), len(lines), m.runActions()) label := m.runSelectionLabel() if m.runStepIndex > 0 && m.runStepIndex <= len(r.Steps) { label = fmt.Sprintf("Details · %s · step %d", r.Steps[m.runStepIndex-1].Stage, r.Steps[m.runStepIndex-1].Sequence) } if m.runDetailFocus { label = "▸ " + label } right := panel(rightWidth, innerHeight, []string{bar(label, "", max(1, rightWidth-4), m.runDetailFocus)}, lines[top:min(len(lines), top+page)], footer, m.runDetailFocus) body := right if sidebar > 0 { body = lipgloss.JoinHorizontal(lipgloss.Top, left, " ", right) } return fitBlock(strings.Split(header+"\n\n"+body, "\n"), m.width, height) }