package tui import ( "fmt" "strconv" "strings" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" "github.com/charmbracelet/x/ansi" "git.a-wan.net/alan/pipelines/internal/draft" "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" ) func selectionWindow(count, index, capacity int) (int, int) { start := max(0, min(index-capacity+1, max(0, count-capacity))) return start, min(count, start+capacity) } // searchNav remembers the step and section to focus once an asynchronously // requested run arrives, so Enter on a step/artifact/field match lands exactly // where it matched. type searchNav struct { runID int64 sequence int section int artifact string } // requestSearch asks the server for the current query. At most one request is in // flight: a keystroke while a request is outstanding is coalesced and the latest // text is sent when the response arrives. Stale responses are dropped by ID, so // no keystroke triggers overlapping or unbounded scans. The server owns parsing // (status words, dates and the optional kind filter), so the client sends the // raw text and needs no second matcher. func (m Model) requestSearch() (tea.Model, tea.Cmd) { query := strings.TrimSpace(m.commandInput.Value()) if m.conn == nil { m.searchResults = nil m.searchText = "" return m, nil } if m.searchInFlight { m.searchQueued = true return m, nil } m.nextID++ m.searchRequest = strconv.FormatUint(m.nextID, 10) m.searchInFlight = true m.searchError = "" return m, m.send(protocol.Message{Type: protocol.Search, ID: m.searchRequest, Search: &protocol.SearchRequest{Query: query}}) } func (m *Model) closeSearch() { m.paletteOpen = false m.searchOpen = false m.keys.palette = false m.searchResults = nil m.searchText = "" m.searchRequest = "" m.searchInFlight = false m.searchQueued = false m.searchError = "" } func (m Model) updateSearch(msg tea.KeyMsg) (tea.Model, tea.Cmd) { items := m.searchResults switch msg.String() { case "esc": m.closeSearch() return m, nil case "down", "ctrl+n": m.commandIndex = min(m.commandIndex+1, max(0, len(items)-1)) return m, nil case "up", "ctrl+p": m.commandIndex = max(0, m.commandIndex-1) return m, nil case "enter": if len(items) == 0 { return m, nil } return m.openSearchResult(items[min(m.commandIndex, len(items)-1)]) } var cmd tea.Cmd m.commandInput, cmd = m.commandInput.Update(msg) m.commandIndex = 0 updated, send := m.requestSearch() return updated, tea.Batch(cmd, send) } // openSearchResult navigates straight to a result: a pipeline/version opens its // detail, and a run/step/artifact/field match opens the run with that step and // section selected once the run arrives. func (m Model) openSearchResult(result protocol.SearchResult) (tea.Model, tea.Cmd) { m.closeSearch() switch result.Kind { case protocol.SearchKindPipeline: if result.Pipeline != nil { return m.requestPipeline(result.Pipeline.ID, result.Pipeline.Version) } case protocol.SearchKindVersion: if result.Version != nil { return m.requestPipeline(result.Version.PipelineID, result.Version.Version) } } runID, sequence, field, artifact := searchResultTarget(result) if runID <= 0 { return m, nil } m.closeRuns() m.runOpen = true m.keys.runs = true m.runIndex = 0 nav := &searchNav{runID: runID, sequence: sequence, section: runSectionNone} switch result.Kind { case protocol.SearchKindStep: nav.section = runSectionProgress case protocol.SearchKindField: nav.section = sectionForField(field) case protocol.SearchKindArtifact: // Artifacts have their own grouped view; open it with the matched entry // selected so the operator can open or copy its URL. nav.section = runSectionNone nav.artifact = artifact } m.pendingRunNav = nav return m.runRequest(protocol.Message{Type: protocol.GetRun, RunID: runID}) } // searchResultTarget returns the run, step, field and artifact a result points // at, read from its typed payload rather than re-parsing the target token. func searchResultTarget(result protocol.SearchResult) (runID int64, sequence int, field, artifact string) { switch result.Kind { case protocol.SearchKindRun: if result.Run != nil { runID = result.Run.ID } case protocol.SearchKindStep: if result.Step != nil { runID, sequence = result.Step.RunID, result.Step.Sequence } case protocol.SearchKindField: if result.Field != nil { runID, sequence, field = result.Field.RunID, result.Field.Sequence, result.Field.Field } case protocol.SearchKindArtifact: if result.Artifact != nil { runID, sequence, artifact = result.Artifact.RunID, result.Artifact.Sequence, result.Artifact.Name } } return runID, sequence, field, artifact } func sectionForField(field string) int { switch field { case "input": return runSectionInput case "output": return runSectionResult case "evidence", "transcript": return runSectionEvidence default: return runSectionDetails } } // applyRunNav selects the matched step and scrolls to the matched section. func (m *Model) applyRunNav(nav searchNav) { if m.runDetail == nil { return } if nav.sequence > 0 { for i, step := range m.runDetail.Steps { if step.Sequence == nav.sequence { m.selectRunStep(i + 1) break } } } if nav.section != runSectionNone { m.runGraphFocus = false m.runDetailFocus = true m.focusRunSection(nav.section) } if nav.section == runSectionNone && nav.artifact != "" { m.openArtifacts() m.selectArtifactByName(nav.artifact) } } // focusRunSection opens the section and scrolls the run detail to its header, // reusing the same shortcut markers runSectionLines renders. func (m *Model) focusRunSection(section int) { if m.runDetail == nil || section < 0 || section >= runSectionCount { return } if m.runCollapsed == nil { m.runCollapsed = map[string]bool{} } m.runCollapsed[m.runSectionKey(section)] = false marker := "[" + runSections[section].Shortcut + "]" for i, line := range m.runSectionLines(m.runDetailWidth()) { if strings.HasPrefix(ansi.Strip(line), marker) { m.runTop = i return } } } // searchBadge is the short type label a result shows. A pipeline version folds // into the pipeline badge and a body-text field into the match badge, so the // row reads the way the operator thinks about it rather than the wire kind. func searchBadge(kind string) string { switch kind { case protocol.SearchKindVersion: return "pipeline" case protocol.SearchKindField: return "match" default: return kind } } // markedSnippet brackets the first case-insensitive occurrence of query in a // field snippet so the matched part is distinguishable without relying on // colour, then clips the result to budget runes with the bracketed match kept // inside the window. It tracks the exact marker span it inserts, so a snippet // that itself contains '[' cannot make the window centre on the wrong bracket. // The server centres the snippet on the match, so the text is present // case-insensitively; the snippet is shown unchanged when it is not. The budget // excludes the row's two-rune indent, since the result is clipped before the // row is styled. func markedSnippet(snippet, query string, budget int) string { runes := []rune(snippet) needle := []rune(strings.TrimSpace(query)) if len(needle) == 0 || len(runes) == 0 { return snippet } at := protocol.RuneIndexFold(runes, needle) if at < 0 { return snippet } marked := string(runes[:at]) + "[" + string(runes[at:at+len(needle)]) + "]" + string(runes[at+len(needle):]) markedRunes := []rune(marked) if budget <= 0 || len(markedRunes) <= budget { return marked } // The inserted '[' sits at rune `at` and the ']' at at+len(needle)+1, so the // span to keep in view is [at, at+len(needle)+2). spanStart, spanEnd := at, at+len(needle)+2 if spanEnd-spanStart >= budget { return string(markedRunes[:budget]) } lo := max(0, spanStart-(budget-(spanEnd-spanStart))/2) hi := min(len(markedRunes), lo+budget) lo = max(0, hi-budget) out := string(markedRunes[lo:hi]) if lo > 0 { out = "…" + out } if hi < len(markedRunes) { out += "…" } return out } // searchRowLines renders one result. A body-text match keeps its (windowed) // snippet on its own indented line so the marker is visible at the popup width // instead of being clipped after a long badge and label. func searchRowLines(result protocol.SearchResult, query string, snippetBudget int) []string { head := "[" + searchBadge(result.Kind) + "] " + result.Label() if result.Kind == protocol.SearchKindField && result.Field != nil && result.Field.Snippet != "" { return []string{head, " " + markedSnippet(result.Field.Snippet, query, snippetBudget)} } return []string{head} } func (m Model) searchView(height int) string { field := m.commandInput field.Width = max(1, min(64, m.width-10)) inner := min(72, max(1, m.width-6)) snippetBudget := max(8, inner-4) lines := []string{"Search", field.View(), ""} items := m.searchResults query := strings.TrimSpace(m.commandInput.Value()) switch { case m.searchError != "": lines = append(lines, "Search failed: "+m.searchError) case len(items) == 0 && m.searchInFlight: lines = append(lines, "Searching…") case len(items) == 0 && query != "": lines = append(lines, "No matches for "+query) case len(items) == 0: lines = append(lines, "Type to search pipelines, runs, steps, text and artifacts.") } // A field match renders two lines, so budget the window by rendered lines. start, end := selectionWindow(len(items), m.commandIndex, max(1, (height-4)/2)) for i := start; i < end; i++ { prefix := " " if i == m.commandIndex { prefix = "› " } for j, row := range searchRowLines(items[i], m.searchText, snippetBudget) { if j == 0 { row = prefix + row } lines = append(lines, menuOption(row, i == m.commandIndex)) } } return popup(m.width, height, 72, lines) } func (m Model) requestPipeline(id int64, version int) (tea.Model, tea.Cmd) { m.requestedPipelineID = id m.requestedVersion = version m.detailLoading = true m.detailError = "" m.keys.detail = true if m.conn == nil { m.status = "Reconnecting…" m.detailRequest = "" if m.reconnecting { return m, nil } m.reconnecting = true return m, m.connect() } m.nextID++ m.detailRequest = strconv.FormatUint(m.nextID, 10) m.detailLoading = true m.detailError = "" m.keys.detail = true return m, m.send(protocol.Message{Type: protocol.GetPipeline, ID: m.detailRequest, PipelineID: id, Version: version}) } func (m Model) goHome() Model { m.requestedPipelineID = 0 m.requestedVersion = 0 m.keys.detail = false m.detail = nil m.detailRequest = "" m.detailLoading = false m.detailError = "" m.pipelineTop = 0 m.graphPan = 0 m.stageIndex = 0 m.stageTop = 0 m.stageFocus = false m.versionsOpen = false m.keys.versions = false return m } func (m Model) openVersions() (tea.Model, tea.Cmd) { if m.detail == nil || m.detailLoading { m.appendLine("open a pipeline first") return m, nil } m.versionsOpen = true m.keys.versions = true m.versionIndex = 0 for i, v := range m.detail.Versions { if v.Version == m.detail.Version { m.versionIndex = i break } } return m, nil } func (m Model) updateVersions(msg tea.KeyMsg) (tea.Model, tea.Cmd) { versions := m.detail.Versions switch msg.String() { case "esc": m.versionsOpen = false m.keys.versions = false return m, nil case "j", "down": m.versionIndex = min(m.versionIndex+1, max(0, len(versions)-1)) case "k", "up": m.versionIndex = max(0, m.versionIndex-1) case "enter": if len(versions) == 0 { return m, nil } m.versionsOpen = false m.keys.versions = false return m.requestPipeline(m.detail.ID, versions[m.versionIndex].Version) } return m, nil } func (m Model) versionsView(height int) string { lines := []string{"Versions · " + m.detail.Name, "Select a version to view or edit", ""} start, end := selectionWindow(len(m.detail.Versions), m.versionIndex, max(1, height-5)) for i := start; i < end; i++ { v := m.detail.Versions[i] prefix := " " if i == m.versionIndex { prefix = "› " } label := "" if v.Version == m.detail.Version { label += " · viewing" } if v.Version == m.detail.LatestVersion { label += " · latest" } lines = append(lines, menuOption(fmt.Sprintf("%sv%d · %d stages · %s%s", prefix, v.Version, v.Stages, dateLabel(v.CreatedAt), label), i == m.versionIndex)) } return popup(m.width, height, 76, lines) } func (m Model) editPipeline() (tea.Model, tea.Cmd) { if m.detail == nil || m.detailLoading { m.appendLine("open a pipeline first") return m, nil } if m.submitID != "" { m.appendLine("submission already in progress") return m, nil } return m.openAuthorPicker(editedMsg{name: m.detail.Name, source: pipeline.ExecutionSource(m.detail.Source), baseVersion: m.detail.LatestVersion}) } func (m Model) updatePipeline(msg tea.KeyMsg) (tea.Model, tea.Cmd) { switch msg.String() { case "esc": return m.goHome(), nil case "v": return m.openVersions() case "r": return m.openRuns() case "c", "enter": if m.stageFocus { m.stageConfigExpanded = !m.stageConfigExpanded if m.stageConfigExpanded { _, _, labels := m.stageColumnsWithHeaders(max(1, m.width-4)) for i, label := range labels { if strings.Contains(label, "CONFIGURATION") { m.stageTop = i break } } } } else { m.revealStage() } case "e": return m.editPipeline() case "s": if m.pendingDraft != nil { m.confirmOpen = true m.keys.confirm = true } case "j", "down": if m.stageFocus { m.stageTop++ } else { m.pipelineTop++ } case "k", "up": if m.stageFocus { m.stageTop-- } else { m.pipelineTop-- } case "ctrl+d", "pgdown": g := m.pipelineGeometry(max(0, m.height-4)) if m.stageFocus { m.stageTop += max(1, (g.stageHeight-6)/2) } else { m.pipelineTop += max(1, (g.graphHeight-5)/2) } case "ctrl+u", "pgup": g := m.pipelineGeometry(max(0, m.height-4)) if m.stageFocus { m.stageTop -= max(1, (g.stageHeight-6)/2) } else { m.pipelineTop -= max(1, (g.graphHeight-5)/2) } case "tab", "shift+tab": m.stageFocus = !m.stageFocus if !m.stageFocus { m.revealStage() } case "1", "2", "3", "4", "5", "6", "7", "8", "9": if m.detail != nil && len(m.detail.Graph.Stages) > 0 { index := int(msg.String()[0] - '1') if index >= len(m.detail.Graph.Stages) { break } m.stageIndex = index m.stageTop = 0 m.revealStage() } case "[", "]", "n", "p": if m.detail != nil && len(m.detail.Graph.Stages) > 0 { delta := 1 if msg.String() == "[" || msg.String() == "p" { delta = -1 } m.stageIndex = (m.stageIndex + delta + len(m.detail.Graph.Stages)) % len(m.detail.Graph.Stages) m.stageTop = 0 m.revealStage() } case "h", "left": m.graphPan = max(0, m.graphPan-4) case "l", "right": width := 0 for _, line := range m.graphLines() { width = max(width, lipgloss.Width(line)) } m.graphPan = min(m.graphPan+4, max(0, width-max(1, m.pipelineGeometry(max(0, m.height-4)).graphWidth-4))) } m.clampPipelineScroll() return m, nil } func (m Model) updateConfirm(msg tea.KeyMsg) (tea.Model, tea.Cmd) { if msg.String() == "esc" { m.confirmOpen = false m.keys.confirm = false m.draftNameInput = newInput() m.templateConfirm = false return m, nil } if m.submitID != "" { return m, nil } if m.pendingDraft == nil { m.confirmOpen = false m.keys.confirm = false return m, nil } if m.templateConfirm { if msg.Type != tea.KeyEnter && msg.String() != "ctrl+s" { var cmd tea.Cmd m.draftNameInput, cmd = m.draftNameInput.Update(msg) return m, cmd } name := strings.TrimSpace(m.draftNameInput.Value()) if name == "" || len(name) > 200 || strings.ContainsAny(name, "\r\n\x00") { m.submitNotice = "Name must be 1–200 bytes without line breaks or NUL." return m, nil } if m.pendingDraft.path == "" { d, err := draft.Create(name, m.pendingDraft.source, m.url, true, 0) if err != nil { m.submitNotice = "Could not retain draft: " + err.Error() return m, nil } m.pendingDraft.path = d.Path } else if err := draft.SetName(m.pendingDraft.path, name); err != nil { m.submitNotice = "Could not save draft name: " + err.Error() return m, nil } m.pendingDraft.name = name msg = tea.KeyMsg{Type: tea.KeyEnter} } if strings.TrimSpace(m.pendingDraft.name) == "" { if m.draftNameInput.Prompt != "Name: " { m.draftNameInput = newInput() m.draftNameInput.Prompt = "Name: " m.draftNameInput.Placeholder = "Pipeline name" m.draftNameInput.Focus() } if msg.Type == tea.KeyEnter { name := strings.TrimSpace(m.draftNameInput.Value()) if name == "" || len(name) > 200 || strings.ContainsAny(name, "\r\n\x00") { m.submitNotice = "Name must be 1–200 bytes without line breaks or NUL." return m, nil } if m.pendingDraft.path == "" { d, err := draft.Create(name, m.pendingDraft.source, m.url, m.pendingDraft.createOnly, m.pendingDraft.baseVersion) if err != nil { m.submitNotice = "Could not retain draft: " + err.Error() return m, nil } m.pendingDraft.path = d.Path } else { if err := draft.SetName(m.pendingDraft.path, name); err != nil { m.submitNotice = "Could not save draft name: " + err.Error() return m, nil } } m.pendingDraft.name = name for i := range m.draftItems { if m.draftItems[i].Path == m.pendingDraft.path { m.draftItems[i].Name = name } } m.draftNameInput = newInput() m.submitNotice = "" return m, nil } var cmd tea.Cmd m.draftNameInput, cmd = m.draftNameInput.Update(msg) return m, cmd } switch msg.String() { case "e": m.confirmOpen = false m.keys.confirm = false return m.confirmMutation("Edit retained draft?", func() tea.Cmd { return editDraftMode(m.pendingDraft.name, m.pendingDraft.source, true, m.pendingDraft.createOnly, draft.Draft{Path: m.pendingDraft.path, Name: m.pendingDraft.name, Server: m.url, CreateOnly: m.pendingDraft.createOnly, BaseVersion: m.pendingDraft.baseVersion}) }) case "s", "enter": if m.conn == nil { m.submitNotice = "Not connected; draft retained" return m, nil } m.nextID++ m.submitID = strconv.FormatUint(m.nextID, 10) m.submitNotice = "Updating pipeline…" if m.pendingDraft.createOnly || m.pendingDraft.baseVersion == 0 { m.submitNotice = "Creating pipeline…" } m.appendLine(m.submitNotice + " " + m.pendingDraft.name) return m, m.send(protocol.Message{Type: protocol.Submit, ID: m.submitID, Name: m.pendingDraft.name, Source: m.pendingDraft.source, CreateOnly: m.pendingDraft.createOnly, ExpectedVersion: m.pendingDraft.baseVersion}) } return m, nil } func (m Model) confirmView(height int) string { if m.templateConfirm { field := m.draftNameInput field.Width = max(1, min(60, m.width-12)) cancelHint := "Esc back" if m.pendingDraft.path != "" { cancelHint = "Esc keep draft" } lines := []string{"Create pipeline", field.View(), "Uses this template without opening an editor.", "Creates a new pipeline; existing pipelines are never replaced.", "Destination: " + m.url, m.submitNotice, "Enter create pipeline · " + cancelHint} if strings.Contains(m.pendingDraft.source, "```schedule") { lines = append(lines, "WARNING: creation activates the included schedule.") } return popup(m.width, height, 90, lines) } if strings.TrimSpace(m.pendingDraft.name) == "" { field := m.draftNameInput if field.Prompt != "Name: " { field = newInput() field.Prompt = "Name: " field.Placeholder = "Pipeline name" field.Focus() } field.Width = max(1, min(60, m.width-12)) hint := "Enter save name and review · Esc keep draft" if m.pendingDraft.path == "" { hint = "Enter save draft and review · Esc back" } return popup(m.width, height, 76, []string{"Name this pipeline", "", field.View(), m.submitNotice, hint}) } lines := []string{"Update pipeline", m.pendingDraft.name, "", "Creates a new immutable version; previous versions are retained.", "s update pipeline · e edit again · Esc keep draft"} if m.pendingDraft.createOnly || m.pendingDraft.baseVersion == 0 { lines[0] = "Create pipeline" lines[3] = "Creates a new pipeline after confirmation." lines[4] = "s create pipeline · e edit again · Esc keep draft" } lines = append(lines, "Destination: "+m.url) if strings.Contains(m.pendingDraft.source, "```schedule") { lines = append(lines, "WARNING: submitting activates the included schedule.") } if m.submitNotice != "" { lines = append(lines, "", m.submitNotice) } return popup(m.width, height, 76, lines) }