Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix(onboarding): stop modified arrow keys from picking an option (#1077)

Rudy Mizrahi Celekliee9d3ae14acd
diff --git a/cli/beacon/internal/onboarding/picker.go b/cli/beacon/internal/onboarding/picker.go
index d3a55142..f63a5039 100644
--- a/cli/beacon/internal/onboarding/picker.go
+++ b/cli/beacon/internal/onboarding/picker.go
@@ -7,6 +7,7 @@ import (
"os"
"strings"
+ tea "github.com/charmbracelet/bubbletea"
"golang.org/x/term"
)
@@ -16,15 +17,6 @@ import (
// of them should lose the ability to answer.
var errRawUnavailable = errors.New("raw terminal mode unavailable")
-// ANSI control sequences. Only the handful worth using: anything more elaborate
-// misbehaves across the range of terminals people actually run.
-const (
- ansiUp = "\x1b[%dA"
- ansiClearLine = "\r\x1b[K"
- ansiHideCur = "\x1b[?25l"
- ansiShowCur = "\x1b[?25h"
-)
-
const (
colorReset = "\x1b[0m"
colorDim = "\x1b[2m"
@@ -48,182 +40,150 @@ func choices(labels []string) []choice {
return rows
}
-// renderedLines is how many terminal lines a picker draws: one per option, one per
-// detail, and the key hint.
-func renderedLines(options []choice) int {
- n := 1
- for _, option := range options {
- n++
- if option.Detail != "" {
- n++
+// menuStep is how far a key moves the cursor of an arrow-key menu: -1 up, 1 down, 0 for
+// any other key. An arrow moves whatever modifier is held; terminals send Shift+Up as
+// ESC [ 1 ; 2 A, and the picker once read those parameter digits as number keys.
+func menuStep(msg tea.KeyMsg) int {
+ switch msg.Type {
+ case tea.KeyUp, tea.KeyShiftUp, tea.KeyCtrlUp, tea.KeyCtrlShiftUp:
+ return -1
+ case tea.KeyDown, tea.KeyShiftDown, tea.KeyCtrlDown, tea.KeyCtrlShiftDown:
+ return 1
+ case tea.KeyRunes:
+ if len(msg.Runes) == 1 && !msg.Alt {
+ return runeStep(msg.Runes[0])
}
}
- return n
+ return 0
}
-// keyAction is what a keypress means to the picker.
-type keyAction int
+// runeStep is menuStep for the vim keys.
+func runeStep(r rune) int {
+ switch r {
+ case 'k', 'K':
+ return -1
+ case 'j', 'J':
+ return 1
+ }
+ return 0
+}
-const (
- keyUp keyAction = iota
- keyDown
- keySelect
- keyPick
- keyAbort
-)
+// pickerModel is the inline arrow-key menu. chosen stays -1 until an option is picked,
+// so a model that quit with it unset was cancelled.
+type pickerModel struct {
+ options []choice
+ color bool
+ width int
+ selected int
+ chosen int
+ done bool
+}
-// keyEvent is one decoded keypress. index is meaningful only for keyPick.
-type keyEvent struct {
- action keyAction
- index int
+func newPickerModel(options []choice, color bool, width int) pickerModel {
+ return pickerModel{options: options, color: color, width: width, chosen: -1}
}
-// selectOption renders an arrow-key menu and returns the index the user chose.
-//
-// The terminal is restored on every exit path, including Ctrl-C: raw mode disables
-// the interrupt signal, so leaving without restoring would hand the user back a shell
-// with no echo.
+// selectOption runs the arrow-key menu inline, below whatever the caller printed, and
+// returns the index the user chose. The menu is erased on every exit, leaving the cursor
+// where it began so the caller's confirmation line takes its place.
func selectOption(in *os.File, out io.Writer, options []choice, color bool) (int, error) {
fd := int(in.Fd())
- state, err := term.MakeRaw(fd)
- if err != nil {
+ if !term.IsTerminal(fd) {
return 0, errRawUnavailable
}
- defer func() {
- _ = term.Restore(fd, state)
- fmt.Fprint(out, ansiShowCur)
- }()
-
- fmt.Fprint(out, ansiHideCur)
-
- // Every drawn line is clipped to the terminal width so nothing wraps: the redraw and
- // the final clear count lines, and a wrapped line would make them eat whatever the
- // caller printed above the menu.
- width, _, sizeErr := term.GetSize(fd)
- if sizeErr != nil {
+ // The size message arrives after the first draw, and a line that wrapped in it would
+ // throw off the line count every redraw rewinds by.
+ width, _, err := term.GetSize(fd)
+ if err != nil {
width = 0
}
-
- selected := 0
- render(out, options, selected, color, true, width)
-
- buf := make([]byte, 32)
- for {
- n, err := in.Read(buf)
- if err != nil || n == 0 {
- clear(out, renderedLines(options))
- return 0, ErrPromptAborted
- }
- moved := false
- for _, event := range decodeKeys(buf[:n], len(options)) {
- switch event.action {
- case keyUp:
- selected = (selected - 1 + len(options)) % len(options)
- moved = true
- case keyDown:
- selected = (selected + 1) % len(options)
- moved = true
- case keySelect:
- clear(out, renderedLines(options))
- return selected, nil
- case keyPick:
- clear(out, renderedLines(options))
- return event.index, nil
- case keyAbort:
- clear(out, renderedLines(options))
- return 0, ErrPromptAborted
- }
- }
- if moved {
- render(out, options, selected, color, false, width)
+ program := tea.NewProgram(newPickerModel(options, color, width),
+ tea.WithInput(in), tea.WithOutput(out), tea.WithoutBracketedPaste())
+ final, err := program.Run()
+ if err != nil {
+ // Run fails without ErrProgramKilled only while setting the terminal up, before
+ // anything is drawn: raw mode was refused.
+ if !errors.Is(err, tea.ErrProgramKilled) {
+ return 0, errRawUnavailable
}
+ return 0, ErrPromptAborted
+ }
+ model := final.(pickerModel)
+ if model.chosen < 0 {
+ return 0, ErrPromptAborted
}
+ return model.chosen, nil
}
-// decodeKeys turns a single raw read into the keypresses it contains.
-//
-// One Read can carry several keys, because a terminal hands over whatever has arrived
-// rather than one keystroke at a time: fast typing, a paste, and scripted input all
-// produce multi-byte reads. An earlier version matched only an exact one-byte read or
-// a three-byte escape, so an ordinary `1\n` was silently discarded and the picker sat
-// waiting for a key the user had already pressed.
-func decodeKeys(buf []byte, total int) []keyEvent {
- var events []keyEvent
- for i := 0; i < len(buf); {
- if buf[i] == 0x1b {
- // Arrow keys. Anything else starting with escape is a sequence this picker
- // does not use; drop the remainder rather than misread its bytes as
- // separate keypresses.
- if i+2 < len(buf) && buf[i+1] == '[' {
- switch buf[i+2] {
- case 'A':
- events = append(events, keyEvent{keyUp, 0})
- case 'B':
- events = append(events, keyEvent{keyDown, 0})
- }
- i += 3
- continue
- }
- break
+func (m pickerModel) Init() tea.Cmd {
+ return nil
+}
+
+func (m pickerModel) Update(message tea.Msg) (tea.Model, tea.Cmd) {
+ // Keys read in the same burst as the answer still arrive after it; none may change it.
+ if m.done {
+ return m, nil
+ }
+ switch msg := message.(type) {
+ case tea.WindowSizeMsg:
+ m.width = msg.Width
+ case tea.KeyMsg:
+ switch msg.String() {
+ case "ctrl+c", "ctrl+d", "esc":
+ m.done = true
+ return m, tea.Quit
+ case "enter", "ctrl+j":
+ m.chosen, m.done = m.selected, true
+ return m, tea.Quit
}
- if event, ok := decodeByte(buf[i], total); ok {
- events = append(events, event)
- // Selecting or aborting ends the menu, so nothing after it can matter.
- if event.action != keyUp && event.action != keyDown {
- return events
+ // Keys typed faster than they are read arrive as one message, so each rune is
+ // its own keypress: `jj` moves twice and `x2` still picks the second option.
+ if msg.Type == tea.KeyRunes && !msg.Alt {
+ for _, r := range msg.Runes {
+ // A number key picks that entry outright: anyone who already knows the
+ // menu should not have to arrow down to their answer.
+ if r >= '1' && r <= '9' && int(r-'0') <= len(m.options) {
+ m.chosen, m.done = int(r-'1'), true
+ return m, tea.Quit
+ }
+ m.move(runeStep(r))
}
+ return m, nil
}
- i++
+ m.move(menuStep(msg))
}
- return events
+ return m, nil
}
-// decodeByte maps a single non-escape byte onto an action.
-func decodeByte(c byte, total int) (keyEvent, bool) {
- switch {
- case c == 'k' || c == 'K':
- return keyEvent{keyUp, 0}, true
- case c == 'j' || c == 'J':
- return keyEvent{keyDown, 0}, true
- case c == '\r' || c == '\n':
- return keyEvent{keySelect, 0}, true
- // A number key picks that entry outright: anyone who already knows the menu
- // should not have to arrow down to their answer.
- case c >= '1' && c <= '9' && int(c-'0') <= total:
- return keyEvent{keyPick, int(c - '1')}, true
- case c == 0x03 || c == 0x04: // Ctrl-C, Ctrl-D
- return keyEvent{keyAbort, 0}, true
- default:
- return keyEvent{}, false
- }
+func (m *pickerModel) move(step int) {
+ n := len(m.options)
+ m.selected = (m.selected + step + n) % n
}
-// render draws the option list plus its key hint, overwriting the previous draw. width is
-// the terminal width in columns, or 0 when unknown; every line is clipped to one column
-// less than that, so the draw occupies exactly renderedLines rows even on terminals that
-// wrap eagerly at the last column.
-func render(out io.Writer, options []choice, selected int, color bool, first bool, width int) {
- if !first {
- fmt.Fprintf(out, ansiUp, renderedLines(options))
- }
- accent, dimmed, clear := "", "", ""
- if color {
- accent, dimmed, clear = colorAccnt, colorDim, colorReset
- }
- for i, option := range options {
- fmt.Fprint(out, ansiClearLine)
- if i == selected {
- fmt.Fprintf(out, " %s❯ %s%s\r\n", accent, clip(option.Label, width-5), clear)
+// View draws the option list plus its key hint. Every line is clipped to one column less
+// than the terminal, so nothing wraps even on terminals that wrap eagerly at the last
+// column. Once an answer is in, the view is empty, which erases the menu.
+func (m pickerModel) View() string {
+ if m.done {
+ return ""
+ }
+ accent, dimmed, plain := "", "", ""
+ if m.color {
+ accent, dimmed, plain = colorAccnt, colorDim, colorReset
+ }
+ var b strings.Builder
+ for i, option := range m.options {
+ if i == m.selected {
+ fmt.Fprintf(&b, " %s❯ %s%s\n", accent, clip(option.Label, m.width-5), plain)
} else {
- fmt.Fprintf(out, " %s\r\n", clip(option.Label, width-5))
+ fmt.Fprintf(&b, " %s\n", clip(option.Label, m.width-5))
}
if option.Detail != "" {
- fmt.Fprint(out, ansiClearLine)
- fmt.Fprintf(out, " %s%s%s\r\n", dimmed, clip(option.Detail, width-7), clear)
+ fmt.Fprintf(&b, " %s%s%s\n", dimmed, clip(option.Detail, m.width-7), plain)
}
}
- fmt.Fprint(out, ansiClearLine)
- fmt.Fprintf(out, " %s↑/↓ move · ↵ select · ^C cancel%s\r\n", dimmed, clear)
+ fmt.Fprintf(&b, " %s↑/↓ move · ↵ select · ^C cancel%s", dimmed, plain)
+ return b.String()
}
// clip shortens text to fit in width columns, ending it with an ellipsis. A width of zero
@@ -242,19 +202,6 @@ func clip(text string, width int) string {
return string(runes[:width-1]) + "…"
}
-// clear erases the last n rendered lines and parks the cursor at their start.
-func clear(out io.Writer, n int) {
- fmt.Fprintf(out, ansiUp, n)
- for i := 0; i < n; i++ {
- fmt.Fprint(out, ansiClearLine)
- if i < n-1 {
- fmt.Fprint(out, "\r\n")
- }
- }
- fmt.Fprintf(out, ansiUp, n-1)
- fmt.Fprint(out, "\r")
-}
-
// terminalFile reports whether r is a real terminal that raw mode can drive.
func terminalFile(r io.Reader) (*os.File, bool) {
file, ok := r.(*os.File)
diff --git a/cli/beacon/internal/onboarding/picker_test.go b/cli/beacon/internal/onboarding/picker_test.go
index 67a338b2..2fee8b86 100644
--- a/cli/beacon/internal/onboarding/picker_test.go
+++ b/cli/beacon/internal/onboarding/picker_test.go
@@ -1,91 +1,94 @@
package onboarding
import (
- "bytes"
+ "context"
"errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
+ "time"
+
+ tea "github.com/charmbracelet/bubbletea"
)
-func TestDecodeKeysSingleKeypress(t *testing.T) {
- const total = 3
- cases := []struct {
- name string
- bytes []byte
- want []keyEvent
- }{
- {"up arrow", []byte{0x1b, '[', 'A'}, []keyEvent{{keyUp, 0}}},
- {"down arrow", []byte{0x1b, '[', 'B'}, []keyEvent{{keyDown, 0}}},
- {"vim k", []byte{'k'}, []keyEvent{{keyUp, 0}}},
- {"vim j", []byte{'j'}, []keyEvent{{keyDown, 0}}},
- {"enter", []byte{'\r'}, []keyEvent{{keySelect, 0}}},
- {"newline", []byte{'\n'}, []keyEvent{{keySelect, 0}}},
- {"digit picks directly", []byte{'2'}, []keyEvent{{keyPick, 1}}},
- {"last digit", []byte{'3'}, []keyEvent{{keyPick, 2}}},
- {"digit past the end is ignored", []byte{'4'}, nil},
- {"zero is not an option", []byte{'0'}, nil},
- {"ctrl-c aborts", []byte{0x03}, []keyEvent{{keyAbort, 0}}},
- {"ctrl-d aborts", []byte{0x04}, []keyEvent{{keyAbort, 0}}},
- {"empty read yields nothing", []byte{}, nil},
- {"unknown letter ignored", []byte{'z'}, nil},
- {"right arrow ignored", []byte{0x1b, '[', 'C'}, nil},
- {"bare escape ignored", []byte{0x1b}, nil},
- }
- for _, tc := range cases {
- t.Run(tc.name, func(t *testing.T) {
- assertEvents(t, decodeKeys(tc.bytes, total), tc.want)
- })
+// runPicker feeds raw terminal bytes through bubbletea's own key parser into a three-option
+// picker, as a terminal would, and returns the model it ended with.
+func runPicker(t *testing.T, input string) pickerModel {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ program := tea.NewProgram(newPickerModel(choices([]string{"One", "Two", "Three"}), false, 0),
+ tea.WithContext(ctx), tea.WithInput(strings.NewReader(input)), tea.WithOutput(io.Discard), tea.WithoutSignalHandler())
+ final, err := program.Run()
+ if err != nil {
+ t.Fatalf("picker did not finish on %q: %v", input, err)
}
+ return final.(pickerModel)
}
-// A terminal hands over whatever has arrived, not one keystroke at a time. Fast
-// typing, a paste, and scripted input all produce multi-byte reads -- and an earlier
-// version dropped them silently, leaving the picker waiting on a key already pressed.
-func TestDecodeKeysMultipleKeysInOneRead(t *testing.T) {
- const total = 3
+func TestPickerKeys(t *testing.T) {
cases := []struct {
name string
- bytes []byte
- want []keyEvent
+ input string
+ want int // -1 is cancelled
}{
- {"digit then newline", []byte("1\n"), []keyEvent{{keyPick, 0}}},
- {"digit then carriage return", []byte("2\r"), []keyEvent{{keyPick, 1}}},
- {"two downs then enter", append(append([]byte{0x1b, '[', 'B'}, 0x1b, '[', 'B'), '\r'),
- []keyEvent{{keyDown, 0}, {keyDown, 0}, {keySelect, 0}}},
- {"vim keys then enter", []byte("jjk\r"),
- []keyEvent{{keyDown, 0}, {keyDown, 0}, {keyUp, 0}, {keySelect, 0}}},
- {"noise before a digit", []byte("xy2"), []keyEvent{{keyPick, 1}}},
- {"nothing survives past a select", []byte("\r3jjj"), []keyEvent{{keySelect, 0}}},
- {"nothing survives past an abort", []byte{0x03, '2', '\r'}, []keyEvent{{keyAbort, 0}}},
- {"a whole pasted line still selects", []byte("1\[email protected]\n"), []keyEvent{{keyPick, 0}}},
+ {"enter picks the first option", "\r", 0},
+ {"newline picks the first option", "\n", 0},
+ {"down arrow", "\x1b[B\r", 1},
+ {"up arrow wraps to the last option", "\x1b[A\r", 2},
+ {"vim j", "j\r", 1},
+ {"vim k wraps", "k\r", 2},
+ {"digit picks directly", "2", 1},
+ {"last digit", "3", 2},
+ {"digit past the end is ignored", "4\r", 0},
+ {"zero is not an option", "0\r", 0},
+ {"alt+digit is not a number key", "\x1b2\r", 0},
+ {"right arrow ignored", "\x1b[C\r", 0},
+ {"ctrl-c cancels", "\x03", -1},
+ {"ctrl-d cancels", "\x04", -1},
+ // Modified arrows carry parameters (Shift+Up is ESC [ 1 ; 2 A) whose digits the
+ // picker once read as number keys.
+ {"shift+up moves", "\x1b[1;2A\r", 2},
+ {"shift+down moves", "\x1b[1;2B\r", 1},
+ {"alt+up moves", "\x1b[1;3A\r", 2},
+ {"ctrl+down moves", "\x1b[1;5B\r", 1},
+ {"ctrl+shift+down moves", "\x1b[1;6B\r", 1},
+ {"delete ignored", "\x1b[3~\r", 0},
+ {"insert ignored", "\x1b[2~\r", 0},
+ {"f2 ignored", "\x1b[12~\r", 0},
+ {"f5 ignored", "\x1b[15~\r", 0},
+ {"page up ignored", "\x1b[5~\r", 0},
+ // A terminal hands over whatever has arrived, not one keystroke at a time: fast
+ // typing, a paste, and scripted input all arrive together.
+ {"two downs then enter", "\x1b[B\x1b[B\r", 2},
+ {"vim keys typed together", "jjk\r", 1},
+ {"noise before a digit", "xy2", 1},
+ {"nothing survives past a select", "\r3jjj", 0},
+ {"nothing survives past a cancel", "\x032\r", -1},
+ {"a whole pasted line still selects", "1\[email protected]\n", 0},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
- assertEvents(t, decodeKeys(tc.bytes, total), tc.want)
+ if got := runPicker(t, tc.input).chosen; got != tc.want {
+ t.Fatalf("picker chose %d, want %d", got, tc.want)
+ }
})
}
}
-func assertEvents(t *testing.T, got, want []keyEvent) {
- t.Helper()
- if len(got) != len(want) {
- t.Fatalf("decodeKeys returned %v, want %v", got, want)
- }
- for i := range want {
- if got[i] != want[i] {
- t.Fatalf("decodeKeys returned %v, want %v", got, want)
- }
+func TestPickerEscCancels(t *testing.T) {
+ model, command := newPickerModel(choices([]string{"A", "B"}), false, 0).Update(tea.KeyMsg{Type: tea.KeyEsc})
+ if command == nil || model.(pickerModel).chosen != -1 {
+ t.Fatalf("esc did not cancel: chosen=%d quit=%v", model.(pickerModel).chosen, command != nil)
}
}
-func TestRenderMarksTheSelectedOption(t *testing.T) {
- var out bytes.Buffer
- render(&out, choices([]string{"Alpha", "Beta", "Gamma"}), 1, false, true, 0)
- got := out.String()
-
+func TestPickerViewMarksTheSelectedOption(t *testing.T) {
+ model := newPickerModel(choices([]string{"Alpha", "Beta", "Gamma"}), false, 0)
+ model.selected = 1
+ got := model.View()
if !strings.Contains(got, "❯ Beta") {
t.Fatalf("selected option is not marked:\n%s", got)
}
@@ -94,32 +97,55 @@ func TestRenderMarksTheSelectedOption(t *testing.T) {
}
}
-// The first draw must not move the cursor up, or it will eat whatever the caller
-// printed above the menu.
-func TestRenderFirstDrawDoesNotMoveTheCursor(t *testing.T) {
- var first, redraw bytes.Buffer
- render(&first, choices([]string{"A", "B"}), 0, false, true, 0)
- render(&redraw, choices([]string{"A", "B"}), 0, false, false, 0)
+func TestPickerViewHonorsColorOff(t *testing.T) {
+ plain := newPickerModel(choices([]string{"Alpha", "Beta"}), false, 0).View()
+ if strings.Contains(plain, "\x1b") {
+ t.Fatalf("colour escapes leaked with colour disabled:\n%q", plain)
+ }
+ if colored := newPickerModel(choices([]string{"Alpha", "Beta"}), true, 0).View(); !strings.Contains(colored, colorAccnt) {
+ t.Fatalf("colour was requested but not emitted:\n%q", colored)
+ }
+}
- if strings.Contains(first.String(), "\x1b[3A") {
- t.Fatalf("first draw moved the cursor up:\n%q", first.String())
+// A detail line is drawn dim under its option, before the next one.
+func TestPickerViewDrawsDetailsUnderTheirOptions(t *testing.T) {
+ rows := []choice{{Label: "Alpha", Detail: "first thing"}, {Label: "Beta"}, {Label: "Gamma", Detail: "third thing"}}
+ got := newPickerModel(rows, true, 0).View()
+ if !strings.Contains(got, " "+colorDim+"first thing"+colorReset) || !strings.Contains(got, colorDim+"third thing") {
+ t.Fatalf("details are not drawn dim under their options:\n%q", got)
+ }
+ if strings.Index(got, "Alpha") > strings.Index(got, "first thing") || strings.Index(got, "first thing") > strings.Index(got, "Beta") {
+ t.Fatalf("detail must sit between its option and the next:\n%s", got)
}
- if !strings.HasPrefix(redraw.String(), "\x1b[3A") {
- t.Fatalf("redraw did not rewind over its own %d lines:\n%q", 3, redraw.String())
+ if lines := strings.Count(got, "\n") + 1; lines != 6 {
+ t.Fatalf("view is %d lines, want 3 options + 2 details + hint", lines)
}
}
-func TestRenderHonorsColorOff(t *testing.T) {
- var out bytes.Buffer
- render(&out, choices([]string{"Alpha", "Beta"}), 0, false, true, 0)
- if strings.Contains(out.String(), colorAccnt) || strings.Contains(out.String(), colorDim) {
- t.Fatalf("colour escapes leaked with colour disabled:\n%q", out.String())
+// A line longer than the terminal is clipped, never wrapped: a wrapped line would throw
+// off the line count that every redraw rewinds by.
+func TestPickerViewClipsToTerminalWidth(t *testing.T) {
+ rows := []choice{{Label: "Alpha", Detail: strings.Repeat("d", 100)}, {Label: strings.Repeat("L", 100)}}
+ got := newPickerModel(rows, false, 40).View()
+ for _, line := range strings.Split(got, "\n") {
+ if n := len([]rune(line)); n >= 40 {
+ t.Fatalf("line is %d columns wide on a 40-column terminal; must leave the last column free: %q", n, line)
+ }
+ }
+ if !strings.Contains(got, "…") {
+ t.Fatalf("clipped lines should end with an ellipsis:\n%q", got)
+ }
+ if clip("short", 0) != "short" || clip("short", 10) != "short" || clip("abcdef", 4) != "abc…" {
+ t.Fatal("clip: unknown width leaves text alone; otherwise width-1 runes plus an ellipsis")
}
+}
- out.Reset()
- render(&out, choices([]string{"Alpha", "Beta"}), 0, true, true, 0)
- if !strings.Contains(out.String(), colorAccnt) {
- t.Fatalf("colour was requested but not emitted:\n%q", out.String())
+// Once answered the view is empty, which erases the menu so the caller's confirmation line
+// lands where it was.
+func TestPickerViewIsEmptyOnceAnswered(t *testing.T) {
+ model, _ := newPickerModel(choices([]string{"A", "B"}), false, 0).Update(tea.KeyMsg{Type: tea.KeyEnter})
+ if got := model.View(); got != "" {
+ t.Fatalf("answered picker still draws:\n%q", got)
}
}
@@ -164,64 +190,3 @@ func TestSupportsColorRespectsNoColor(t *testing.T) {
t.Fatalf("TERM=dumb but colour was still enabled")
}
}
-
-// clear must rewind exactly as far as it wiped, so the confirmation line lands where
-// the menu was instead of below it.
-func TestClearRewindsWhatItWiped(t *testing.T) {
- var out bytes.Buffer
- clear(&out, 4)
- got := out.String()
-
- if !strings.HasPrefix(got, "\x1b[4A") {
- t.Fatalf("clear did not rewind 4 lines first:\n%q", got)
- }
- if strings.Count(got, "\x1b[K") != 4 {
- t.Fatalf("clear wiped %d lines, want 4:\n%q", strings.Count(got, "\x1b[K"), got)
- }
- if !strings.HasSuffix(got, "\x1b[3A\r") {
- t.Fatalf("clear did not park the cursor at the start of the block:\n%q", got)
- }
-}
-
-// A detail line is drawn dim under its option and counted when the menu is redrawn or
-// cleared, so a picker with descriptions never eats the lines above it.
-func TestRenderDrawsDetailsAndCountsThem(t *testing.T) {
- rows := []choice{{Label: "Alpha", Detail: "first thing"}, {Label: "Beta"}, {Label: "Gamma", Detail: "third thing"}}
- if got := renderedLines(rows); got != 6 {
- t.Fatalf("renderedLines = %d, want 3 options + 2 details + hint", got)
- }
- var out bytes.Buffer
- render(&out, rows, 0, true, true, 0)
- got := out.String()
- if !strings.Contains(got, " "+colorDim+"first thing"+colorReset) || !strings.Contains(got, colorDim+"third thing") {
- t.Fatalf("details are not drawn dim under their options:\n%q", got)
- }
- if strings.Index(got, "Alpha") > strings.Index(got, "first thing") || strings.Index(got, "first thing") > strings.Index(got, "Beta") {
- t.Fatalf("detail must sit between its option and the next:\n%s", got)
- }
- var redraw bytes.Buffer
- render(&redraw, rows, 1, false, false, 0)
- if !strings.HasPrefix(redraw.String(), "\x1b[6A") {
- t.Fatalf("redraw must move up over options, details and hint:\n%q", redraw.String())
- }
-}
-
-// A line longer than the terminal is clipped, never wrapped: a wrapped line would throw
-// off the line count that the redraw and the final clear rely on.
-func TestRenderClipsToTerminalWidth(t *testing.T) {
- rows := []choice{{Label: "Alpha", Detail: strings.Repeat("d", 100)}, {Label: strings.Repeat("L", 100)}}
- var out bytes.Buffer
- render(&out, rows, 0, false, true, 40)
- for _, line := range strings.Split(strings.TrimSpace(out.String()), "\r\n") {
- visible := strings.NewReplacer(ansiClearLine, "").Replace(line)
- if n := len([]rune(visible)); n >= 40 {
- t.Fatalf("line is %d columns wide on a 40-column terminal; must leave the last column free: %q", n, visible)
- }
- }
- if !strings.Contains(out.String(), "…") {
- t.Fatalf("clipped lines should end with an ellipsis:\n%q", out.String())
- }
- if clip("short", 0) != "short" || clip("short", 10) != "short" || clip("abcdef", 4) != "abc…" {
- t.Fatal("clip: unknown width leaves text alone; otherwise width-1 runes plus an ellipsis")
- }
-}
diff --git a/cli/beacon/internal/onboarding/wizard.go b/cli/beacon/internal/onboarding/wizard.go
index 2f5f5829..02229090 100644
--- a/cli/beacon/internal/onboarding/wizard.go
+++ b/cli/beacon/internal/onboarding/wizard.go
@@ -298,6 +298,12 @@ func (m wizardModel) Update(message tea.Msg) (tea.Model, tea.Cmd) {
case signInDoneMsg:
return m.signInFinished(msg)
case tea.KeyMsg:
+ if step := menuStep(msg); step != 0 {
+ if n := m.choiceCount(); m.isPicker() && n > 0 {
+ m.selected = (m.selected + step + n) % n
+ }
+ return m, nil
+ }
switch msg.String() {
// esc and ctrl+c cancel; "q" deliberately does not. It used to, on every
// screen, so a user typing q at the destination list killed the install --
@@ -313,14 +319,6 @@ func (m wizardModel) Update(message tea.Msg) (tea.Model, tea.Cmd) {
return m, nil
}
return m.cancelAndQuit()
- case "up", "k":
- if n := m.choiceCount(); m.isPicker() && n > 0 {
- m.selected = (m.selected - 1 + n) % n
- }
- case "down", "j":
- if n := m.choiceCount(); m.isPicker() && n > 0 {
- m.selected = (m.selected + 1) % n
- }
case " ", "space", "x":
if m.screen == agentToolsScreen {
m.toggleAgentTool()