From b6c62bfd38dc65ce4f9cb166da6b56f3990ff585 Mon Sep 17 00:00:00 2001 From: Dmitrii Iutkin Date: Fri, 20 Nov 2026 18:10:10 +0200 Subject: [PATCH] fix(tui): wizard multiselect Back panic, vanishing validation errors, lost answers, double hint bar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - multiselect: "← Back" is an action row (no checkbox, skipped by select-all, Enter goes back); engine ignores out-of-range indices; stop the prompt program on abnormal exit - textinput: clear validation error only when the value changes; show the full placeholder - wizard: keep the previous answer as the prompt default after going back - remove the duplicate HintBarView from vm, network, auth, registry, objectstorage and settings wizards Co-Authored-By: Claude Sonnet 5.5 --- .ai/skills/new-command.md | 3 +- internal/verda-cli/cmd/auth/wizard.go | 2 - internal/verda-cli/cmd/network/create_test.go | 9 ++ internal/verda-cli/cmd/network/wizard.go | 2 - .../cmd/objectstorage/move_wizard.go | 2 - .../verda-cli/cmd/objectstorage/wizard.go | 2 - internal/verda-cli/cmd/registry/wizard.go | 2 - internal/verda-cli/cmd/settings/CLAUDE.md | 2 +- internal/verda-cli/cmd/settings/theme.go | 6 +- internal/verda-cli/cmd/vm/wizard.go | 14 ++- internal/verda-cli/cmd/vm/wizard_test.go | 13 +++ pkg/tui/bubbletea/multiselect.go | 28 +++++- pkg/tui/bubbletea/multiselect_test.go | 49 ++++++++++ pkg/tui/bubbletea/textinput.go | 20 +++- pkg/tui/bubbletea/textinput_prompt_test.go | 52 ++++++++++ pkg/tui/tui.go | 7 ++ pkg/tui/wizard/engine.go | 60 ++++++++---- pkg/tui/wizard/engine_test.go | 97 +++++++++++++++++++ 18 files changed, 326 insertions(+), 44 deletions(-) diff --git a/.ai/skills/new-command.md b/.ai/skills/new-command.md index e700593e..b912067d 100644 --- a/.ai/skills/new-command.md +++ b/.ai/skills/new-command.md @@ -186,12 +186,13 @@ flow := &wizard.Flow{ Name: "s3-move", Layout: []wizard.ViewDef{ {ID: "progress", View: wizard.NewProgressView(wizard.WithProgressPercent())}, - {ID: "hints", View: wizard.NewHintBarView(wizard.WithHintStyle(bubbletea.HintStyle()))}, }, Steps: []wizard.Step{ /* ... */ }, } ``` +Do not register a `HintBarView`: the wizard composite already renders its own hint bar, and a second one shows contradictory hints. + Per-step rules: - Each `Step` binds to a variable via `Setter`/`Value`/`IsSet`/`Resetter`. `IsSet()==true` (e.g. a `--flag` was passed) makes the engine **skip** the step and propagate `Value()` into the collected map. - `SelectPrompt` with a `Loader` for dynamic lists. A Loader may read earlier steps from `store.Collected()[""]`; declare `DependsOn: []string{""}` so it re-runs when that input changes (e.g. mv's source-object list depends on the chosen source bucket). diff --git a/internal/verda-cli/cmd/auth/wizard.go b/internal/verda-cli/cmd/auth/wizard.go index d2f43606..1df44c4b 100644 --- a/internal/verda-cli/cmd/auth/wizard.go +++ b/internal/verda-cli/cmd/auth/wizard.go @@ -18,7 +18,6 @@ import ( "errors" "strings" - "github.com/verda-cloud/verda-cli/pkg/tui/bubbletea" "github.com/verda-cloud/verda-cli/pkg/tui/wizard" ) @@ -35,7 +34,6 @@ func buildLoginFlow(opts *loginOptions) *wizard.Flow { Name: "auth-login", Layout: []wizard.ViewDef{ {ID: "progress", View: wizard.NewProgressView(wizard.WithProgressPercent())}, - {ID: "hints", View: wizard.NewHintBarView(wizard.WithHintStyle(bubbletea.HintStyle()))}, }, Steps: []wizard.Step{ loginStepProfile(opts), diff --git a/internal/verda-cli/cmd/network/create_test.go b/internal/verda-cli/cmd/network/create_test.go index a129ed61..3b9cd3c3 100644 --- a/internal/verda-cli/cmd/network/create_test.go +++ b/internal/verda-cli/cmd/network/create_test.go @@ -154,3 +154,12 @@ func TestNameIsTrimmedAndCountedInCharacters(t *testing.T) { t.Errorf("name must be trimmed: %s", body) } } + +func TestWizardLayoutHasNoExtraHintBar(t *testing.T) { + t.Parallel() + for _, def := range wizardLayout() { + if _, ok := def.View.(*wizard.HintBarView); ok { + t.Fatalf("view %q duplicates the wizard composite's hint bar", def.ID) + } + } +} diff --git a/internal/verda-cli/cmd/network/wizard.go b/internal/verda-cli/cmd/network/wizard.go index 582641e8..cb3fef3f 100644 --- a/internal/verda-cli/cmd/network/wizard.go +++ b/internal/verda-cli/cmd/network/wizard.go @@ -22,7 +22,6 @@ import ( "github.com/verda-cloud/verdacloud-sdk-go/pkg/verda" - "github.com/verda-cloud/verda-cli/pkg/tui/bubbletea" "github.com/verda-cloud/verda-cli/pkg/tui/wizard" ) @@ -43,7 +42,6 @@ func validateName(s string) error { func wizardLayout() []wizard.ViewDef { return []wizard.ViewDef{ {ID: "progress", View: wizard.NewProgressView(wizard.WithProgressPercent())}, - {ID: "hints", View: wizard.NewHintBarView(wizard.WithHintStyle(bubbletea.HintStyle()))}, } } diff --git a/internal/verda-cli/cmd/objectstorage/move_wizard.go b/internal/verda-cli/cmd/objectstorage/move_wizard.go index e5045bc8..15113b84 100644 --- a/internal/verda-cli/cmd/objectstorage/move_wizard.go +++ b/internal/verda-cli/cmd/objectstorage/move_wizard.go @@ -24,7 +24,6 @@ import ( "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/spf13/cobra" "github.com/verda-cloud/verda-cli/pkg/tui" - "github.com/verda-cloud/verda-cli/pkg/tui/bubbletea" "github.com/verda-cloud/verda-cli/pkg/tui/wizard" cmdutil "github.com/verda-cloud/verda-cli/internal/verda-cli/cmd/util" @@ -99,7 +98,6 @@ func buildMoveFlow(f cmdutil.Factory, client API, st *moveWizardState) *wizard.F Name: "s3-move", Layout: []wizard.ViewDef{ {ID: "progress", View: wizard.NewProgressView(wizard.WithProgressPercent())}, - {ID: "hints", View: wizard.NewHintBarView(wizard.WithHintStyle(bubbletea.HintStyle()))}, }, Steps: []wizard.Step{ moveStepSourceBucket(f, client, st), diff --git a/internal/verda-cli/cmd/objectstorage/wizard.go b/internal/verda-cli/cmd/objectstorage/wizard.go index 6ba4f382..0425e4a5 100644 --- a/internal/verda-cli/cmd/objectstorage/wizard.go +++ b/internal/verda-cli/cmd/objectstorage/wizard.go @@ -20,7 +20,6 @@ import ( "strings" "github.com/verda-cloud/verda-cli/pkg/tui" - "github.com/verda-cloud/verda-cli/pkg/tui/bubbletea" "github.com/verda-cloud/verda-cli/pkg/tui/wizard" "github.com/verda-cloud/verda-cli/internal/verda-cli/options" @@ -43,7 +42,6 @@ func buildConfigureFlow(opts *configureOptions) *wizard.Flow { Name: "s3-configure", Layout: []wizard.ViewDef{ {ID: "progress", View: wizard.NewProgressView(wizard.WithProgressPercent())}, - {ID: "hints", View: wizard.NewHintBarView(wizard.WithHintStyle(bubbletea.HintStyle()))}, }, Steps: []wizard.Step{ configureStepProfile(opts), diff --git a/internal/verda-cli/cmd/registry/wizard.go b/internal/verda-cli/cmd/registry/wizard.go index 99878c68..582ca860 100644 --- a/internal/verda-cli/cmd/registry/wizard.go +++ b/internal/verda-cli/cmd/registry/wizard.go @@ -22,7 +22,6 @@ import ( "strings" "github.com/verda-cloud/verda-cli/pkg/tui" - "github.com/verda-cloud/verda-cli/pkg/tui/bubbletea" "github.com/verda-cloud/verda-cli/pkg/tui/wizard" "github.com/verda-cloud/verda-cli/internal/verda-cli/options" @@ -63,7 +62,6 @@ func buildConfigureFlow(opts *configureOptions) *wizard.Flow { Name: "registry-configure", Layout: []wizard.ViewDef{ {ID: "progress", View: wizard.NewProgressView(wizard.WithProgressPercent())}, - {ID: "hints", View: wizard.NewHintBarView(wizard.WithHintStyle(bubbletea.HintStyle()))}, }, Steps: []wizard.Step{ configureStepProfile(opts), diff --git a/internal/verda-cli/cmd/settings/CLAUDE.md b/internal/verda-cli/cmd/settings/CLAUDE.md index cfec8edc..c558f285 100644 --- a/internal/verda-cli/cmd/settings/CLAUDE.md +++ b/internal/verda-cli/cmd/settings/CLAUDE.md @@ -24,6 +24,6 @@ ## Relationships - `cmdutil.Factory` / `cmdutil.IOStreams` -- standard dependency injection - `options` package -- `SaveSetting()` for persisting to config YAML -- `pkg/tui/wizard` -- wizard engine, `SelectPrompt`, `StaticChoices`, `NewHintBarView` +- `pkg/tui/wizard` -- wizard engine, `SelectPrompt`, `StaticChoices` - `pkg/tui/bubbletea` -- `Themes`, `ThemeNames()`, `GetThemeName()`, `SetThemeByName()`, `HintStyle()`, `Theme` type - `charm.land/lipgloss/v2` -- used in `renderThemePreview` for styled color swatches diff --git a/internal/verda-cli/cmd/settings/theme.go b/internal/verda-cli/cmd/settings/theme.go index 3e710db0..0a7f03cc 100644 --- a/internal/verda-cli/cmd/settings/theme.go +++ b/internal/verda-cli/cmd/settings/theme.go @@ -83,10 +83,8 @@ func selectThemeWizard(cmd *cobra.Command, f cmdutil.Factory, ioStreams cmdutil. } flow := &wizard.Flow{ - Name: "theme-select", - Layout: []wizard.ViewDef{ - {ID: "hints", View: wizard.NewHintBarView(wizard.WithHintStyle(bubbletea.HintStyle()))}, - }, + Name: "theme-select", + Layout: []wizard.ViewDef{}, Steps: []wizard.Step{ { Name: "theme", diff --git a/internal/verda-cli/cmd/vm/wizard.go b/internal/verda-cli/cmd/vm/wizard.go index 7fc651ad..21c52c62 100644 --- a/internal/verda-cli/cmd/vm/wizard.go +++ b/internal/verda-cli/cmd/vm/wizard.go @@ -22,7 +22,6 @@ import ( "strings" "github.com/verda-cloud/verda-cli/pkg/tui" - "github.com/verda-cloud/verda-cli/pkg/tui/bubbletea" "github.com/verda-cloud/verda-cli/pkg/tui/wizard" "github.com/verda-cloud/verdacloud-sdk-go/pkg/verda" @@ -169,14 +168,13 @@ func buildCreateFlow(ctx context.Context, getClient clientFunc, opts *createOpti ) } - layout := []wizard.ViewDef{ - {ID: "hints", View: wizard.NewHintBarView(wizard.WithHintStyle(bubbletea.HintStyle()))}, - } + // Non-nil: a nil Layout selects the default progress view. + layout := []wizard.ViewDef{} if mode == WizardModeDeploy { - layout = append([]wizard.ViewDef{ - {ID: "progress", View: wizard.NewProgressView(wizard.WithProgressPercent())}, - {ID: "summary", View: newSummaryView(ctx, getClient, cache, opts)}, - }, layout...) + layout = append(layout, + wizard.ViewDef{ID: "progress", View: wizard.NewProgressView(wizard.WithProgressPercent())}, + wizard.ViewDef{ID: "summary", View: newSummaryView(ctx, getClient, cache, opts)}, + ) } return &wizard.Flow{ diff --git a/internal/verda-cli/cmd/vm/wizard_test.go b/internal/verda-cli/cmd/vm/wizard_test.go index 04eb9fdb..21a5de74 100644 --- a/internal/verda-cli/cmd/vm/wizard_test.go +++ b/internal/verda-cli/cmd/vm/wizard_test.go @@ -123,3 +123,16 @@ func TestBuildCreateFlowSpotSkipsContract(t *testing.T) { t.Errorf("expected hostname=spot-vm, got %q", opts.Hostname) } } + +func TestBuildCreateFlowHasNoExtraHintBar(t *testing.T) { + t.Parallel() + errClient := func() (*verda.Client, error) { return nil, errors.New("no client in test") } + for _, mode := range []WizardMode{WizardModeDeploy, WizardModeTemplate} { + flow := buildCreateFlow(context.Background(), errClient, &createOptions{}, mode) + for _, def := range flow.Layout { + if _, ok := def.View.(*wizard.HintBarView); ok { + t.Fatalf("mode %v: view %q duplicates the wizard composite's hint bar", mode, def.ID) + } + } + } +} diff --git a/pkg/tui/bubbletea/multiselect.go b/pkg/tui/bubbletea/multiselect.go index 7fd832a0..a693c822 100644 --- a/pkg/tui/bubbletea/multiselect.go +++ b/pkg/tui/bubbletea/multiselect.go @@ -38,6 +38,7 @@ type multiSelectModel struct { max int minErr func(min int) string // resolved: caller override or library default maxErr func(max int) string // resolved: caller override or library default + backItem bool // last choice is a back action, not a selectable value showHints bool customHints []string // nil = derive from bindings bindings []KeyBinding[multiSelectModel] // resolved (defaults + overrides + extras) @@ -101,6 +102,9 @@ func DefaultMultiSelectBindings() []KeyBinding[multiSelectModel] { return nil, true } idx := m.matched[m.cursor] + if m.isBack(idx) { + return nil, true + } if m.selected[idx] { delete(m.selected, idx) m.err = "" @@ -139,6 +143,10 @@ func DefaultMultiSelectBindings() []KeyBinding[multiSelectModel] { Match: MatchKey(tea.KeyEnter), Label: func(*multiSelectModel) string { return "enter confirm" }, Handle: func(m *multiSelectModel, _ tea.KeyPressMsg) (tea.Cmd, bool) { + if len(m.matched) > 0 && m.isBack(m.matched[m.cursor]) { + m.aborted = true + return func() tea.Msg { return GoBackMsg{} }, true + } if m.min > 0 && len(m.selected) < m.min { m.err = m.minErr(m.min) return nil, true @@ -207,7 +215,7 @@ func newMultiSelectModel(prompt string, choices []string, cfg tui.MultiSelectCon } selected := make(map[int]bool) for _, idx := range cfg.Defaults { - if idx >= 0 && idx < len(choices) { + if idx >= 0 && idx < len(choices) && (!cfg.BackItem || idx != len(choices)-1) { selected[idx] = true } } @@ -247,12 +255,17 @@ func newMultiSelectModel(prompt string, choices []string, cfg tui.MultiSelectCon max: cfg.Max, minErr: minErr, maxErr: maxErr, + backItem: cfg.BackItem, showHints: cfg.ShowHints, customHints: cfg.Hints, bindings: bindings, } } +func (m *multiSelectModel) isBack(idx int) bool { + return m.backItem && idx == len(m.choices)-1 +} + func (m *multiSelectModel) refilter() { m.matched = refilter(m.filter, m.choices, m.matched) m.cursor = 0 @@ -284,7 +297,7 @@ func (m *multiSelectModel) moveDown() { func (m *multiSelectModel) toggleAll() { allSelected := true for _, idx := range m.matched { - if !m.selected[idx] { + if !m.isBack(idx) && !m.selected[idx] { allSelected = false break } @@ -295,6 +308,9 @@ func (m *multiSelectModel) toggleAll() { } } else { for _, idx := range m.matched { + if m.isBack(idx) { + continue + } if m.max > 0 && len(m.selected) >= m.max { m.err = m.maxErr(m.max) return @@ -375,6 +391,14 @@ func (m multiSelectModel) View() tea.View { if i == m.cursor { cur = cursorStyle.Render("> ") } + if m.isBack(idx) { + label := dimStyle.Render(m.choices[idx]) + if i == m.cursor { + label = selectedStyle.Render(m.choices[idx]) + } + fmt.Fprintf(&b, " %s %s\n", cur, label) + continue + } check := uncheckStyle.Render("[ ]") label := dimStyle.Render(m.choices[idx]) if m.selected[idx] { diff --git a/pkg/tui/bubbletea/multiselect_test.go b/pkg/tui/bubbletea/multiselect_test.go index 7ae539ce..4aa0e9a4 100644 --- a/pkg/tui/bubbletea/multiselect_test.go +++ b/pkg/tui/bubbletea/multiselect_test.go @@ -748,3 +748,52 @@ func TestMultiSelectModel_ViewShowsError(t *testing.T) { t.Errorf("view should show min error, got:\n%s", view) } } + +func TestMultiSelectModel_BackItem(t *testing.T) { + newBack := func() multiSelectModel { + return newMS([]string{"a", "b", "← Back"}, func(c *tui.MultiSelectConfig) { c.BackItem = true }) + } + + t.Run("select-all skips back", func(t *testing.T) { + m := msCtrl(newBack(), 'a') + if len(m.selected) != 2 || m.selected[2] { + t.Errorf("selected = %v, want only indices 0 and 1", m.selected) + } + m = msCtrl(m, 'a') + if len(m.selected) != 0 { + t.Errorf("second ctrl+a should deselect, selected = %v", m.selected) + } + }) + + t.Run("space on back is a no-op", func(t *testing.T) { + m := newBack() + m.cursor = 2 + m = msKey(m, tea.KeyPressMsg{Code: tea.KeySpace, Text: " "}) + if m.selected[2] { + t.Error("back row must not be selectable") + } + }) + + t.Run("enter on back goes back", func(t *testing.T) { + m := newBack() + m.cursor = 2 + updated, cmd := m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + m = updated.(multiSelectModel) + if m.done { + t.Fatal("enter on back must not complete the prompt") + } + if cmd == nil { + t.Fatal("expected a go-back command") + } + if _, ok := cmd().(GoBackMsg); !ok { + t.Fatalf("expected GoBackMsg, got %T", cmd()) + } + }) + + t.Run("back renders without a checkbox", func(t *testing.T) { + view := newBack().View().Content + if strings.Count(view, "[ ]") != 2 { + t.Errorf("want checkboxes for the two real rows only:\n%s", view) + } + }) +} diff --git a/pkg/tui/bubbletea/textinput.go b/pkg/tui/bubbletea/textinput.go index d8409716..d9d12431 100644 --- a/pkg/tui/bubbletea/textinput.go +++ b/pkg/tui/bubbletea/textinput.go @@ -20,6 +20,7 @@ import ( "charm.land/bubbles/v2/textinput" tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" "github.com/verda-cloud/verda-cli/pkg/tui" ) @@ -109,6 +110,7 @@ func newTextInputModel(prompt string, cfg tui.TextInputConfig) textInputModel { ti.Placeholder = cfg.Placeholder ti.SetValue(cfg.Default) ti.Focus() + syncPlaceholderWidth(&ti) defaults := ApplyBindingOverrides(DefaultTextInputBindings(), cfg.RelabelByID, cfg.HiddenByID) var bindings []KeyBinding[textInputModel] @@ -141,12 +143,28 @@ func (m textInputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } } + before := m.textInput.Value() var cmd tea.Cmd m.textInput, cmd = m.textInput.Update(msg) - m.err = nil + if m.textInput.Value() != before { + m.err = nil + syncPlaceholderWidth(&m.textInput) + } return m, cmd } +// syncPlaceholderWidth: bubbles renders only the first rune of a placeholder +// while Width is 0, so give an empty input the placeholder's width and leave +// typed text unbounded. +func syncPlaceholderWidth(ti *textinput.Model) { + if ti.Value() == "" { + ti.SetWidth(lipgloss.Width(ti.Placeholder)) + return + } + ti.SetWidth(0) + ti.SetCursor(ti.Position()) // recompute scroll offsets computed under the narrow width +} + // Hints derives key hints from the resolved bindings. func (m textInputModel) Hints() []string { return HintsFor(&m, m.bindings) diff --git a/pkg/tui/bubbletea/textinput_prompt_test.go b/pkg/tui/bubbletea/textinput_prompt_test.go index ec9f51e8..c6a3a245 100644 --- a/pkg/tui/bubbletea/textinput_prompt_test.go +++ b/pkg/tui/bubbletea/textinput_prompt_test.go @@ -15,6 +15,8 @@ package bubbletea import ( + "errors" + "strings" "testing" tea "charm.land/bubbletea/v2" @@ -76,3 +78,53 @@ func TestTextInputPrompt_Result_NotDoneInitially(t *testing.T) { t.Fatal("should not be done initially") } } + +type tickMsg struct{} + +func TestTextInputPrompt_ValidationErrorSurvivesNonKeyMessages(t *testing.T) { + cfg := tui.ResolveTextInputConfig([]tui.TextInputOption{ + tui.WithValidation(func(s string) error { + if s == "" { + return errors.New("required") + } + return nil + }), + }) + m := NewTextInputPrompt("Name:", cfg) + + updated, _ := m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + m = updated.(PromptModel) + for _, msg := range []tea.Msg{tickMsg{}, tea.WindowSizeMsg{Width: 80, Height: 24}} { + updated, _ = m.Update(msg) + m = updated.(PromptModel) + } + if !strings.Contains(m.View().Content, "required") { + t.Fatalf("validation error vanished after a non-key message:\n%s", m.View().Content) + } + + updated, _ = m.Update(tea.KeyPressMsg{Code: 'x', Text: "x"}) + m = updated.(PromptModel) + if strings.Contains(m.View().Content, "required") { + t.Fatal("typing should clear the validation error") + } +} + +func TestTextInputPrompt_ShowsFullPlaceholder(t *testing.T) { + cfg := tui.ResolveTextInputConfig([]tui.TextInputOption{tui.WithPlaceholder("default: 90 days")}) + m := NewTextInputPrompt("Expires:", cfg) + if !strings.Contains(m.View().Content, "efault: 90 days") { + t.Fatalf("placeholder truncated:\n%s", m.View().Content) + } +} + +func TestTextInputPrompt_PasteLongerThanPlaceholderIsNotClipped(t *testing.T) { + cfg := tui.ResolveTextInputConfig([]tui.TextInputOption{tui.WithPlaceholder("name")}) + m := NewTextInputPrompt("Name:", cfg) + + pasted := "a-much-longer-pasted-value" + updated, _ := m.Update(tea.PasteMsg{Content: pasted}) + m = updated.(PromptModel) + if !strings.Contains(m.View().Content, pasted) { + t.Fatalf("pasted text clipped:\n%s", m.View().Content) + } +} diff --git a/pkg/tui/tui.go b/pkg/tui/tui.go index b6433832..151fb99e 100644 --- a/pkg/tui/tui.go +++ b/pkg/tui/tui.go @@ -326,6 +326,7 @@ type MultiSelectConfig struct { RelabelByID map[string]string // override individual binding labels by ID HiddenByID []string // suppress these binding labels from the hint bar ExtraBindings any // engine-specific extra/replacement bindings (set via bubbletea options) + BackItem bool // last choice is a "back" action: no checkbox, never selected, Enter on it goes back // MinError / MaxError override the validation messages shown when the // selection count is below Min or above Max. nil = library default. @@ -338,6 +339,12 @@ func WithMultiSelectDefaults(indices []int) MultiSelectOption { return func(c *MultiSelectConfig) { c.Defaults = indices } } +// WithMultiSelectBackItem marks the last choice as a back action rather than +// a selectable value. +func WithMultiSelectBackItem() MultiSelectOption { + return func(c *MultiSelectConfig) { c.BackItem = true } +} + // WithMultiSelectPageSize sets the number of visible items. func WithMultiSelectPageSize(n int) MultiSelectOption { return func(c *MultiSelectConfig) { c.PageSize = n } diff --git a/pkg/tui/wizard/engine.go b/pkg/tui/wizard/engine.go index 29a13289..85e82d63 100644 --- a/pkg/tui/wizard/engine.go +++ b/pkg/tui/wizard/engine.go @@ -65,6 +65,7 @@ type stepRuntime struct { choices []Choice // cached loader results loaded bool // true if loader has been called (distinguishes nil from not-loaded) rewindCount int // how many times auto-rewind has targeted this step + prior any // answer to pre-fill after a user-initiated back; consumed by the next completion } // maxRewindsPerStep is the maximum number of times the engine will auto-rewind @@ -292,6 +293,13 @@ func (e *Engine) runPersistentProgram(ctx context.Context) error { // create their own tea.Programs (spinners, sub-flow prompts) without stdin // conflicts. func (e *Engine) runPerPromptProgram(ctx context.Context) error { + defer func() { + if e.program != nil && e.progErrCh != nil { + e.program.Quit() + <-e.progErrCh + e.program = nil + } + }() return e.stepLoop(ctx) } @@ -495,9 +503,11 @@ func (e *Engine) handlePromptResult(result promptResult, step Step, choices []Ch // Convert indices to values for multiselect. if step.Prompt == MultiSelectPrompt { if indices, ok := value.([]int); ok { - values := make([]string, len(indices)) - for i, idx := range indices { - values[i] = choices[idx].Value + values := make([]string, 0, len(indices)) + for _, idx := range indices { + if idx >= 0 && idx < len(choices) { + values = append(values, choices[idx].Value) + } } value = values } @@ -541,6 +551,20 @@ func (e *Engine) handlePromptResult(result promptResult, step Step, choices []Ch return true, nil } +// promptDefault returns the value to pre-fill: the answer the user gave before +// going back, else the step's Default. +func (e *Engine) promptDefault(step Step) (any, bool) { + if e.current < len(e.steps) { + if prior := e.steps[e.current].prior; prior != nil { + return prior, true + } + } + if step.Default == nil { + return nil, false + } + return step.Default(e.store.Collected()), true +} + // buildPromptModel creates the appropriate PromptModel for a step. func (e *Engine) buildPromptModel(step Step, choices []Choice, canGoBack bool) bubbletea.PromptModel { switch step.Prompt { @@ -550,9 +574,8 @@ func (e *Engine) buildPromptModel(step Step, choices []Choice, canGoBack bool) b labels = append(labels, backLabel) } var opts []tui.SelectOption - if step.Default != nil { - col := e.store.Collected() - if defVal, ok := step.Default(col).(string); ok { + if def, ok := e.promptDefault(step); ok { + if defVal, ok := def.(string); ok { for i, c := range choices { if c.Value == defVal { opts = append(opts, tui.WithSelectDefault(i)) @@ -565,19 +588,19 @@ func (e *Engine) buildPromptModel(step Step, choices []Choice, canGoBack bool) b return bubbletea.NewSelectPrompt(promptLabel(step), labels, cfg) case MultiSelectPrompt: labels := choiceLabels(choices) + var opts []tui.MultiSelectOption if canGoBack { labels = append(labels, backLabel) + opts = append(opts, tui.WithMultiSelectBackItem()) } - var opts []tui.MultiSelectOption if step.Required { opts = append(opts, tui.WithMinSelections(1)) } if step.MinError != nil { opts = append(opts, tui.WithMinSelectionsError(step.MinError)) } - if step.Default != nil { - col := e.store.Collected() - if defVals, ok := step.Default(col).([]string); ok && len(defVals) > 0 { + if def, ok := e.promptDefault(step); ok { + if defVals, ok := def.([]string); ok && len(defVals) > 0 { valSet := make(map[string]bool, len(defVals)) for _, v := range defVals { valSet[v] = true @@ -597,9 +620,8 @@ func (e *Engine) buildPromptModel(step Step, choices []Choice, canGoBack bool) b return bubbletea.NewMultiSelectPrompt(promptLabel(step), labels, cfg) case TextInputPrompt: var opts []tui.TextInputOption - if step.Default != nil { - col := e.store.Collected() - if d, ok := step.Default(col).(string); ok && d != "" { + if def, ok := e.promptDefault(step); ok { + if d, ok := def.(string); ok && d != "" { opts = append(opts, tui.WithDefault(d)) } } @@ -618,9 +640,8 @@ func (e *Engine) buildPromptModel(step Step, choices []Choice, canGoBack bool) b return bubbletea.NewTextInputPrompt(promptLabel(step), cfg) case ConfirmPrompt: var opts []tui.ConfirmOption - if step.Default != nil { - col := e.store.Collected() - if d, ok := step.Default(col).(bool); ok { + if def, ok := e.promptDefault(step); ok { + if d, ok := def.(bool); ok { opts = append(opts, tui.WithConfirmDefault(d)) } } @@ -707,6 +728,7 @@ func (e *Engine) transition(idx int, newState stepState, value any) { rt.value = value rt.choices = nil // invalidate cached choices rt.loaded = false + rt.prior = nil // Only forward progress clears the auto-rewind guard. Resetting it on // every transition was self-defeating: the rewind that follows an empty // loader resets the very step that counted the attempt, so the guard @@ -735,13 +757,17 @@ func (e *Engine) resetRange(from, to int) { // --- Navigation --- -// rewindOne goes back to the nearest editable prior step, clearing everything between. +// rewindOne goes back to the nearest editable prior step, clearing everything +// between. The step landed on keeps its answer as a pre-filled default; its +// loader still re-runs and the store value is cleared, so dependents never see it. func (e *Engine) rewindOne() { from := e.current e.current-- for e.current >= 0 { if e.isEditable(e.current) { + prior := e.steps[e.current].value e.resetRange(e.current, from+1) // +1 to include the abandoned step + e.steps[e.current].prior = prior return } e.current-- diff --git a/pkg/tui/wizard/engine_test.go b/pkg/tui/wizard/engine_test.go index 2b11a64b..688c045b 100644 --- a/pkg/tui/wizard/engine_test.go +++ b/pkg/tui/wizard/engine_test.go @@ -1940,3 +1940,100 @@ func TestEngine_MultiSelectMinErrorPlumbed(t *testing.T) { t.Errorf("expected wizard MinError override in view, got %q", view) } } + +func multiSelectBackFlow(got *[]string) *Flow { + return &Flow{ + Name: "test", + Steps: []Step{ + { + Name: "region", + Prompt: SelectPrompt, + Required: true, + Loader: StaticChoices(Choice{Label: "Finland", Value: "FIN-01"}), + }, + { + Name: "keys", + Prompt: MultiSelectPrompt, + Required: true, + Loader: StaticChoices(Choice{Label: "key-a", Value: "a"}), + Setter: func(v any) { *got = v.([]string) }, + }, + }, + } +} + +// Select-all ticks the "← Back" row too, yielding index len(choices). +func TestEngine_MultiSelect_BackIndexInResultDoesNotPanic(t *testing.T) { + var got []string + engine := newTestEngine([]promptResult{ + selectResult(0), + multiSelectResult([]int{0, 1}), + }) + if err := engine.Run(context.Background(), multiSelectBackFlow(&got)); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(got) != 1 || got[0] != "a" { + t.Errorf("got %v, want [a]", got) + } +} + +func TestEngine_BuildPromptModel_MultiSelectBackIsNotAValue(t *testing.T) { + var got []string + flow := multiSelectBackFlow(&got) + engine := newTestEngine(nil) + engine.flow = flow + engine.steps = make([]stepRuntime, len(flow.Steps)) + engine.current = 1 + choices := []Choice{{Label: "key-a", Value: "a"}} + + model := engine.buildPromptModel(flow.Steps[1], choices, true) + updated, _ := model.Update(tea.KeyPressMsg{Code: 'a', Mod: tea.ModCtrl}) + updated, _ = updated.(bubbletea.PromptModel).Update(tea.KeyPressMsg{Code: tea.KeyDown}) + updated, cmd := updated.(bubbletea.PromptModel).Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + if _, done := updated.(bubbletea.PromptModel).Result(); done { + t.Fatal("Enter on the Back row must not complete the step") + } + if cmd == nil { + t.Fatal("expected a go-back command") + } + if _, ok := cmd().(bubbletea.GoBackMsg); !ok { + t.Fatalf("expected GoBackMsg, got %T", cmd()) + } +} + +func TestEngine_RewindOne_KeepsAnswerAsDefault(t *testing.T) { + flow := &Flow{ + Name: "test", + Steps: []Step{ + {Name: "name", Prompt: TextInputPrompt, Required: true}, + {Name: "gpu", Prompt: SelectPrompt, Required: true, DependsOn: []string{"name"}}, + }, + } + engine := newTestEngine(nil) + engine.flow = flow + engine.steps = make([]stepRuntime, len(flow.Steps)) + engine.transition(0, stateCompleted, "my-pool") + engine.steps[0].loaded = true + engine.current = 1 + + engine.rewindOne() + + if engine.current != 0 { + t.Fatalf("current = %d, want 0", engine.current) + } + if _, ok := engine.Collected()["name"]; ok { + t.Error("store must not keep the rewound answer: dependents would see a stale value") + } + if engine.steps[0].loaded { + t.Error("loader cache must be invalidated so dependent loaders re-run") + } + def, ok := engine.promptDefault(flow.Steps[0]) + if !ok || def != "my-pool" { + t.Errorf("promptDefault = %v, %v; want my-pool", def, ok) + } + + engine.transition(0, stateCompleted, "other") + if _, ok := engine.promptDefault(flow.Steps[0]); ok { + t.Error("prior answer must be dropped once the step is completed again") + } +}