Files
pipelines/internal/tui/artifacts.go
T
alan 889d811858 Fix artifacts-view scrolling, narrow widths and capture wording
The Artifacts view re-clamped its scroll offset to the selected row on every
render, so the tail of the list - a trailing visit that recorded none (running
or finished) and its capture summary - could never be brought on screen, and
the image marker crowded out artifact names at narrow widths.

- Decouple the scroll offset from the selection: add PgUp/PgDn (and ctrl+u/
  ctrl+d) paging, and make G/end select the last artifact and scroll to the
  tail so a trailing visit stays reachable.
- Share artifactContent/clampArtifactTop/revealArtifactSelection between
  selection and render so both agree on the same page.
- Show the [img] marker only while the width still leaves room for a usable
  name, keeping columns aligned either way.
- Advertise the scroll keys in the artifacts footer help.
- Test the omitted-files capture wording, trailing-visit reachability via
  G/end and page scroll, and narrow-width no-overflow; render both the top and
  the scrolled tail in the env-gated live capture test.
- Update the packaged operations reference for the A artifacts view.
2026-10-17 00:24:42 +01:00

470 lines
16 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package tui
import (
"fmt"
"net/url"
"os/exec"
"runtime"
"sort"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
"github.com/atotto/clipboard"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
)
// artifactVisit is one recorded stage visit and the artifacts the server
// observed for it. A visit is kept even when it recorded none, so the view can
// say plainly that nothing was captured rather than omitting it.
type artifactVisit struct {
stage string
visit int
step protocol.RunStep
artifacts []protocol.StageArtifact
}
// runArtifactVisits groups a run's recorded steps by stage and visit in the
// order the run produced them: stages in first-appearance order and each
// stage's visits by sequence. The display visit number is the recorded control
// visit when present, else the position within the stage (mirroring the app's
// runTimeline/runArtifactGroups). Pure, O(n), and it never dedupes steps, so a
// repeated stage's visits stay distinct.
func runArtifactVisits(steps []protocol.RunStep) []artifactVisit {
order := make([]string, 0)
index := map[string]int{}
byStage := make([][]protocol.RunStep, 0)
for _, step := range steps {
at, ok := index[step.Stage]
if !ok {
at = len(order)
index[step.Stage] = at
order = append(order, step.Stage)
byStage = append(byStage, nil)
}
byStage[at] = append(byStage[at], step)
}
visits := make([]artifactVisit, 0, len(steps))
for i, stage := range order {
stageSteps := byStage[i]
sort.SliceStable(stageSteps, func(a, b int) bool { return stageSteps[a].Sequence < stageSteps[b].Sequence })
for j, step := range stageSteps {
visit := j + 1
if step.Control != nil && step.Control.Visit > 0 {
visit = step.Control.Visit
}
visits = append(visits, artifactVisit{stage: stage, visit: visit, step: step, artifacts: step.Artifacts})
}
}
return visits
}
// artifactRef addresses one artifact row in the flat selection order the view
// uses (group order, then recorded order within the group).
type artifactRef struct {
visit int
artifact protocol.StageArtifact
}
func artifactRefs(visits []artifactVisit) []artifactRef {
var refs []artifactRef
for i, visit := range visits {
for _, artifact := range visit.artifacts {
refs = append(refs, artifactRef{visit: i, artifact: artifact})
}
}
return refs
}
// isImageContentType mirrors the app's isImageContentType: an image the
// terminal cannot render and therefore marks distinctly.
func isImageContentType(contentType string) bool {
return strings.HasPrefix(contentType, "image/")
}
// Column geometry for one aligned artifact row. The name and type widths are
// clamped so one very long value cannot widen every other row; the size column
// is right-aligned.
const (
artifactCursorWidth = 2
artifactMarkerWidth = 5 // "[img]" or five spaces
artifactColumnGap = 2
artifactMinName = 8
artifactMinURLWidth = 12
artifactMaxName = 40
artifactMaxType = 28
)
type artifactWidths struct{ name, typ, size int }
func artifactWidthsFor(visits []artifactVisit) artifactWidths {
widths := artifactWidths{}
for _, visit := range visits {
for _, artifact := range visit.artifacts {
widths.name = min(artifactMaxName, max(widths.name, lipgloss.Width(ansi.Strip(artifact.Name))))
widths.typ = min(artifactMaxType, max(widths.typ, lipgloss.Width(ansi.Strip(artifact.ContentType))))
widths.size = max(widths.size, lipgloss.Width(humanBytes(artifact.SizeBytes)))
}
}
return widths
}
func padRight(text string, width int) string {
if deficit := width - lipgloss.Width(text); deficit > 0 {
return text + strings.Repeat(" ", deficit)
}
return text
}
func padLeft(text string, width int) string {
if deficit := width - lipgloss.Width(text); deficit > 0 {
return strings.Repeat(" ", deficit) + text
}
return text
}
// artifactScrollTop returns the offset that keeps the selected row visible in a
// window of page rows, given the current offset and the total line count. It
// scrolls by the minimum needed, so a one-row move shifts the window by one
// rather than recentring it, and it never leaves the viewport past the end.
// Both the selection clamp and the renderer use it, so they can never disagree
// about which row is on screen.
func artifactScrollTop(from, row, page, total int) int {
if page <= 0 {
return 0
}
maxTop := max(0, total-page)
from = max(0, min(from, maxTop))
if row < from {
from = row
} else if row >= from+page {
from = row - page + 1
}
return max(0, min(from, maxTop))
}
// artifactsViewHeight is the frame body height the artifacts panel is rendered
// at, matching View: a one-line header and a one-line footer, each followed by
// a separating row.
func (m Model) artifactsViewHeight() int { return max(0, m.height-4) }
// artifactsPageSize is the number of artifact body rows the panel shows: the
// frame body less the panel's own bar and border, matching artifactsView.
func (m Model) artifactsPageSize() int { return max(0, m.artifactsViewHeight()-4) }
// artifactRowText renders one artifact as an aligned row: the image marker, the
// name, the content type and the human-readable size, with the URL appended
// when the terminal is wide enough. Optional columns drop as width shrinks and
// every cell is truncated, so the row never exceeds width.
func artifactRowText(artifact protocol.StageArtifact, widths artifactWidths, width int, selected bool) string {
prefix := strings.Repeat(" ", artifactCursorWidth)
if selected {
prefix = "› "
}
// Keep the image marker only while it still leaves room for a usable name:
// at very narrow widths the name is more useful than the marker, and the
// decision depends only on width, so every row's columns stay aligned
// whether or not the marker is shown.
if width >= artifactCursorWidth+artifactMarkerWidth+1+artifactMinName {
if isImageContentType(artifact.ContentType) {
prefix += "[img] "
} else {
prefix += strings.Repeat(" ", artifactMarkerWidth) + " "
}
}
available := width - lipgloss.Width(prefix)
if available <= 0 {
return ansi.Truncate(prefix, max(1, width), "")
}
name := ansi.Strip(artifact.Name)
contentType := ansi.Strip(artifact.ContentType)
if strings.TrimSpace(contentType) == "" {
contentType = "unknown type"
}
size := humanBytes(artifact.SizeBytes)
gap := strings.Repeat(" ", artifactColumnGap)
nameCell := func(w int) string { return padRight(ansi.Truncate(name, max(1, w), "…"), w) }
typeCell := padRight(ansi.Truncate(contentType, max(1, widths.typ), "…"), widths.typ)
sizeCell := padLeft(size, widths.size)
switch {
case available >= widths.name+artifactColumnGap+widths.typ+artifactColumnGap+widths.size+artifactColumnGap+artifactMinURLWidth:
urlWidth := available - (widths.name + artifactColumnGap + widths.typ + artifactColumnGap + widths.size + artifactColumnGap)
return prefix + nameCell(widths.name) + gap + typeCell + gap + sizeCell + gap + ansi.Truncate(artifact.URL, max(1, urlWidth), "…")
case available >= widths.name+artifactColumnGap+widths.typ+artifactColumnGap+widths.size:
return prefix + nameCell(widths.name) + gap + typeCell + gap + sizeCell
case available >= artifactMinName+artifactColumnGap+widths.size:
nameWidth := min(widths.name, available-artifactColumnGap-widths.size)
return prefix + nameCell(nameWidth) + gap + sizeCell
default:
return prefix + ansi.Truncate(name, max(1, available), "…")
}
}
// artifactViewContent renders the grouped artifact lines for one content width
// and returns the line index of each flat artifact ref, so selection can scroll
// it into view. Group headers, the shared capture summary and the partial
// capture notes precede each visit's aligned rows.
func artifactViewContent(visits []artifactVisit, widths artifactWidths, width, selected int) ([]string, []int) {
if len(visits) == 0 {
return []string{"No recorded visits yet."}, nil
}
var lines []string
var refLines []int
ref := 0
for i, visit := range visits {
if i > 0 {
lines = append(lines, "")
}
lines = append(lines, lipgloss.NewStyle().Bold(true).Foreground(themeAccent).Render(fmt.Sprintf("%s · visit %d", ansi.Strip(visit.stage), visit.visit)))
lines = append(lines, lipgloss.NewStyle().Foreground(themePrimary).Render(artifactsSummary(visit.step)))
for _, note := range artifactCaptureNotes(visit.step) {
lines = append(lines, lipgloss.NewStyle().Foreground(themeMuted).Render(note))
}
for _, artifact := range visit.artifacts {
lines = append(lines, artifactRowText(artifact, widths, width, ref == selected))
refLines = append(refLines, len(lines)-1)
ref++
}
}
return lines, refLines
}
func (m Model) artifactViewVisits() ([]artifactVisit, []artifactRef) {
if m.runDetail == nil {
return nil, nil
}
visits := runArtifactVisits(m.runDetail.Steps)
return visits, artifactRefs(visits)
}
func (m *Model) openArtifacts() {
if m.runDetail == nil {
m.runError = "Open a run to inspect its artifacts."
return
}
m.artifactsOpen = true
m.artifactIndex = 0
m.artifactTop = 0
}
func (m *Model) selectArtifactByName(name string) {
_, refs := m.artifactViewVisits()
for i, ref := range refs {
if ref.artifact.Name == name {
m.artifactIndex = i
break
}
}
m.clampArtifactScroll()
}
// artifactContent renders the grouped artifact lines and the line index of each
// flat artifact ref for the model's current width and selection, so selection
// and the scroll offset always agree on the same content.
func (m Model) artifactContent() ([]string, []int) {
visits, _ := m.artifactViewVisits()
widths := artifactWidthsFor(visits)
return artifactViewContent(visits, widths, max(1, m.width-4), m.artifactIndex)
}
// clampArtifactTop bounds the scroll offset to the range the current page can
// actually show.
func (m *Model) clampArtifactTop() {
lines, _ := m.artifactContent()
m.artifactTop = max(0, min(m.artifactTop, max(0, len(lines)-m.artifactsPageSize())))
}
// scrollArtifactBy moves the scroll offset by delta and clamps it, independent
// of the selection, so the offset can reach lines past the last artifact (a
// trailing visit's header and capture summary).
func (m *Model) scrollArtifactBy(delta int) {
m.artifactTop += delta
m.clampArtifactTop()
}
// scrollArtifactToEnd puts the window's last line on screen, exposing any
// trailing visits that recorded no artifacts.
func (m *Model) scrollArtifactToEnd() {
lines, _ := m.artifactContent()
m.artifactTop = max(0, len(lines)-m.artifactsPageSize())
}
// revealArtifactSelection nudges the scroll offset by the minimum needed to put
// the selected artifact row on screen; it never scrolls past the end.
func (m *Model) revealArtifactSelection() {
lines, refLines := m.artifactContent()
if m.artifactIndex < len(refLines) {
m.artifactTop = artifactScrollTop(m.artifactTop, refLines[m.artifactIndex], m.artifactsPageSize(), len(lines))
}
}
// clampArtifactScroll keeps the selection valid and its row on screen after a
// selection move.
func (m *Model) clampArtifactScroll() {
if m.runDetail == nil {
m.artifactIndex, m.artifactTop = 0, 0
return
}
_, refs := m.artifactViewVisits()
m.artifactIndex = max(0, min(m.artifactIndex, max(0, len(refs)-1)))
m.revealArtifactSelection()
}
func (m Model) updateArtifacts(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
_, refs := m.artifactViewVisits()
count := len(refs)
switch msg.String() {
case "esc":
m.artifactsOpen = false
return m, nil
case "j", "down":
m.artifactIndex = min(m.artifactIndex+1, max(0, count-1))
case "k", "up":
m.artifactIndex = max(0, m.artifactIndex-1)
case "g", "home":
m.artifactIndex = 0
case "G", "end":
// Select the last artifact and show the tail of the list, so a trailing
// visit that recorded none (running or finished) is on screen.
m.artifactIndex = max(0, count-1)
m.clampArtifactScroll()
m.scrollArtifactToEnd()
return m, nil
case "pgdown", "ctrl+d":
m.scrollArtifactBy(max(1, m.artifactsPageSize()))
return m, nil
case "pgup", "ctrl+u":
m.scrollArtifactBy(-max(1, m.artifactsPageSize()))
return m, nil
case "enter", "o":
if count == 0 {
return m, nil
}
return m, openArtifactCmd(m.url, refs[m.artifactIndex].artifact)
case "y":
if count == 0 {
return m, nil
}
return m, copyArtifactCmd(m.url, refs[m.artifactIndex].artifact)
}
m.clampArtifactScroll()
return m, nil
}
func (m Model) artifactsView(height int) string {
if m.runDetail == nil {
return fitBlock([]string{"Open a run to inspect its artifacts."}, m.width, height)
}
if height <= 0 || m.width <= 0 {
return ""
}
visits, refs := m.artifactViewVisits()
widths := artifactWidthsFor(visits)
selected := max(0, min(m.artifactIndex, max(0, len(refs)-1)))
inner := max(1, m.width-4)
lines, _ := artifactViewContent(visits, widths, inner, selected)
page := max(0, height-4)
// The offset is authoritative and free: selection moves keep the selected
// row on screen, while page scroll and end can move past the last artifact
// to a trailing visit's header and capture summary.
top := max(0, min(m.artifactTop, max(0, len(lines)-page)))
body := lines[top:min(len(lines), top+page)]
title := fmt.Sprintf("Artifacts · run #%d", m.runDetail.ID)
if len(visits) > 0 {
title = fmt.Sprintf("Artifacts · run #%d · %d recorded · %d visits", m.runDetail.ID, len(refs), len(visits))
}
right := ""
if len(refs) > 0 {
right = fmt.Sprintf("%d/%d", selected+1, len(refs))
}
footer := "No artifacts recorded"
if len(refs) > 0 {
// Keep the selected entry's URL available even when the row is too
// narrow to carry its own URL column.
footer = refs[selected].artifact.URL
}
return panel(m.width, height, []string{bar(title, right, inner, true)}, body, footer, true)
}
// artifactActionMsg reports the outcome of handing a URL to the opener or the
// clipboard, so a failure is surfaced instead of silently dropped.
type artifactActionMsg struct {
verb string
url string
err error
}
// openExternal and copyText are seams so tests can observe the resolved URL
// without launching a process or touching the system clipboard.
var (
openExternal = func(target string) error { return openerCommand(target).Run() }
copyText = clipboard.WriteAll
)
// openerCommand is the platform command that hands target to the system opener.
func openerCommand(target string) *exec.Cmd {
switch runtime.GOOS {
case "darwin":
return exec.Command("open", target)
case "windows":
return exec.Command("rundll32", "url.dll,FileProtocolHandler", target)
default:
return exec.Command("xdg-open", target)
}
}
// resolveArtifactURL resolves a server-relative artifact URL against the
// configured websocket server URL by mapping ws/wss to http/https and keeping
// host:port, mirroring the app's ServerUrl.resolveArtifactUrl; it never
// hardcodes a host. An already-absolute http(s) URL is returned unchanged, and
// a blank or invalid configuration fails.
func resolveArtifactURL(serverURL, artifactURL string) (string, bool) {
target := strings.TrimSpace(artifactURL)
if target == "" {
return "", false
}
if strings.HasPrefix(target, "http://") || strings.HasPrefix(target, "https://") {
return target, true
}
parsed, err := url.Parse(strings.TrimSpace(serverURL))
if err != nil || (parsed.Scheme != "ws" && parsed.Scheme != "wss") || parsed.Hostname() == "" {
return "", false
}
scheme := "http"
if parsed.Scheme == "wss" {
scheme = "https"
}
if !strings.HasPrefix(target, "/") {
target = "/" + target
}
return scheme + "://" + parsed.Host + target, true
}
func artifactURLAction(verb, serverURL string, artifact protocol.StageArtifact) tea.Cmd {
resolved, ok := resolveArtifactURL(serverURL, artifact.URL)
if !ok {
return func() tea.Msg {
return artifactActionMsg{verb: verb, err: fmt.Errorf("no server URL to resolve %q", artifact.Name)}
}
}
action := openExternal
if verb == "copy" {
action = copyText
}
return func() tea.Msg {
if err := action(resolved); err != nil {
return artifactActionMsg{verb: verb, url: resolved, err: err}
}
return artifactActionMsg{verb: verb, url: resolved}
}
}
func openArtifactCmd(serverURL string, artifact protocol.StageArtifact) tea.Cmd {
return artifactURLAction("open", serverURL, artifact)
}
func copyArtifactCmd(serverURL string, artifact protocol.StageArtifact) tea.Cmd {
return artifactURLAction("copy", serverURL, artifact)
}