From f2051f2ca89fd13e254ddcb977d42753d3ec8a5c Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:23:23 -0500 Subject: [PATCH 01/30] feat(client): let a request say what the spinner is waiting for MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit client.WithSpinnerMessage puts a message on a request's context, which the spinner shows in place of what the command does. A picker loading your workspaces before environment publish runs should say "Loading your workspaces…", not "Publish environment…". --- internal/client/spinner.go | 16 +++++++++++++++- internal/client/spinner_test.go | 15 ++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/internal/client/spinner.go b/internal/client/spinner.go index f87ca04..e7e2122 100644 --- a/internal/client/spinner.go +++ b/internal/client/spinner.go @@ -4,6 +4,7 @@ package client import ( + "context" "io" "net/http" "time" @@ -49,6 +50,15 @@ func StartSpinner(cmd *cobra.Command, msg string) (stop func()) { return output.UI(cmd, w).SpinAfter(w, spinnerDelay, msg, "ctrl-c to cancel").Stop } +type spinnerMessageKey struct{} + +// WithSpinnerMessage makes the spinner say msg for requests made with ctx, +// in place of what the command does: while a picker loads workspaces, vf is +// not yet publishing anything. +func WithSpinnerMessage(ctx context.Context, msg string) context.Context { + return context.WithValue(ctx, spinnerMessageKey{}, msg) +} + // spinnerMessage is what the command does, as its help says it ("List // projects"), so the line reads like Claude Code's "Reading file…". func spinnerMessage(cmd *cobra.Command) string { @@ -69,7 +79,11 @@ type spinnerClient struct { // Do runs the request under a spinner. The spinner stops when the response // headers arrive, so a streamed body is never drawn over. func (c *spinnerClient) Do(req *http.Request) (*http.Response, error) { - s := c.u.SpinAfter(c.w, c.delay, c.msg, "ctrl-c to cancel") + msg := c.msg + if m, ok := req.Context().Value(spinnerMessageKey{}).(string); ok { + msg = m + } + s := c.u.SpinAfter(c.w, c.delay, msg, "ctrl-c to cancel") defer s.Stop() return c.inner.Do(req) } diff --git a/internal/client/spinner_test.go b/internal/client/spinner_test.go index 1a4e93c..8cc1aa2 100644 --- a/internal/client/spinner_test.go +++ b/internal/client/spinner_test.go @@ -4,6 +4,7 @@ package client import ( "bytes" + "context" "net/http" "strings" "testing" @@ -22,6 +23,10 @@ func (c *slowClient) Do(*http.Request) (*http.Response, error) { } func spinning(pause, delay time.Duration) string { + return spinningWith(context.Background(), pause, delay) +} + +func spinningWith(ctx context.Context, pause, delay time.Duration) string { var out bytes.Buffer c := &spinnerClient{ inner: &slowClient{pause: pause}, @@ -30,7 +35,7 @@ func spinning(pause, delay time.Duration) string { msg: "List projects…", delay: delay, } - req, _ := http.NewRequest(http.MethodGet, "https://api.example/v1/projects", nil) + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.example/v1/projects", nil) if _, err := c.Do(req); err != nil { panic(err) } @@ -76,3 +81,11 @@ func TestSpinnerMessageIsWhatTheCommandDoes(t *testing.T) { t.Errorf("got %q", got) } } + +// A picker's request says what it loads, not what the command will do. +func TestARequestCanSayWhatItLoads(t *testing.T) { + got := spinningWith(WithSpinnerMessage(context.Background(), "Loading your workspaces…"), 250*time.Millisecond, 10*time.Millisecond) + if !strings.Contains(got, "Loading your workspaces…") || strings.Contains(got, "List projects…") { + t.Errorf("got %q", got) + } +} From 4db9f7eb0fe5a0f097aca4db249fa6afb9c9f4ec Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:23:23 -0500 Subject: [PATCH 02/30] feat(interactive): pick a missing ID from a list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The form asked for every missing ID as free text, so a person had to find and paste one. It can now offer a list instead, for any flag with a registered Picker: - What an ID depends on is picked first: a project after its workspace, even when the command has no --workspace-id, an environment after its project. - A lone choice is taken and said so, unless the command changes or removes what it picks (delete, publish, merge, update…). - The last pick comes first, where Enter takes it again; it is never taken without asking. It is kept in ~/.config/vf/picks.json (owner-only). - "Type an ID…" ends every list, and a list that fails or comes back empty says so and asks for the ID, as before. PromptAndSetFlags calls pickRequired after its header, so pickers run only where the form does: never in agent mode, a pipe or --no-interactive. --- internal/interactive/interactive.go | 7 + internal/interactive/pickers.go | 294 +++++++++++++++++++++++++++ internal/interactive/pickers_test.go | 240 ++++++++++++++++++++++ internal/interactive/picks.go | 50 +++++ 4 files changed, 591 insertions(+) create mode 100644 internal/interactive/pickers.go create mode 100644 internal/interactive/pickers_test.go create mode 100644 internal/interactive/picks.go diff --git a/internal/interactive/interactive.go b/internal/interactive/interactive.go index 14ec77c..91e5069 100644 --- a/internal/interactive/interactive.go +++ b/internal/interactive/interactive.go @@ -216,6 +216,13 @@ func PromptAndSetFlags(cmd *cobra.Command, meta []flagutil.FlagMeta) error { // Print the command header once before any forms printCommandHeader(cmd, len(required), len(optional)) + // pickers.go: an ID vf can look up (organization, workspace, project, + // environment) is picked from a list; the form asks for the rest. + required, err := pickRequired(cmd, required) + if err != nil { + return err + } + theme := formTheme() width := formWidth() diff --git a/internal/interactive/pickers.go b/internal/interactive/pickers.go new file mode 100644 index 0000000..0653d82 --- /dev/null +++ b/internal/interactive/pickers.go @@ -0,0 +1,294 @@ +// This file is not generated by Speakeasy. It turns a missing ID into a +// choice: when a command needs an organization, workspace, project or +// environment and none was given, the form lists the ones you have instead +// of asking you to paste an ID. internal/cli/pickers.go registers what each +// flag lists; PromptAndSetFlags calls pickRequired before its own form. +// +// Pickers run only where the form does: at a terminal, outside agent mode, +// without --no-interactive. Scripts and agents still get the error that +// names the flag. + +package interactive + +import ( + "context" + "fmt" + "io" + "os" + "strings" + "unicode/utf8" + + "github.com/charmbracelet/huh" + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/ui" +) + +// Choice is one row of a picker. +type Choice struct { + Value string // set on the flag + Name string // what a person recognizes: "Support bot" + Detail string // shown after it: the ID, which org +} + +// Picker lists the values a flag can take. +type Picker struct { + Noun string // "workspace": the list's title, and "Using workspace …" + Plural string // "workspaces": "Couldn't list your workspaces" + Needs []string // flags picked first, whose values List reads: a project needs its workspace + List func(ctx context.Context, cmd *cobra.Command, needs map[string]string) ([]Choice, error) +} + +var pickers = map[string]Picker{} + +// RegisterPicker makes the form offer a list for flag. +func RegisterPicker(flag string, p Picker) { pickers[flag] = p } + +// typeOwn is the last row of every list, for an ID that is not in it: an +// organization with no workspace yet, a project shared by link. +const typeOwn = "\x00type" + +// picking is the state of one form: what has been picked, and which flags +// belong to the command (a workspace picked only to find a project is not +// set on a command that has no --workspace-id). +type picking struct { + cmd *cobra.Command + u *ui.UI + out io.Writer // status lines: stderr + bound map[string]bool + picked map[string]string + + // choose shows a list and ask an input, each in its own form; tests + // replace them. + choose func(title, desc string, options []huh.Option[string], value *string) error + ask func(title, desc string, value *string) error +} + +// pickRequired fills the required fields vf can look up, each from a list, +// and returns the rest for the form to ask as before. +func pickRequired(cmd *cobra.Command, required []fieldInfo) ([]fieldInfo, error) { + p := &picking{cmd: cmd, u: output.UI(cmd, os.Stderr), out: os.Stderr, + bound: map[string]bool{}, picked: map[string]string{}, choose: chooseInForm, ask: askInForm} + return p.fill(required) +} + +func (p *picking) fill(required []fieldInfo) ([]fieldInfo, error) { + for _, f := range required { + if _, ok := pickers[f.binding.flagName]; ok { + p.bound[f.binding.flagName] = true + } + } + if len(p.bound) == 0 { + return required, nil + } + var rest []fieldInfo + for _, f := range required { + name := f.binding.flagName + if !p.bound[name] { + rest = append(rest, f) + continue + } + if _, ok, err := p.resolve(name); err != nil { + return nil, err + } else if !ok { + rest = append(rest, f) // nothing picked: the form asks for it + } + } + return rest, nil +} + +// resolve finds flag's value: given on the command line, picked already, or +// picked now, after whatever it needs. ok is false when nothing was picked. +func (p *picking) resolve(flag string) (value string, ok bool, err error) { + if v, done := p.picked[flag]; done { + return v, v != "", nil + } + if f := p.cmd.Flags().Lookup(flag); f != nil && f.Changed { + return f.Value.String(), true, nil + } + picker := pickers[flag] + needs := map[string]string{} + for _, n := range picker.Needs { + v, ok, err := p.resolve(n) + if err != nil { + return "", false, err + } + if !ok { + p.picked[flag] = "" + return "", false, nil + } + needs[n] = v + } + v, err := p.pick(flag, picker, needs) + if err != nil { + return "", false, err + } + p.picked[flag] = v + if v != "" && p.bound[flag] { + if err := p.cmd.Flags().Set(flag, v); err != nil { + return "", false, fmt.Errorf("setting flag %q: %w", flag, err) + } + } + return v, v != "", nil +} + +// pick lists flag's values and lets the person choose one. A single value is +// taken without asking, and said so, unless the command changes or removes +// the thing picked: deleting your only project still asks which. A list that +// fails or comes back empty falls back to typing the ID. +func (p *picking) pick(flag string, picker Picker, needs map[string]string) (string, error) { + ctx := p.cmd.Context() + if ctx == nil { + ctx = context.Background() + } + choices, err := picker.List(ctx, p.cmd, needs) + switch { + case err != nil: + fmt.Fprintln(p.out, p.u.Status(ui.StatusWarn, "Couldn't list your "+picker.Plural+": "+firstLine(err.Error()))) + return p.typeID(flag, picker) + case len(choices) == 0: + fmt.Fprintln(p.out, p.u.Status(ui.StatusWarn, "No "+picker.Plural+" found")) + return p.typeID(flag, picker) + case len(choices) == 1 && !(p.bound[flag] && changesWhatItPicks(p.cmd)): + c := choices[0] + fmt.Fprintln(p.out, p.u.Status(ui.StatusDone, "Using "+picker.Noun+" "+c.Name+" ("+c.Value+"), the only one")) + savePick(flag, c.Value) + return c.Value, nil + } + + choices = lastPickFirst(choices, lastPick(flag)) + value := choices[0].Value + desc := "/ to filter · enter to pick" + if p.bound[flag] { + desc = "--" + flag + " · " + desc + } else { + desc = "to find the " + strings.Join(boundNouns(p), " and ") + " · " + desc + } + if err := p.choose(title(picker.Noun), desc, optionsFor(choices), &value); err != nil { + return "", fmt.Errorf("interactive prompt: %w", err) + } + if value == typeOwn { + return p.typeID(flag, picker) + } + savePick(flag, value) + return value, nil +} + +// typeID asks for the ID itself, as the form did before pickers. +func (p *picking) typeID(flag string, picker Picker) (string, error) { + var value string + if err := p.ask(title(picker.Noun)+" ID", "--"+flag, &value); err != nil { + return "", fmt.Errorf("interactive prompt: %w", err) + } + return strings.TrimSpace(value), nil +} + +func chooseInForm(title, desc string, options []huh.Option[string], value *string) error { + return runField(huh.NewSelect[string](). + Title(title). + Description(desc). + Options(options...). + Height(min(len(options), 10)). + Value(value)) +} + +func askInForm(title, desc string, value *string) error { + return runField(huh.NewInput().Title(title).Description(desc).Value(value)) +} + +// runField runs one field in its own form, as PromptAndSetFlags runs each. +func runField(f huh.Field) error { + return huh.NewForm(huh.NewGroup(f)). + WithWidth(formWidth()). + WithTheme(formTheme()). + WithShowHelp(false). + Run() +} + +// changesWhatItPicks is whether the command changes or removes what its +// flags name, so a lone choice is shown rather than taken. +func changesWhatItPicks(cmd *cobra.Command) bool { + for _, verb := range []string{"delete", "remove", "publish", "merge", "disconnect", "unassign", "revoke", "cancel", "update", "replace"} { + if strings.HasPrefix(cmd.Name(), verb) { + return true + } + } + return false +} + +// boundNouns names what the command itself needs, for the description of a +// list picked on the way to it. +func boundNouns(p *picking) []string { + var nouns []string + for flag := range p.bound { + if _, done := p.picked[flag]; !done { + nouns = append(nouns, pickers[flag].Noun) + } + } + if len(nouns) == 0 { + return []string{"rest"} + } + if len(nouns) > 1 { + // Keep the order stable: what is picked first reads first. + order := map[string]int{"organization": 0, "workspace": 1, "project": 2, "environment": 3} + for i := 1; i < len(nouns); i++ { + for j := i; j > 0 && order[nouns[j]] < order[nouns[j-1]]; j-- { + nouns[j], nouns[j-1] = nouns[j-1], nouns[j] + } + } + } + return nouns +} + +// lastPickFirst moves the value picked last time to the top, so Enter takes +// it again: the default, which is never taken without asking. +func lastPickFirst(choices []Choice, last string) []Choice { + for i, c := range choices { + if c.Value == last && i > 0 { + out := append([]Choice{c}, choices[:i]...) + return append(out, choices[i+1:]...) + } + } + return choices +} + +// optionsFor lays the choices out in two columns, names then details, and +// ends with the row for typing an ID. +func optionsFor(choices []Choice) []huh.Option[string] { + const maxName = 40 + width := 0 + for _, c := range choices { + width = max(width, min(utf8.RuneCountInString(c.Name), maxName)) + } + options := make([]huh.Option[string], 0, len(choices)+1) + for _, c := range choices { + label := truncate(c.Name, maxName) + if c.Detail != "" { + label += strings.Repeat(" ", width-utf8.RuneCountInString(label)+2) + c.Detail + } + options = append(options, huh.NewOption(label, c.Value)) + } + return append(options, huh.NewOption("Type an ID…", typeOwn)) +} + +func truncate(s string, n int) string { + if utf8.RuneCountInString(s) <= n { + return s + } + return string([]rune(s)[:n-1]) + "…" +} + +func title(noun string) string { + if noun == "" { + return "" + } + return strings.ToUpper(noun[:1]) + noun[1:] +} + +func firstLine(s string) string { + if i := strings.IndexByte(s, '\n'); i >= 0 { + s = s[:i] + } + return truncate(strings.TrimSpace(s), 100) +} diff --git a/internal/interactive/pickers_test.go b/internal/interactive/pickers_test.go new file mode 100644 index 0000000..02153c6 --- /dev/null +++ b/internal/interactive/pickers_test.go @@ -0,0 +1,240 @@ +// This file is not generated by Speakeasy. It covers pickers.go and picks.go. + +package interactive + +import ( + "bytes" + "context" + "errors" + "io" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/charmbracelet/huh" + "github.com/spf13/cobra" + "github.com/voiceflow/cli/internal/ui" +) + +// isolatePicks keeps picks.json in a temporary directory, and the registry +// to what the test registers. +func isolatePicks(t *testing.T) { + t.Helper() + dir := t.TempDir() + saved, savedPickers := picksPath, pickers + picksPath = func() string { return filepath.Join(dir, "picks.json") } + pickers = map[string]Picker{} + t.Cleanup(func() { picksPath, pickers = saved, savedPickers }) +} + +// fakePicker lists choices and records what it was given. +type fakePicker struct { + choices []Choice + err error + calls []map[string]string +} + +func (f *fakePicker) register(flag, noun string, needs ...string) *fakePicker { + RegisterPicker(flag, Picker{Noun: noun, Plural: noun + "s", Needs: needs, + List: func(_ context.Context, _ *cobra.Command, n map[string]string) ([]Choice, error) { + f.calls = append(f.calls, n) + return f.choices, f.err + }}) + return f +} + +// session is a picking for a command named name with the given string flags, +// whose lists pick choose(title) and whose inputs type typed. +type session struct { + *picking + out *bytes.Buffer + shown []string // titles of the lists shown, in order + asked []string // titles of the inputs shown + picks map[string]string + typing string +} + +func newSession(name string, flags ...string) *session { + cmd := &cobra.Command{Use: name} + for _, f := range flags { + cmd.Flags().String(f, "", "") + } + s := &session{out: &bytes.Buffer{}, picks: map[string]string{}} + s.picking = &picking{cmd: cmd, u: ui.New(io.Discard, ui.Options{Decorate: true}), out: s.out, + bound: map[string]bool{}, picked: map[string]string{}, + choose: func(title, _ string, options []huh.Option[string], value *string) error { + s.shown = append(s.shown, title) + if v, ok := s.picks[title]; ok { + *value = v + } + return nil + }, + ask: func(title, _ string, value *string) error { + s.asked = append(s.asked, title) + *value = s.typing + return nil + }} + return s +} + +func fields(flags ...string) []fieldInfo { + var out []fieldInfo + for _, f := range flags { + out = append(out, fieldInfo{binding: flagBinding{flagName: f}, name: f}) + } + return out +} + +func names(fs []fieldInfo) []string { + out := []string{} + for _, f := range fs { + out = append(out, f.binding.flagName) + } + return out +} + +func flag(s *session, name string) string { return s.cmd.Flags().Lookup(name).Value.String() } + +// environment publish needs an environment and a project. The project needs a +// workspace, which publish has no flag for: it is picked on the way, and +// taken without asking when there is only one. +func TestPickersRunInTheOrderTheyNeed(t *testing.T) { + isolatePicks(t) + ws := (&fakePicker{choices: []Choice{{Value: "w1", Name: "Support"}}}).register("workspace-id", "workspace") + projects := (&fakePicker{choices: []Choice{{Value: "p1", Name: "Bot A"}, {Value: "p2", Name: "Bot B"}}}).register("project-id", "project", "workspace-id") + envs := (&fakePicker{choices: []Choice{{Value: "production", Name: "Production"}}}).register("environment-alias", "environment", "project-id") + + s := newSession("publish", "environment-alias", "name", "project-id") + s.picks["Project"] = "p2" + s.picks["Environment"] = "production" + rest, err := s.fill(fields("environment-alias", "name", "project-id")) + if err != nil { + t.Fatal(err) + } + if got := names(rest); !reflect.DeepEqual(got, []string{"name"}) { + t.Errorf("the form should ask only for what has no picker, got %q", got) + } + if flag(s, "project-id") != "p2" || flag(s, "environment-alias") != "production" { + t.Errorf("picked values should be set on the flags: project %q, environment %q", flag(s, "project-id"), flag(s, "environment-alias")) + } + if !reflect.DeepEqual(projects.calls, []map[string]string{{"workspace-id": "w1"}}) || !reflect.DeepEqual(envs.calls, []map[string]string{{"project-id": "p2"}}) { + t.Errorf("each list should get what was picked before it: projects %v, environments %v", projects.calls, envs.calls) + } + if len(ws.calls) != 1 || !strings.Contains(s.out.String(), "Using workspace Support (w1), the only one") { + t.Errorf("the only workspace should be taken and said so, got %q", s.out.String()) + } + // Publishing changes the environment, so the lone one is still shown. + if !reflect.DeepEqual(s.shown, []string{"Project", "Environment"}) { + t.Errorf("lists shown: %q", s.shown) + } +} + +func TestALoneChoiceIsTakenWhenNothingChanges(t *testing.T) { + isolatePicks(t) + (&fakePicker{choices: []Choice{{Value: "w1", Name: "Support"}}}).register("workspace-id", "workspace") + s := newSession("list", "workspace-id") + if _, err := s.fill(fields("workspace-id")); err != nil { + t.Fatal(err) + } + if len(s.shown) != 0 || flag(s, "workspace-id") != "w1" { + t.Errorf("one workspace and a list command: take it. shown %q, flag %q", s.shown, flag(s, "workspace-id")) + } + for _, verb := range []string{"delete", "publish", "merge", "update-traffic-split"} { + if !changesWhatItPicks(&cobra.Command{Use: verb}) { + t.Errorf("%s should always show the list", verb) + } + } +} + +// A list that fails, comes back empty or does not have the ID falls back to +// typing it, as the form asked before pickers. +func TestTypingTheIDIsAlwaysThere(t *testing.T) { + isolatePicks(t) + (&fakePicker{err: errors.New("HTTP 401\nbody")}).register("workspace-id", "workspace") + s := newSession("list", "workspace-id") + s.typing = "w9" + if _, err := s.fill(fields("workspace-id")); err != nil { + t.Fatal(err) + } + if flag(s, "workspace-id") != "w9" || !strings.Contains(s.out.String(), "Couldn't list your workspaces: HTTP 401") { + t.Errorf("a failed list should say so and ask for the ID: flag %q, said %q", flag(s, "workspace-id"), s.out.String()) + } + + isolatePicks(t) + (&fakePicker{}).register("organization-id", "organization") + s = newSession("create", "organization-id") + rest, err := s.fill(fields("organization-id")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(s.out.String(), "No organizations found") || len(rest) != 1 { + t.Errorf("an empty list, then nothing typed: the form asks as before. said %q, rest %q", s.out.String(), names(rest)) + } + + isolatePicks(t) + (&fakePicker{choices: []Choice{{Value: "o1", Name: "Acme"}, {Value: "o2", Name: "Beta"}}}).register("organization-id", "organization") + s = newSession("create", "organization-id") + s.picks["Organization"] = typeOwn + s.typing = " o3 " + if _, err := s.fill(fields("organization-id")); err != nil { + t.Fatal(err) + } + if flag(s, "organization-id") != "o3" || !reflect.DeepEqual(s.asked, []string{"Organization ID"}) { + t.Errorf("Type an ID… should ask for it: flag %q, asked %q", flag(s, "organization-id"), s.asked) + } +} + +// An ID given on the command line is used, not picked, and what needs it +// lists with it. +func TestAGivenFlagIsNotPicked(t *testing.T) { + isolatePicks(t) + projects := (&fakePicker{choices: []Choice{{Value: "p1"}}}).register("project-id", "project", "workspace-id") + envs := (&fakePicker{choices: []Choice{{Value: "development", Name: "Dev"}, {Value: "production", Name: "Prod"}}}).register("environment-alias", "environment", "project-id") + s := newSession("get", "environment-alias", "project-id") + if err := s.cmd.Flags().Set("project-id", "given"); err != nil { + t.Fatal(err) + } + if _, err := s.fill(fields("environment-alias")); err != nil { + t.Fatal(err) + } + if len(projects.calls) != 0 || !reflect.DeepEqual(envs.calls, []map[string]string{{"project-id": "given"}}) { + t.Errorf("projects %v, environments %v", projects.calls, envs.calls) + } +} + +// The last pick is the default: first in the list, where Enter takes it. +func TestTheLastPickComesFirst(t *testing.T) { + isolatePicks(t) + (&fakePicker{choices: []Choice{{Value: "p1", Name: "A"}, {Value: "p2", Name: "B"}, {Value: "p3", Name: "C"}}}).register("project-id", "project") + s := newSession("get", "project-id") + s.picks["Project"] = "p3" + if _, err := s.fill(fields("project-id")); err != nil { + t.Fatal(err) + } + if lastPick("project-id") != "p3" { + t.Fatalf("the pick should be remembered, got %q", lastPick("project-id")) + } + info, err := os.Stat(picksPath()) + if err != nil || info.Mode().Perm() != 0o600 { + t.Errorf("picks.json should be readable by its owner only: %v %v", info.Mode().Perm(), err) + } + got := lastPickFirst([]Choice{{Value: "p1"}, {Value: "p2"}, {Value: "p3"}}, "p3") + if got[0].Value != "p3" || got[1].Value != "p1" || got[2].Value != "p2" { + t.Errorf("got %v", got) + } + if got := lastPickFirst([]Choice{{Value: "p1"}}, "gone"); got[0].Value != "p1" { + t.Errorf("a last pick no longer listed changes nothing, got %v", got) + } +} + +func TestOptionsLineUpAndEndWithTypingAnID(t *testing.T) { + opts := optionsFor([]Choice{{Value: "a", Name: "Support bot", Detail: "6a67"}, {Value: "b", Name: "Sales", Detail: "6a68"}}) + if len(opts) != 3 || opts[2].Value != typeOwn || opts[2].Key != "Type an ID…" { + t.Fatalf("got %v", opts) + } + if opts[0].Key != "Support bot 6a67" || opts[1].Key != "Sales 6a68" { + t.Errorf("details should line up: %q / %q", opts[0].Key, opts[1].Key) + } +} diff --git a/internal/interactive/picks.go b/internal/interactive/picks.go new file mode 100644 index 0000000..bedf4d6 --- /dev/null +++ b/internal/interactive/picks.go @@ -0,0 +1,50 @@ +// This file is not generated by Speakeasy. It remembers the last value picked +// for each flag, so the next list puts it first and Enter takes it again. + +package interactive + +import ( + "encoding/json" + "os" + "path/filepath" + + "github.com/voiceflow/cli/internal/config" +) + +// picksPath is beside config.yaml: ~/.config/vf/picks.json. +var picksPath = func() string { + return filepath.Join(filepath.Dir(config.GetConfigPath()), "picks.json") +} + +func readPicks() map[string]string { + picks := map[string]string{} + if data, err := os.ReadFile(picksPath()); err == nil { + _ = json.Unmarshal(data, &picks) + } + return picks +} + +// lastPick is the value picked for flag last time, or "". +func lastPick(flag string) string { return readPicks()[flag] } + +// savePick remembers value for flag, readable by its owner only. It is a +// convenience, so a failure is silent. +func savePick(flag, value string) { + picks := readPicks() + if picks[flag] == value { + return + } + picks[flag] = value + data, err := json.MarshalIndent(picks, "", " ") + if err != nil { + return + } + path := picksPath() + if os.MkdirAll(filepath.Dir(path), 0o700) != nil { + return + } + tmp := path + ".tmp" + if os.WriteFile(tmp, append(data, '\n'), 0o600) == nil { + _ = os.Rename(tmp, path) + } +} From 13ba88f0180cd52c2f6865c5ec25abc7bcef3012 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:23:23 -0500 Subject: [PATCH 03/30] feat: list organizations, workspaces, projects and environments Registers the four pickers most commands need: --project-id is required by 252 of 273 commands and --environment-alias by 197. Organizations come from the workspace list, since the API has no organizations endpoint and no organization names: each is named by its workspaces ("Acme, Support +2 more"). Workspaces say which org they are in when there is more than one; environments are picked by alias, with the main one marked. Tests run against a fake API server; none lists a real account. --- internal/cli/pickers.go | 135 +++++++++++++++++++++++++++++++++++ internal/cli/pickers_test.go | 120 +++++++++++++++++++++++++++++++ internal/ui/DESIGN.md | 38 ++++++++++ 3 files changed, 293 insertions(+) create mode 100644 internal/cli/pickers.go create mode 100644 internal/cli/pickers_test.go diff --git a/internal/cli/pickers.go b/internal/cli/pickers.go new file mode 100644 index 0000000..63ecc58 --- /dev/null +++ b/internal/cli/pickers.go @@ -0,0 +1,135 @@ +// This file is not generated by Speakeasy. It tells the form what to list for +// each ID it can look up (internal/interactive/pickers.go): your +// organizations, workspaces, projects and environments. + +package cli + +import ( + "context" + "strconv" + "strings" + + "github.com/spf13/cobra" + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/interactive" + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" +) + +func init() { + interactive.RegisterPicker("organization-id", interactive.Picker{ + Noun: "organization", Plural: "organizations", List: listOrganizations, + }) + interactive.RegisterPicker("workspace-id", interactive.Picker{ + Noun: "workspace", Plural: "workspaces", List: listWorkspaceChoices, + }) + interactive.RegisterPicker("project-id", interactive.Picker{ + Noun: "project", Plural: "projects", Needs: []string{"workspace-id"}, List: listProjects, + }) + interactive.RegisterPicker("environment-alias", interactive.Picker{ + Noun: "environment", Plural: "environments", Needs: []string{"project-id"}, List: listEnvironments, + }) +} + +func listWorkspaces(ctx context.Context, cmd *cobra.Command, msg string) ([]components.StableWorkspace, error) { + s, err := client.NewClient(cmd) + if err != nil { + return nil, err + } + res, err := s.Workspace.List(client.WithSpinnerMessage(ctx, msg)) + if err != nil || res.StableWorkspaceListResponse == nil { + return nil, err + } + return res.StableWorkspaceListResponse.Workspaces, nil +} + +func listWorkspaceChoices(ctx context.Context, cmd *cobra.Command, _ map[string]string) ([]interactive.Choice, error) { + workspaces, err := listWorkspaces(ctx, cmd, "Loading your workspaces…") + if err != nil { + return nil, err + } + orgs := map[string]bool{} + for _, w := range workspaces { + orgs[w.OrganizationID] = true + } + choices := make([]interactive.Choice, 0, len(workspaces)) + for _, w := range workspaces { + detail := w.ID + if len(orgs) > 1 { + detail += " · org " + w.OrganizationID // the same name can be in two orgs + } + choices = append(choices, interactive.Choice{Value: w.ID, Name: w.Name, Detail: detail}) + } + return choices, nil +} + +// listOrganizations reads your organizations off your workspaces, since the +// API has no organizations endpoint and no organization names: each is +// named by its workspaces. An organization you have no workspace in is not +// listed; "Type an ID…" covers it. +func listOrganizations(ctx context.Context, cmd *cobra.Command, _ map[string]string) ([]interactive.Choice, error) { + workspaces, err := listWorkspaces(ctx, cmd, "Loading your organizations…") + if err != nil { + return nil, err + } + var order []string + names := map[string][]string{} + for _, w := range workspaces { + if _, seen := names[w.OrganizationID]; !seen { + order = append(order, w.OrganizationID) + } + names[w.OrganizationID] = append(names[w.OrganizationID], w.Name) + } + choices := make([]interactive.Choice, 0, len(order)) + for _, org := range order { + choices = append(choices, interactive.Choice{Value: org, Name: workspaceNames(names[org]), Detail: org}) + } + return choices, nil +} + +// workspaceNames is "Acme, Support, Sales", or "Acme, Support +4 more". +func workspaceNames(names []string) string { + const shown = 3 + if len(names) <= shown { + return strings.Join(names, ", ") + } + return strings.Join(names[:shown-1], ", ") + " +" + strconv.Itoa(len(names)-shown+1) + " more" +} + +func listProjects(ctx context.Context, cmd *cobra.Command, needs map[string]string) ([]interactive.Choice, error) { + s, err := client.NewClient(cmd) + if err != nil { + return nil, err + } + res, err := s.Project.List(client.WithSpinnerMessage(ctx, "Loading projects…"), + operations.StableProjectControllerListRequest{WorkspaceID: needs["workspace-id"]}) + if err != nil || res.StableProjectListResponse == nil { + return nil, err + } + var choices []interactive.Choice + for _, p := range res.StableProjectListResponse.Projects { + choices = append(choices, interactive.Choice{Value: p.ID, Name: p.Name, Detail: p.ID}) + } + return choices, nil +} + +func listEnvironments(ctx context.Context, cmd *cobra.Command, needs map[string]string) ([]interactive.Choice, error) { + s, err := client.NewClient(cmd) + if err != nil { + return nil, err + } + res, err := s.Environment.List(client.WithSpinnerMessage(ctx, "Loading environments…"), + operations.StableEnvironmentControllerListRequest{ProjectID: needs["project-id"]}) + if err != nil || res.StableEnvironmentListResponse == nil { + return nil, err + } + var choices []interactive.Choice + for _, e := range res.StableEnvironmentListResponse.Environments { + detail := e.Alias + if e.IsMain { + detail += " · main" + } + choices = append(choices, interactive.Choice{Value: e.Alias, Name: e.Name, Detail: detail}) + } + return choices, nil +} diff --git a/internal/cli/pickers_test.go b/internal/cli/pickers_test.go new file mode 100644 index 0000000..db67341 --- /dev/null +++ b/internal/cli/pickers_test.go @@ -0,0 +1,120 @@ +// This file is not generated by Speakeasy. It covers pickers.go, against a +// fake API server: no test lists a real account's workspaces. + +package cli + +import ( + "context" + "net/http" + "net/http/httptest" + "reflect" + "testing" + + "github.com/spf13/cobra" + "github.com/voiceflow/cli/internal/interactive" +) + +const stamp = `"createdAt":"2026-01-01T00:00:00Z","updatedAt":"2026-01-01T00:00:00Z","image":null` + +// fakeAPI answers the three list calls the pickers make, and fails the test +// on any other request or on a list asked for the wrong parent. +func fakeAPI(t *testing.T) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + q := r.URL.Query() + switch { + case r.URL.Path == "/v1/stable/workspace": + _, _ = w.Write([]byte(`{"workspaces":[ + {"id":"w1","name":"Acme",` + stamp + `,"organizationID":"o1"}, + {"id":"w2","name":"Support",` + stamp + `,"organizationID":"o1"}, + {"id":"w3","name":"Lab",` + stamp + `,"organizationID":"o2"}, + {"id":"w4","name":"Sales",` + stamp + `,"organizationID":"o1"}, + {"id":"w5","name":"Ops",` + stamp + `,"organizationID":"o1"}]}`)) + case r.URL.Path == "/v1/stable/project" && q.Get("workspaceID") == "w2": + _, _ = w.Write([]byte(`{"projects":[{"id":"p1","name":"Help bot",` + stamp + `,"workspaceID":"w2","description":null}]}`)) + case r.URL.Path == "/v1/stable/environment" && q.Get("projectID") == "p1": + _, _ = w.Write([]byte(`{"environments":[ + {"name":"Production","alias":"production","isMain":true,"releases":[],"createdAt":"2026-01-01T00:00:00Z","trafficPercentage":100}, + {"name":"Staging","alias":"staging","isMain":false,"releases":[],"createdAt":"2026-01-01T00:00:00Z","trafficPercentage":0}]}`)) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL) + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + return srv +} + +// apiCommand is a real vf command pointed at the fake server with a dummy +// token, so no stored credential is read or sent. +func apiCommand(t *testing.T, srv *httptest.Server) *cobra.Command { + t.Helper() + isolate(t) + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + cmd, _, err := root.Find([]string{"environment", "publish"}) + if err != nil { + t.Fatal(err) + } + if err := cmd.ParseFlags([]string{"--server-url", srv.URL, "--token", "vfp_test"}); err != nil { + t.Fatal(err) + } + return cmd +} + +func TestPickersListFromTheAPI(t *testing.T) { + srv := fakeAPI(t) + cmd := apiCommand(t, srv) + ctx := context.Background() + + orgs, err := listOrganizations(ctx, cmd, nil) + if err != nil { + t.Fatal(err) + } + want := []interactive.Choice{ + {Value: "o1", Name: "Acme, Support +2 more", Detail: "o1"}, + {Value: "o2", Name: "Lab", Detail: "o2"}, + } + if !reflect.DeepEqual(orgs, want) { + t.Errorf("organizations come from the workspaces, named by them:\n got %+v\nwant %+v", orgs, want) + } + + workspaces, err := listWorkspaceChoices(ctx, cmd, nil) + if err != nil { + t.Fatal(err) + } + if len(workspaces) != 5 || workspaces[1] != (interactive.Choice{Value: "w2", Name: "Support", Detail: "w2 · org o1"}) { + t.Errorf("with two orgs, each workspace says which: %+v", workspaces) + } + + projects, err := listProjects(ctx, cmd, map[string]string{"workspace-id": "w2"}) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(projects, []interactive.Choice{{Value: "p1", Name: "Help bot", Detail: "p1"}}) { + t.Errorf("projects: %+v", projects) + } + + envs, err := listEnvironments(ctx, cmd, map[string]string{"project-id": "p1"}) + if err != nil { + t.Fatal(err) + } + want = []interactive.Choice{ + {Value: "production", Name: "Production", Detail: "production · main"}, + {Value: "staging", Name: "Staging", Detail: "staging"}, + } + if !reflect.DeepEqual(envs, want) { + t.Errorf("environments are picked by alias:\n got %+v\nwant %+v", envs, want) + } +} + +func TestWorkspaceNames(t *testing.T) { + for in, want := range map[int]string{1: "a", 3: "a, b, c", 4: "a, b +2 more"} { + if got := workspaceNames([]string{"a", "b", "c", "d"}[:in]); got != want { + t.Errorf("%d names: got %q, want %q", in, got, want) + } + } +} diff --git a/internal/ui/DESIGN.md b/internal/ui/DESIGN.md index 6148be0..6ce32a4 100644 --- a/internal/ui/DESIGN.md +++ b/internal/ui/DESIGN.md @@ -245,6 +245,44 @@ Build workflows: blocks, steps, branches and links workflow --help shows a command's flags ``` +## Pickers + +When a command needs an ID it was not given, at a terminal, the form lists +what you have instead of asking you to paste one +(`internal/interactive/pickers.go`; `internal/cli/pickers.go` says what each +flag lists). + +``` +✓ Using workspace Support (w1), the only one +┃ Project +┃ --project-id · / to filter · enter to pick +┃ > Help bot p1 +┃ Sales bot p2 +┃ Type an ID… +``` + +- **Which IDs:** organization, workspace, project and environment, the ones + most commands need (`--project-id` alone is required by 252 of 273). +- **In order:** what an ID depends on is picked first. A project needs its + workspace, picked on the way even when the command has no + `--workspace-id`; an environment needs its project. +- **One choice** is taken, and a status line says so, unless the command + changes or removes what it picks (delete, publish, merge, update…): + deleting your only project still asks which. +- **The default** is the last pick: first in the list, where Enter takes it + again, but never taken without asking. Kept in `~/.config/vf/picks.json`, + readable by its owner only. +- **Organizations** come from your workspaces. The API has no organizations + endpoint and no organization names, so each is named by its workspaces + (`Acme, Support +2 more`), and one you have no workspace in is not listed. +- **Type an ID…** ends every list, for an ID that is not in it. A list that + fails or comes back empty says so (`⚠ Couldn't list your workspaces: …`) + and asks for the ID, as the form did before. +- **Only where the form runs:** at a terminal, outside agent mode, without + `--no-interactive`. Agents and scripts get the error naming the flag, as + before. While a list loads, the spinner says what it loads + (`✻ Loading projects…`). + ## Aligning vfe `vfe` already shares the accent, the rounded banner with its title in the From f933b1fef5e3d10e7dbbd119f73c5df3e6fef948 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:24:57 -0500 Subject: [PATCH 04/30] feat(output): explain every API and connection error, with next steps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An API error printed its raw JSON body, then a generic hint that told everyone with a 401 or 403 to run 'vf auth login', 'vf auth signup' or 'vf configure'. A signed-in user whose browser session was refused, as when creating a workspace without an admin role, was told to sign in again; a 403 got the same advice; and the hints the SDK hook injected said personal keys expire, which a session does not. internal/output/explain.go now decides what every failure says: what happened, why, and what to do next, drawn per internal/ui/DESIGN.md: ✗ Couldn't get project · HTTP 404 Not Found ⎿ Project not found Check --project-id p1: it may be wrong, or belong to another workspace or environment. Next: vf project list lists the IDs you can use Docs: https://www.voiceflow.com/docs/cli/commands/project - A 401 is explained by the credential sent: a key from --token, a VF_TOKEN that outranks the session, or a current browser session, which makes it a permission problem. - 402 links the add-credits page; 409, 429 (Retry-After), 5xx, an undocumented status and an unreadable response each say why and what next; field errors name their flag. - Timeouts, DNS failures, refused connections and TLS failures say which, and name the server URL when it was overridden. They used to be classified as connection errors with "check network connectivity", including a response vf could not decode. - Not signed in leads with 'vf auth login'; Settings → Personal keys replaces the old Access tokens name. - Agents get the same content in the envelope: explanation, hints and docs_url, with a server's own hints winning. The SDK hook keeps the no-credential preflight and the malformed-token warnings; its per-status hints move into explain.go, which knows the command, its flags and the credential. --- internal/interactive/pickers.go | 9 +- internal/output/explain.go | 731 ++++++++++++++++++ internal/output/explain_test.go | 360 +++++++++ internal/output/output.go | 31 +- internal/output/reported.go | 22 +- internal/output/reported_test.go | 14 +- .../sdk/sdkinternal/hooks/registration.go | 4 +- internal/sdk/sdkinternal/hooks/teach.go | 235 +----- test/agent-mode-flag.test.ts | 2 +- test/dry-run.test.ts | 2 +- test/errors-teach.test.ts | 32 +- 11 files changed, 1165 insertions(+), 277 deletions(-) create mode 100644 internal/output/explain.go create mode 100644 internal/output/explain_test.go diff --git a/internal/interactive/pickers.go b/internal/interactive/pickers.go index 0653d82..49665ec 100644 --- a/internal/interactive/pickers.go +++ b/internal/interactive/pickers.go @@ -145,7 +145,7 @@ func (p *picking) pick(flag string, picker Picker, needs map[string]string) (str choices, err := picker.List(ctx, p.cmd, needs) switch { case err != nil: - fmt.Fprintln(p.out, p.u.Status(ui.StatusWarn, "Couldn't list your "+picker.Plural+": "+firstLine(err.Error()))) + fmt.Fprintln(p.out, p.u.Status(ui.StatusWarn, "Couldn't list your "+picker.Plural+": "+output.ShortReason(p.cmd, err))) return p.typeID(flag, picker) case len(choices) == 0: fmt.Fprintln(p.out, p.u.Status(ui.StatusWarn, "No "+picker.Plural+" found")) @@ -285,10 +285,3 @@ func title(noun string) string { } return strings.ToUpper(noun[:1]) + noun[1:] } - -func firstLine(s string) string { - if i := strings.IndexByte(s, '\n'); i >= 0 { - s = s[:i] - } - return truncate(strings.TrimSpace(s), 100) -} diff --git a/internal/output/explain.go b/internal/output/explain.go new file mode 100644 index 0000000..b210f73 --- /dev/null +++ b/internal/output/explain.go @@ -0,0 +1,731 @@ +// This file is not generated by Speakeasy. It decides what vf says when a +// command fails: what happened, why, and what to do next. +// +// One Explanation serves both audiences. Render draws it for a person at a +// terminal (internal/ui/DESIGN.md, "Errors"): +// +// ✗ Couldn't get project · HTTP 404 Not Found +// ⎿ Project not found +// The ID may be wrong, or belong to another workspace or environment. +// Next: +// vf project list lists the projects you can use +// Docs: https://www.voiceflow.com/docs/cli/commands/project +// +// and Envelope adds the same content to the JSON error an agent or a script +// reads, as explanation, hints (the next steps) and docs_url. +// +// Steps name commands in `backticks`: Render draws them in Accent, and the +// JSON gets them in 'single quotes', the convention every other hint uses. + +package output + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "net/url" + "regexp" + "strconv" + "strings" + "syscall" + "time" + "unicode" + "unicode/utf8" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/config" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/ui" +) + +// Explanation is what vf tells someone about a failure. +type Explanation struct { + Type string // error_type, for machines: authentication_error, not_found, … + Title string // what happened, on one line + Message string // the server's own message, when it says more than the status + Why []string // the likely cause, most likely first + Details []string // field errors from the response: "name: Required (--name)" + Next []string // what to do, each a step someone can take + Docs string // the page that covers the command +} + +// Credential is what vf signs its requests with, so a 401 or 403 can be +// explained in terms of it: an expired key and a refused session need +// different fixes. +type Credential struct { + Kind string // CredentialSession, CredentialKey, or "" for none + Source string // where a key came from: "--token", "VF_TOKEN", "your saved token" + Expiry time.Time // a session's expiry + Renews bool // a session renews itself + EnvWins bool // VF_TOKEN is set, so it outranks a session +} + +const ( + CredentialSession = "session" // signed in with 'vf auth login' + CredentialKey = "key" // a personal or service key +) + +// DescribeCredential reports the credential vf sends. The cli package +// replaces it with one that also sees the browser session, which this +// package cannot import (internal/oauth imports output). +var DescribeCredential = func(cmd *cobra.Command) Credential { + switch _, source := config.ResolveSecurityCredential(cmd, "token"); source { + case "flag": + return Credential{Kind: CredentialKey, Source: "--token"} + case "env": + return Credential{Kind: CredentialKey, Source: "VF_TOKEN", EnvWins: true} + case "keyring", "config": + return Credential{Kind: CredentialKey, Source: "your saved token"} + } + return Credential{} +} + +const ( + docsCommandBase = "https://www.voiceflow.com/docs/cli/commands" + AuthDocsURL = "https://www.voiceflow.com/docs/api-reference/authentication" + updateCommand = "npm install -g @voiceflow/cli" +) + +// docsGroupPages is the set of command groups with a page under +// docsCommandBase; other commands link the overview. +var docsGroupPages = map[string]bool{ + "agent": true, "analytics": true, "api-tool": true, "conversation": true, + "document": true, "environment": true, "evaluation": true, "function": true, + "knowledge-base": true, "mcp-server": true, "mcp-tool": true, "playbook": true, + "project": true, "tool": true, "transcript": true, "variable": true, "workspace": true, +} + +// ExplainError explains any error a command returns: an API error, a request +// that never got an answer, a response vf could not read, or a credential +// that is missing. +func ExplainError(cmd *cobra.Command, err error) Explanation { + return explain(cmd, err, extractErrorStatusCode(err), extractErrorBody(err)) +} + +func explain(cmd *cobra.Command, err error, status int, body string) Explanation { + if x, ok := explainNoCredential(cmd, err); ok { + return x + } + if status != 0 { + return explainAPI(cmd, err, status, body, extractErrorResponseHeaders(err)) + } + if x, ok := explainTransport(cmd, err); ok { + return x + } + return Explanation{Type: "error", Title: action(cmd) + ": " + firstLine(err.Error())} +} + +// ShortReason is one line saying why a request failed, for a status line +// that reports the failure in passing: "Couldn't list your workspaces: …". +func ShortReason(cmd *cobra.Command, err error) string { + x := ExplainError(cmd, err) + if x.Type == "error" { // nothing more to say than the error itself + return firstLine(err.Error()) + } + _, reason, found := strings.Cut(x.Title, " · ") + if !found { + reason = x.Title + } + if x.Message != "" { + reason += " — " + x.Message + } + return reason +} + +func explainAPI(cmd *cobra.Command, err error, status int, body string, headers http.Header) Explanation { + fields := parseObject(body) + x := Explanation{ + Type: classifyErrorType(status), + Title: action(cmd) + " · HTTP " + strconv.Itoa(status) + " " + http.StatusText(status), + Message: serverMessage(status, fields, body), + Details: fieldErrors(cmd, fields), + Docs: docsFor(cmd), + } + cred := DescribeCredential(cmd) + + switch { + case status < 400: + // The SDK treats any status the operation does not document as an + // error, a 200 where only 201 means success among them. + x.Type = "unexpected_response" + x.Title = action(cmd) + " · unexpected HTTP " + strconv.Itoa(status) + " " + http.StatusText(status) + x.Why = []string{"Voiceflow answered, but not with a status this version of vf expects for this command. The API may have changed since this vf was built."} + x.Next = []string{"Update vf: `" + updateCommand + "`", "Run it again with `--debug` to see the full response"} + + case status == 400 || status == 422: + if len(x.Details) == 0 && x.Message == "" { + x.Why = []string{"Voiceflow rejected some of the values sent."} + } + if len(x.Details) > 0 { + x.Next = append(x.Next, "Fix the values above, then run it again") + } + x.Next = append(x.Next, + "Add `--dry-run` to see the exact request without sending it", + "`"+cmd.CommandPath()+" --help` lists the flags and the values they take") + + case status == 401: + x.Why, x.Next = unauthorized(cred) + + case status == 402: + x.Type = "payment_required" + if x.Message == "" { + x.Why = []string{"The workspace is out of credits, so Voiceflow didn't run this."} + } + if link := detailString(fields, "addCreditsURL"); link != "" { + x.Next = []string{"Add credits or upgrade the plan: " + link} + } else { + x.Next = []string{"Add credits or upgrade the workspace's plan in Voiceflow"} + } + + case status == 403: + x.Why = []string{"You're signed in, but your account isn't allowed to do this. The resource may belong to a workspace or organization you can't act on, or your role there may not include this action."} + if cred.Kind == CredentialKey { + x.Why = append(x.Why, "Personal keys can also be limited to some workspaces, projects and actions; the one from "+cred.Source+" may not cover this.") + } + x.Next = []string{"`vf workspace list` shows the workspaces you can reach", "Ask an admin of that workspace or organization for access"} + if cred.Kind == CredentialKey { + x.Next = append(x.Next, "Check the key's access in Voiceflow under Settings → Personal keys") + } + + case status == 404: + x.Why = []string{"The ID may be wrong, or belong to another workspace or environment."} + if given := givenIDs(cmd); given != "" { + x.Why = []string{"Check " + given + ": it may be wrong, or belong to another workspace or environment."} + } + if list := listCommand(cmd); list != "" { + x.Next = []string{"`" + list + "` lists the IDs you can use"} + } + + case status == 409: + x.Why = []string{"It conflicts with something that already exists, such as a name that's already taken."} + x.Next = []string{"Use a different name, or change the one that exists"} + if list := listCommand(cmd); list != "" { + x.Next = append(x.Next, "`"+list+"` shows what's there") + } + + case status == 429: + x.Why = []string{"Too many requests in a short time."} + x.Next = []string{waitStep(headers.Get("Retry-After"))} + + case status >= 500: + x.Why = []string{"Voiceflow had a problem on its side. It's usually temporary."} + if status == 502 || status == 503 || status == 504 { + x.Why = []string{"Voiceflow is unavailable or overloaded right now. It's usually temporary."} + } + x.Next = []string{"Run it again in a minute", supportStep(headers)} + + default: + x.Why = []string{"Voiceflow rejected the request."} + x.Next = []string{"Run it again with `--debug` to see the full request and response"} + } + + // A server that says what to do knows better than these defaults. + if hints := stringList(fields["hints"]); len(hints) > 0 { + x.Next = hints + } + if docs, ok := fields["docs_url"].(string); ok && docs != "" { + x.Docs = docs + } + return x +} + +// unauthorized explains a 401 in terms of the credential that was sent. +func unauthorized(cred Credential) (why, next []string) { + switch cred.Kind { + case CredentialSession: + if !cred.Expiry.IsZero() && time.Now().After(cred.Expiry) && !cred.Renews { + return []string{"Your browser session has ended."}, []string{"Sign in again: `vf auth login`"} + } + return []string{ + "You're signed in, and your session is current, so this isn't an expired login.", + "Most likely your account isn't allowed to do this in the workspace or organization it targets: some actions, such as creating a workspace, need an admin role there.", + }, []string{ + "Check your role there, or try the same thing in the Voiceflow app", + "`vf auth whoami` shows who you're signed in as", + "If your access changed recently, sign in again: `vf auth logout`, then `vf auth login`", + } + case CredentialKey: + why = []string{"Voiceflow didn't accept the token from " + cred.Source + ". Personal keys expire (after 30 days by default) and can be deleted; this one may have lapsed."} + if cred.EnvWins { + next = append(next, "To sign in with your browser instead: `unset VF_TOKEN`, then `vf auth login`") + } else { + next = append(next, "`vf auth login` signs you in with your browser instead") + } + next = append(next, "Or create a new key in Voiceflow under Settings → Personal keys, then pass it with `--token` or `export VF_TOKEN=vfp_...`") + return why, next + } + return []string{"Voiceflow didn't accept the request's credentials."}, []string{"Sign in: `vf auth login`"} +} + +// explainNoCredential recognizes the request the SDK refused to send because +// no credential is set up (internal/sdk/sdkinternal/hooks/teach.go). +func explainNoCredential(cmd *cobra.Command, err error) (Explanation, bool) { + var missing interface{ NoCredential() bool } + if !errors.As(err, &missing) || !missing.NoCredential() { + return Explanation{}, false + } + x := Explanation{ + Type: "authentication_error", + Title: action(cmd) + " · you're not signed in", + Why: []string{"No credential is set up, so the request wasn't sent."}, + Next: []string{ + "`vf auth login` signs you in with your browser", + "For CI or scripts: `export VF_TOKEN=vfp_...` with a personal key from Settings → Personal keys", + }, + Docs: AuthDocsURL, + } + if IsAgentMode() { + x.Next = []string{ + "Run `vf auth login` in the background and give the user the authorization_url it prints; it waits until they finish signing in", + "Or, without a browser: `export VF_TOKEN=vfp_...` with a personal key the user creates under Settings → Personal keys (every command also accepts --token)", + "`vf auth whoami` shows what is configured, without a network call", + } + } + return x, true +} + +// explainTransport explains a request that got no answer, or an answer vf +// could not read. +func explainTransport(cmd *cobra.Command, err error) (Explanation, bool) { + msg := err.Error() + x := Explanation{Type: "connection_error", Docs: docsFor(cmd)} + + var urlErr *url.Error + host, target := "", "" + if errors.As(err, &urlErr) { + if u, parseErr := url.Parse(urlErr.URL); parseErr == nil { + host, target = u.Host, u.Scheme+"://"+u.Host + } + } + serverStep := "Check your internet connection, and any VPN or proxy" + if source := serverURLSource(cmd); source != "" { + serverStep = "Check the server URL " + target + ", which comes from " + source + } + + var dnsErr *net.DNSError + var netErr net.Error + switch { + case strings.Contains(msg, "error unmarshaling json response body"): + x.Type = "unexpected_response" + x.Title = action(cmd) + " · couldn't read the response" + x.Why = []string{"Voiceflow's answer wasn't in the shape this version of vf expects (" + lastCause(msg) + ")."} + x.Next = []string{"Run it again; if it keeps happening, update vf: `" + updateCommand + "`", "`--debug` shows the raw response"} + case errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &netErr) && netErr.Timeout()): + x.Type = "timeout" + x.Title = action(cmd) + " · timed out" + if limit, _ := flagutil.GetStringFlag(cmd, "timeout"); limit != "" { + x.Why = []string{"Voiceflow didn't answer within --timeout " + limit + "."} + } else { + x.Why = []string{"Voiceflow took too long to answer."} + } + x.Next = []string{"Run it again with a longer timeout, such as `--timeout 2m`", serverStep} + case errors.As(err, &dnsErr): + x.Title = action(cmd) + " · couldn't reach Voiceflow" + x.Why = []string{"Couldn't look up " + dnsErr.Name + "."} + x.Next = []string{serverStep} + case errors.Is(err, syscall.ECONNREFUSED): + x.Title = action(cmd) + " · couldn't reach Voiceflow" + x.Why = []string{"Nothing answered at " + orDefault(target, "the server") + " (connection refused)."} + x.Next = []string{serverStep} + case strings.Contains(msg, "x509:") || strings.Contains(msg, "tls:"): + x.Title = action(cmd) + " · couldn't connect securely" + x.Why = []string{"The secure connection to " + orDefault(host, "Voiceflow") + " failed (" + lastCause(msg) + ")."} + x.Next = []string{"A proxy or VPN that inspects HTTPS can cause this; so can a wrong system clock", serverStep} + case strings.HasPrefix(msg, "error sending request"): + x.Title = action(cmd) + " · couldn't reach Voiceflow" + x.Why = []string{lastCause(msg) + "."} + x.Next = []string{serverStep, "`--debug` shows the request"} + default: + return Explanation{}, false + } + return x, true +} + +// Envelope adds an explanation to a JSON error object, keeping every key the +// response already has: a server's own hints and docs win. +func Envelope(m map[string]interface{}, x Explanation) { + if _, has := m["error_type"]; !has && x.Type != "" && IsAgentMode() { + m["error_type"] = x.Type + } + if _, has := m["message"]; !has && x.Title != "" { + m["message"] = x.Title + } + if why := strings.Join(x.Why, " "); why != "" { + if _, has := m["explanation"]; !has { + m["explanation"] = Plain(why) + } + } + if _, has := m["hints"]; !has && len(x.Next) > 0 { + hints := make([]string, len(x.Next)) + for i, step := range x.Next { + hints[i] = Plain(step) + } + m["hints"] = hints + } + if _, has := m["docs_url"]; !has && x.Docs != "" { + m["docs_url"] = x.Docs + } +} + +// Render writes x for a person: +// +// ✗ +// ⎿ <Message> +// <Why…> +// <Details…> +// Next: +// <step…> +// Docs: <url> +// +// Off a terminal the glyphs become "Error:" and "-", as every status does. +func Render(cmd *cobra.Command, x Explanation) { + w := cmd.ErrOrStderr() + u := UI(cmd, w) + title := x.Title + if !u.Decorated() { + title = strings.ReplaceAll(title, " · ", " | ") + } + fmt.Fprintln(w, u.Status(ui.StatusFailed, title)) + + var under []string + if x.Message != "" { + under = append(under, x.Message) + } + under = append(under, x.Why...) + under = append(under, x.Details...) + if len(under) > 0 { + fmt.Fprintln(w, u.Under(under...)) + } + if len(x.Next) > 0 { + fmt.Fprintln(w, " "+u.Bold("Next:")) + for _, step := range x.Next { + fmt.Fprintln(w, " "+styleCode(u, step)) + } + } + if x.Docs != "" { + fmt.Fprintln(w, " "+u.Muted("Docs: "+x.Docs)) + } +} + +// Report prints x where it belongs, as JSON in agent mode and for a person +// otherwise, and returns err marked as reported. +func Report(cmd *cobra.Command, x Explanation, err error) error { + if IsAgentMode() { + m := map[string]interface{}{"error": x.Title} + if x.Message != "" { + m["message"] = x.Title + ": " + x.Message + } + Envelope(m, x) + if len(x.Details) > 0 { + m["details"] = x.Details + } + // No HTML escaping: a step such as "--project-id <value>" should + // read as written, not as "\u003cvalue\u003e". + enc := json.NewEncoder(cmd.ErrOrStderr()) + enc.SetEscapeHTML(false) + enc.SetIndent("", " ") + _ = enc.Encode(m) + return AlreadyReported(err) + } + Render(cmd, x) + return AlreadyReported(err) +} + +var codeSpan = regexp.MustCompile("`([^`]+)`") + +// Plain is a step with its commands in 'single quotes', for JSON and logs. +func Plain(s string) string { return codeSpan.ReplaceAllString(s, "'$1'") } + +// styleCode draws the commands in a step in Accent, at a terminal, and +// quotes them anywhere else. +func styleCode(u *ui.UI, s string) string { + if !u.Decorated() && !u.Colored() { + return Plain(s) + } + return codeSpan.ReplaceAllStringFunc(s, func(m string) string { return u.Accent(m[1 : len(m)-1]) }) +} + +// action is what the command was doing, as the start of a failure: +// "Couldn't list workspaces". +func action(cmd *cobra.Command) string { + if cmd == nil { + return "Couldn't run the command" + } + short := strings.TrimSuffix(strings.TrimSpace(cmd.Short), ".") + if short == "" || utf8.RuneCountInString(short) > 60 { + return "Couldn't run " + cmd.CommandPath() + } + r, size := utf8.DecodeRuneInString(short) + if next, _ := utf8.DecodeRuneInString(short[size:]); !unicode.IsUpper(next) { + short = string(unicode.ToLower(r)) + short[size:] + } + return "Couldn't " + short +} + +// docsFor is the docs page for cmd's command group. +func docsFor(cmd *cobra.Command) string { + if group := commandGroup(cmd); docsGroupPages[group] { + return docsCommandBase + "/" + group + } + return docsCommandBase + "/overview" +} + +// commandGroup is the top-level command cmd belongs to: "project" for +// 'vf project get'. +func commandGroup(cmd *cobra.Command) string { + if cmd == nil { + return "" + } + for c := cmd; c.HasParent(); c = c.Parent() { + if !c.Parent().HasParent() { + return c.Name() + } + } + return "" +} + +// listCommand is the list command beside cmd, which shows the IDs it takes: +// 'vf project list' for 'vf project get'. Empty when there is none. +func listCommand(cmd *cobra.Command) string { + if cmd == nil || !cmd.HasParent() { + return "" + } + for _, sibling := range cmd.Parent().Commands() { + if sibling.Name() == "list" && sibling != cmd { + return sibling.CommandPath() + } + } + return "" +} + +// givenIDs names the ID flags the command was given: "--project-id p1". +func givenIDs(cmd *cobra.Command) string { + if cmd == nil { + return "" + } + var given []string + for _, name := range []string{"organization-id", "workspace-id", "project-id", "environment-alias", "environment-id"} { + if f := cmd.Flags().Lookup(name); f != nil && f.Changed { + given = append(given, "--"+name+" "+f.Value.String()) + } + } + for _, f := range []string{"id"} { + if flag := cmd.Flags().Lookup(f); flag != nil && flag.Changed { + given = append(given, "--"+f+" "+flag.Value.String()) + } + } + return strings.Join(given, ", ") +} + +// serverURLSource names where a server URL other than the default came from, +// or "" when vf is using its default. +func serverURLSource(cmd *cobra.Command) string { + if cmd != nil { + if f := cmd.Flags().Lookup("server-url"); f != nil && f.Changed { + return "--server-url" + } + } + if config.GetEnvValue("server-url") != "" { + return "VF_SERVER_URL" + } + if config.GetConfigValue("server-url") != "" { + return "server-url in " + config.GetConfigPath() + } + return "" +} + +// waitStep says how long to wait before retrying, from a Retry-After header +// (seconds, or an HTTP date). +func waitStep(retryAfter string) string { + retryAfter = strings.TrimSpace(retryAfter) + if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds >= 0 { + return fmt.Sprintf("Wait %ds (Retry-After: %s), then run it again", seconds, retryAfter) + } + if when, err := http.ParseTime(retryAfter); err == nil { + return "Wait until " + when.Local().Format("15:04:05") + " (Retry-After: " + retryAfter + "), then run it again" + } + return "Wait a few seconds, then run it again" +} + +// supportStep is what to do when a server error keeps happening, with the +// request's ID when the response carried one. +func supportStep(headers http.Header) string { + for _, name := range []string{"X-Request-Id", "X-Amzn-Requestid", "X-Amz-Cf-Id", "Cf-Ray"} { + if id := headers.Get(name); id != "" { + return "If it keeps failing, contact Voiceflow support and quote " + name + ": " + id + } + } + return "If it keeps failing, run it with `--debug` and send the output to Voiceflow support" +} + +func parseObject(body string) map[string]interface{} { + var m map[string]interface{} + if json.Unmarshal([]byte(body), &m) != nil { + return nil + } + return m +} + +var htmlTitle = regexp.MustCompile(`(?is)<title>\s*(.*?)\s*`) + +// genericMessages are messages that only restate the status. +var genericMessages = map[string]bool{ + "forbidden resource": true, "internal server error": true, "too many requests": true, + "bad request": true, "unauthorized": true, "not found": true, "service unavailable": true, +} + +// serverMessage is the response's own message, when it says more than the +// status line already does. +func serverMessage(status int, fields map[string]interface{}, body string) string { + var msg string + switch { + case fields != nil: + switch m := fields["message"].(type) { + case string: + msg = m + case []interface{}: + // NestJS validation lists its messages here; fieldErrors shows them. + return "" + } + if msg == "" { + msg, _ = fields["error"].(string) + } + case htmlTitle.MatchString(body): + msg = htmlTitle.FindStringSubmatch(body)[1] + case strings.TrimSpace(body) != "" && !strings.HasPrefix(strings.TrimSpace(body), "<"): + msg = firstLine(body) + } + msg = strings.TrimSpace(msg) + lower := strings.ToLower(msg) + if msg == "" || genericMessages[lower] || strings.EqualFold(msg, http.StatusText(status)) || + lower == strconv.Itoa(status)+" "+strings.ToLower(http.StatusText(status)) { + return "" + } + return msg +} + +// fieldErrors lists the per-field errors a response carries, each with the +// flag that sets the field when cmd has one. +func fieldErrors(cmd *cobra.Command, fields map[string]interface{}) []string { + if fields == nil { + return nil + } + var out []string + if list, ok := fields["details"].([]interface{}); ok { + for _, item := range list { + d, ok := item.(map[string]interface{}) + if !ok { + continue + } + path := fieldPath(d["path"]) + if path == "" { + path = fieldPath(d["field"]) + } + msg, _ := d["message"].(string) + if path == "" && msg == "" { + continue + } + line := strings.TrimPrefix(path+": "+msg, ": ") + if flag := flagForField(cmd, path); flag != "" { + line += " (" + flag + ")" + } + out = append(out, line) + } + } + if list, ok := fields["message"].([]interface{}); ok { + for _, item := range list { + if s, ok := item.(string); ok { + out = append(out, s) + } + } + } + return out +} + +func fieldPath(v interface{}) string { + switch p := v.(type) { + case string: + return p + case []interface{}: + parts := make([]string, 0, len(p)) + for _, seg := range p { + parts = append(parts, fmt.Sprint(seg)) + } + return strings.Join(parts, ".") + } + return "" +} + +// flagForField is the flag that sets a request body field, matched on the +// path's last segment: "data.displayName" is --display-name. +func flagForField(cmd *cobra.Command, path string) string { + if cmd == nil || path == "" { + return "" + } + last := path[strings.LastIndex(path, ".")+1:] + var b strings.Builder + for i, r := range last { + if unicode.IsUpper(r) && i > 0 { + b.WriteByte('-') + } + b.WriteRune(unicode.ToLower(r)) + } + if f := cmd.Flags().Lookup(b.String()); f != nil { + return "--" + f.Name + } + return "" +} + +func detailString(fields map[string]interface{}, key string) string { + if d, ok := fields["details"].(map[string]interface{}); ok { + s, _ := d[key].(string) + return s + } + return "" +} + +func stringList(v interface{}) []string { + list, ok := v.([]interface{}) + if !ok { + return nil + } + var out []string + for _, item := range list { + if s, ok := item.(string); ok && s != "" { + out = append(out, s) + } + } + return out +} + +// lastCause is the innermost reason in a wrapped Go error message: +// "dial tcp: lookup x: no such host" gives "no such host". +func lastCause(msg string) string { + msg = firstLine(msg) + if i := strings.LastIndex(msg, ": "); i >= 0 { + return msg[i+2:] + } + return msg +} + +func firstLine(s string) string { + s = strings.TrimSpace(s) + if i := strings.IndexByte(s, '\n'); i >= 0 { + s = s[:i] + } + if utf8.RuneCountInString(s) > 200 { + s = string([]rune(s)[:199]) + "…" + } + return s +} + +func orDefault(s, def string) string { + if s == "" { + return def + } + return s +} diff --git a/internal/output/explain_test.go b/internal/output/explain_test.go new file mode 100644 index 0000000..dd3d418 --- /dev/null +++ b/internal/output/explain_test.go @@ -0,0 +1,360 @@ +// This file is not generated by Speakeasy. It covers explain.go: every +// failure says what happened, why, and what to do next. + +package output + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "net/url" + "os" + "strings" + "syscall" + "testing" + "time" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/sdk/models/sdkerrors" +) + +// projectGet is 'vf project get' beside 'vf project list', with an ID flag. +func projectGet(t *testing.T) *cobra.Command { + t.Helper() + root := &cobra.Command{Use: "vf"} + group := &cobra.Command{Use: "project"} + get := &cobra.Command{Use: "get", Short: "Get project", RunE: func(*cobra.Command, []string) error { return nil }} + list := &cobra.Command{Use: "list", Short: "List projects", RunE: func(*cobra.Command, []string) error { return nil }} + get.Flags().String("project-id", "", "") + get.Flags().String("display-name", "", "") + get.Flags().String("timeout", "", "") + get.Flags().String("server-url", "", "") + root.AddCommand(group) + group.AddCommand(get, list) + return get +} + +func apiError(status int, body string, headers http.Header) error { + if headers == nil { + headers = http.Header{} + } + res := &http.Response{StatusCode: status, Status: http.StatusText(status), Header: headers} + msg := "API error occurred" + if status < 400 { + msg = "unknown status code returned" + } + return sdkerrors.NewSDKDefaultError(msg, status, body, res) +} + +// withCredential makes DescribeCredential report c for the test. +func withCredential(t *testing.T, c Credential) { + t.Helper() + saved := DescribeCredential + DescribeCredential = func(*cobra.Command) Credential { return c } + t.Cleanup(func() { DescribeCredential = saved }) +} + +func joined(x Explanation) string { + return strings.Join(append(append(append([]string{x.Title, x.Message}, x.Why...), x.Details...), x.Next...), "\n") +} + +func TestEveryStatusSaysWhyAndWhatNext(t *testing.T) { + withCredential(t, Credential{Kind: CredentialKey, Source: "--token"}) + cases := []struct { + status int + body string + headers http.Header + typ string + title, says string + next string + docsOrMessage string + }{ + {400, `{"message":"Validation failed","details":[{"path":["data","displayName"],"message":"Required"}]}`, nil, + "validation_error", "HTTP 400 Bad Request", "displayName: Required (--display-name)", "--dry-run", "Validation failed"}, + {402, `{"message":"The workspace is out of credits","details":{"addCreditsURL":"https://example.com/billing"}}`, nil, + "payment_required", "HTTP 402 Payment Required", "out of credits", "https://example.com/billing", ""}, + {403, `{"message":"Forbidden resource"}`, nil, + "authorization_error", "HTTP 403 Forbidden", "isn't allowed to do this", "vf workspace list", ""}, + {404, `{"message":"Project not found"}`, nil, + "not_found", "HTTP 404 Not Found", "may be wrong", "`vf project list` lists the IDs you can use", "Project not found"}, + {409, `{"message":"A variable with this name already exists"}`, nil, + "api_error", "HTTP 409 Conflict", "already exists", "`vf project list` shows what's there", ""}, + {429, `{"message":"Too many requests"}`, http.Header{"Retry-After": {"17"}}, + "rate_limit_error", "HTTP 429 Too Many Requests", "Too many requests in a short time", "Wait 17s (Retry-After: 17)", ""}, + {500, `{"message":"Internal server error"}`, http.Header{"X-Request-Id": {"req-1"}}, + "server_error", "HTTP 500 Internal Server Error", "on its side", "X-Request-Id: req-1", ""}, + {502, `502 Bad Gateway`, nil, + "server_error", "HTTP 502 Bad Gateway", "unavailable", "--debug", ""}, + {200, `{}`, nil, + "unexpected_response", "unexpected HTTP 200 OK", "not with a status this version of vf expects", "npm install -g @voiceflow/cli", ""}, + } + for _, tc := range cases { + t.Run(fmt.Sprint(tc.status), func(t *testing.T) { + ResetAgentMode() + t.Setenv("FORCE_AGENT_MODE", "1") // error_type is set in agent mode + InitAgentMode(&cobra.Command{Use: "vf"}) + t.Cleanup(ResetAgentMode) + + x := ExplainError(projectGet(t), apiError(tc.status, tc.body, tc.headers)) + all := joined(x) + if x.Type != tc.typ { + t.Errorf("type = %q, want %q", x.Type, tc.typ) + } + if !strings.HasPrefix(x.Title, "Couldn't get project · ") || !strings.Contains(x.Title, tc.title) { + t.Errorf("title = %q, want the action and %q", x.Title, tc.title) + } + if !strings.Contains(all, tc.says) { + t.Errorf("explanation does not say %q:\n%s", tc.says, all) + } + if !strings.Contains(strings.Join(x.Next, "\n"), tc.next) { + t.Errorf("next steps %q do not include %q", x.Next, tc.next) + } + if tc.docsOrMessage != "" && x.Message != tc.docsOrMessage { + t.Errorf("message = %q, want %q", x.Message, tc.docsOrMessage) + } + if x.Docs != "https://www.voiceflow.com/docs/cli/commands/project" { + t.Errorf("docs = %q", x.Docs) + } + }) + } +} + +// A message that only restates the status says nothing, and an HTML error +// page is reduced to its title, never dumped. +func TestServerMessagesThatSayNothingAreDropped(t *testing.T) { + for body, want := range map[string]string{ + `{"statusCode":401,"message":"Unauthorized"}`: "", + `{"statusCode":403,"message":"Forbidden resource"}`: "", + `{"message":"Project not found"}`: "Project not found", + `503 Service Unavailable`: "", + `Down for maintenance`: "Down for maintenance", + `{"message":["name must be a string","type is required"]}`: "", + } { + status := 401 + switch { + case strings.Contains(body, "403"): + status = 403 + case strings.Contains(body, "503"): + status = 503 + } + if got := serverMessage(status, parseObject(body), body); got != want { + t.Errorf("serverMessage(%s) = %q, want %q", body, got, want) + } + } + got := fieldErrors(nil, parseObject(`{"message":["name must be a string","type is required"]}`)) + if len(got) != 2 || got[0] != "name must be a string" { + t.Errorf("NestJS validation messages should become field errors, got %q", got) + } +} + +// A 401 is explained by what was sent: a key that may have expired, or a +// browser session that is current, which makes it a permission problem. The +// second is the case that used to tell a signed-in user to sign in. +func TestUnauthorizedDependsOnTheCredential(t *testing.T) { + cmd := projectGet(t) + err := apiError(401, `{"statusCode":401,"message":"Unauthorized"}`, nil) + + withCredential(t, Credential{Kind: CredentialSession, Expiry: time.Now().Add(time.Hour), Renews: true}) + session := joined(ExplainError(cmd, err)) + for _, want := range []string{"isn't an expired login", "admin role", "`vf auth whoami`"} { + if !strings.Contains(session, want) { + t.Errorf("a refused session should say %q:\n%s", want, session) + } + } + if strings.Contains(session, "Personal keys expire") { + t.Errorf("a session is not a key:\n%s", session) + } + + withCredential(t, Credential{Kind: CredentialKey, Source: "--token"}) + key := joined(ExplainError(cmd, err)) + for _, want := range []string{"the token from --token", "expire", "`vf auth login` signs you in", "Settings → Personal keys"} { + if !strings.Contains(key, want) { + t.Errorf("a refused key should say %q:\n%s", want, key) + } + } + + withCredential(t, Credential{Kind: CredentialKey, Source: "VF_TOKEN", EnvWins: true}) + if env := joined(ExplainError(cmd, err)); !strings.Contains(env, "`unset VF_TOKEN`, then `vf auth login`") { + t.Errorf("VF_TOKEN outranks a session, so signing in alone would not help:\n%s", env) + } + + withCredential(t, Credential{Kind: CredentialSession, Expiry: time.Now().Add(-time.Hour)}) + if ended := joined(ExplainError(cmd, err)); !strings.Contains(ended, "has ended") { + t.Errorf("a session past its expiry with nothing to renew it has ended:\n%s", ended) + } +} + +func TestAServersOwnHintsWin(t *testing.T) { + withCredential(t, Credential{}) + x := ExplainError(projectGet(t), apiError(404, `{"message":"Gone","hints":["Ask Kim"],"docs_url":"https://example.com/x"}`, nil)) + if len(x.Next) != 1 || x.Next[0] != "Ask Kim" || x.Docs != "https://example.com/x" { + t.Errorf("server hints and docs should replace the defaults: next %q, docs %q", x.Next, x.Docs) + } +} + +type noCredential struct{ Body string } + +func (noCredential) Error() string { return "not signed in" } +func (noCredential) NoCredential() bool { return true } + +func TestNotSignedInSaysHowToSignIn(t *testing.T) { + ResetAgentMode() + t.Cleanup(ResetAgentMode) + x := ExplainError(projectGet(t), noCredential{Body: `{"error":"not signed in"}`}) + if !strings.HasSuffix(x.Title, "you're not signed in") || !strings.Contains(strings.Join(x.Next, "\n"), "`vf auth login`") || x.Docs != AuthDocsURL { + t.Errorf("got %+v", x) + } + if !strings.Contains(strings.Join(x.Next, "\n"), "export VF_TOKEN=vfp_") { + t.Errorf("CI needs the token route: %q", x.Next) + } +} + +func TestRequestsThatGotNoAnswer(t *testing.T) { + ResetAgentMode() + t.Cleanup(ResetAgentMode) + cmd := projectGet(t) + wrap := func(cause error) error { + return fmt.Errorf("error sending request: %w", &url.Error{Op: "Get", URL: "https://api.example.com/v1/x", Err: cause}) + } + cases := map[string]struct { + err error + typ, title, why string + }{ + "timeout": {wrap(context.DeadlineExceeded), "timeout", "timed out", "took too long"}, + "dns": {wrap(&net.OpError{Op: "dial", Err: &net.DNSError{Name: "api.example.com", Err: "no such host"}}), + "connection_error", "couldn't reach Voiceflow", "Couldn't look up api.example.com"}, + "refused": {wrap(&net.OpError{Op: "dial", Err: os.NewSyscallError("connect", syscall.ECONNREFUSED)}), + "connection_error", "couldn't reach Voiceflow", "Nothing answered at https://api.example.com"}, + "decode": {errors.New("error unmarshaling json response body: unexpected end of JSON input"), + "unexpected_response", "couldn't read the response", "unexpected end of JSON input"}, + } + for name, tc := range cases { + x := ExplainError(cmd, tc.err) + if x.Type != tc.typ || !strings.HasSuffix(x.Title, tc.title) || !strings.Contains(strings.Join(x.Why, " "), tc.why) || len(x.Next) == 0 { + t.Errorf("%s: got %+v", name, x) + } + } + + // With --server-url set, the URL is the first suspect. + if err := cmd.Flags().Set("server-url", "https://api.example.com"); err != nil { + t.Fatal(err) + } + x := ExplainError(cmd, cases["refused"].err) + if !strings.Contains(x.Next[0], "comes from --server-url") { + t.Errorf("next = %q, want the server URL named", x.Next) + } + if err := cmd.Flags().Set("timeout", "300ms"); err != nil { + t.Fatal(err) + } + if x := ExplainError(cmd, cases["timeout"].err); !strings.Contains(x.Why[0], "within --timeout 300ms") { + t.Errorf("why = %q, want the timeout named", x.Why) + } +} + +// Off a terminal: "Error:" and "-" for the glyphs, and commands in quotes, so +// a CI log stays greppable and pasteable. +func TestRenderOffATerminal(t *testing.T) { + ResetAgentMode() + t.Cleanup(ResetAgentMode) + cmd := projectGet(t) + var stderr bytes.Buffer + cmd.SetErr(&stderr) + Render(cmd, Explanation{ + Title: "Couldn't get project · HTTP 404 Not Found", + Message: "Project not found", + Why: []string{"The ID may be wrong."}, + Next: []string{"`vf project list` lists the IDs you can use"}, + Docs: "https://example.com/project", + }) + want := "Error: Couldn't get project | HTTP 404 Not Found\n" + + " - Project not found\n" + + " The ID may be wrong.\n" + + " Next:\n" + + " 'vf project list' lists the IDs you can use\n" + + " Docs: https://example.com/project\n" + if stderr.String() != want { + t.Errorf("rendered:\n%s\nwant:\n%s", stderr.String(), want) + } +} + +// In agent mode a report is one JSON object and nothing else, with the +// commands quoted and the angle brackets left as written. +func TestReportInAgentModeIsOneJSONObject(t *testing.T) { + ResetAgentMode() + t.Setenv("FORCE_AGENT_MODE", "1") + InitAgentMode(&cobra.Command{Use: "vf"}) + t.Cleanup(ResetAgentMode) + + cmd := projectGet(t) + var stderr bytes.Buffer + cmd.SetErr(&stderr) + cause := errors.New("missing required flag: --project-id") + got := Report(cmd, Explanation{Type: "missing_flag", Title: "vf project get needs --project-id", Why: []string{"Agent mode doesn't ask."}, Next: []string{"Pass it: `vf project get --project-id `"}}, cause) + + var m map[string]interface{} + if err := json.Unmarshal(stderr.Bytes(), &m); err != nil { + t.Fatalf("stderr is not one JSON object: %v\n%s", err, stderr.String()) + } + if m["error_type"] != "missing_flag" || m["explanation"] != "Agent mode doesn't ask." { + t.Errorf("envelope = %v", m) + } + if hints, _ := m["hints"].([]interface{}); len(hints) != 1 || hints[0] != "Pass it: 'vf project get --project-id '" { + t.Errorf("hints = %v", m["hints"]) + } + if strings.Contains(stderr.String(), `\u003c`) { + t.Errorf("angle brackets were escaped:\n%s", stderr.String()) + } + if got == nil || got.Error() != "" || !errors.Is(got, cause) { + t.Errorf("Report should return the error marked as reported, got %#v", got) + } +} + +func TestEnvelopeKeepsWhatTheResponseSays(t *testing.T) { + m := map[string]interface{}{"message": "Project not found", "hints": []string{"server hint"}} + Envelope(m, Explanation{Title: "t", Why: []string{"why"}, Next: []string{"`vf x`"}, Docs: "d"}) + if m["message"] != "Project not found" || fmt.Sprint(m["hints"]) != "[server hint]" || m["explanation"] != "why" || m["docs_url"] != "d" { + t.Errorf("envelope = %v", m) + } +} + +func TestWaitStepReadsRetryAfter(t *testing.T) { + if got := waitStep("17"); got != "Wait 17s (Retry-After: 17), then run it again" { + t.Errorf("seconds: %q", got) + } + if got := waitStep("Wed, 21 Oct 2026 07:28:00 GMT"); !strings.HasPrefix(got, "Wait until ") { + t.Errorf("date: %q", got) + } + if got := waitStep(""); got != "Wait a few seconds, then run it again" { + t.Errorf("none: %q", got) + } +} + +func TestActionReadsTheCommandsShortHelp(t *testing.T) { + for short, want := range map[string]string{ + "List workspaces": "Couldn't list workspaces", + "Get MCP server.": "Couldn't get MCP server", + "MCP server sync": "Couldn't MCP server sync", + "": "Couldn't run vf", + strings.Repeat("x", 70): "Couldn't run vf", + } { + if got := action(&cobra.Command{Use: "vf", Short: short}); got != want { + t.Errorf("action(%q) = %q, want %q", short, got, want) + } + } +} + +func TestShortReasonIsOneLine(t *testing.T) { + withCredential(t, Credential{}) + cmd := projectGet(t) + if got := ShortReason(cmd, apiError(404, `{"message":"Project not found"}`, nil)); got != "HTTP 404 Not Found — Project not found" { + t.Errorf("api: %q", got) + } + if got := ShortReason(cmd, errors.New("boom\nmore")); got != "boom" { + t.Errorf("plain: %q", got) + } +} diff --git a/internal/output/output.go b/internal/output/output.go index e60acde..1bed901 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -400,28 +400,14 @@ func Error(cmd *cobra.Command, err error) error { } } - // Surface the error so the user can see what went wrong. - if body != "" && statusCode != 0 { - fmt.Fprintf(cmd.ErrOrStderr(), "\nAPI Error (HTTP %d):%s\n%s\n", statusCode, sdkErrorDetail(err), formatErrorBody(body)) - } else if body != "" { - fmt.Fprintf(cmd.ErrOrStderr(), "\nAPI Error:\n%s\n", formatErrorBody(body)) - } else { - // Connection errors, auth failures, and other non-API errors - // have no body or status code — print the error message directly. - fmt.Fprintf(cmd.ErrOrStderr(), "\nError: %s\n", err.Error()) - } - - // Auth hint for 401/403 - if statusCode == 401 || statusCode == 403 { - fmt.Fprintf(cmd.ErrOrStderr(), "\nHint: run '%s auth login' to sign in, '%s auth signup' to create an account, or '%s configure' to set a token.\n", cliName, cliName, cliName) - } - - return AlreadyReported(err) // see reported.go + Render(cmd, explain(cmd, err, statusCode, body)) // explain.go: what happened, why, and what to do next + return AlreadyReported(err) // see reported.go } out := cmd.ErrOrStderr() colorFlag, _ := flagutil.GetStringFlag(cmd, "color") colorize := ShouldColorize(colorFlag) + explained := explain(cmd, err, statusCode, body) // explain.go: added to the JSON as explanation, hints and docs_url // Try to extract the raw body from error types via reflection. // Works with APIError and typed SDK errors that have a Body field. @@ -438,10 +424,9 @@ func Error(cmd *cobra.Command, err error) error { m["status_code"] = statusCode } } + Envelope(m, explained) // explain.go if IsAgentMode() { enrichAgentError(m, err, statusCode) - } else if statusCode == 401 || statusCode == 403 { - m["_hint"] = fmt.Sprintf("run '%s auth login' to sign in, '%s auth signup' to create an account, or '%s configure' to set a token", cliName, cliName, cliName) } if enriched, mergeErr := json.MarshalIndent(m, "", " "); mergeErr == nil { jsonData = enriched @@ -455,10 +440,9 @@ func Error(cmd *cobra.Command, err error) error { if statusCode != 0 { envelope["status_code"] = statusCode } + Envelope(envelope, explained) // explain.go if IsAgentMode() { enrichAgentError(envelope, err, statusCode) - } else if statusCode == 401 || statusCode == 403 { - envelope["_hint"] = fmt.Sprintf("run '%s auth login' to sign in, '%s auth signup' to create an account, or '%s configure' to set a token", cliName, cliName, cliName) } if enriched, mergeErr := json.MarshalIndent(envelope, "", " "); mergeErr == nil { jsonData = enriched @@ -468,7 +452,7 @@ func Error(cmd *cobra.Command, err error) error { } else { // Fallback: wrap error info in a consistent JSON envelope envelope := map[string]interface{}{ - "error": err.Error(), + "error": explained.Title, // explain.go: the SDK's message repeats the whole body } if statusCode != 0 { envelope["status_code"] = statusCode @@ -476,10 +460,9 @@ func Error(cmd *cobra.Command, err error) error { if body != "" { envelope["body"] = body } + Envelope(envelope, explained) // explain.go if IsAgentMode() { enrichAgentError(envelope, err, statusCode) - } else if statusCode == 401 || statusCode == 403 { - envelope["_hint"] = fmt.Sprintf("run '%s auth login' to sign in, '%s auth signup' to create an account, or '%s configure' to set a token", cliName, cliName, cliName) } var marshalErr error jsonData, marshalErr = json.MarshalIndent(envelope, "", " ") diff --git a/internal/output/reported.go b/internal/output/reported.go index 179af20..2d69a53 100644 --- a/internal/output/reported.go +++ b/internal/output/reported.go @@ -30,29 +30,13 @@ // The one part of it the body does not show is the SDK's message, and only // when it says more than the generic "API error occurred": for a status the // operation never documents, such as a 200 where only 201 means success, it is -// "unknown status code returned", which is why a 200 is an error at all. Error -// puts that message on its status line (sdkErrorDetail below), so everything -// the trailing line carried is already printed, and human mode now marks its +// "unknown status code returned", which is why a 200 is an error at all. +// explain.go says that in words ("unexpected HTTP 200"), so everything the +// trailing line carried is already printed, and human mode now marks its // errors as reported too. package output -import ( - "errors" - - "github.com/voiceflow/cli/internal/sdk/models/sdkerrors" -) - -// sdkErrorDetail is the SDK's message for Error's status line, with a leading -// space, or "" when it is the generic one that the status already says. -func sdkErrorDetail(err error) string { - var sdkErr *sdkerrors.SDKDefaultError - if !errors.As(err, &sdkErr) || sdkErr.Message == "" || sdkErr.Message == "API error occurred" { - return "" - } - return " " + sdkErr.Message -} - // alreadyReported marks an error whose message has been written to stderr by // the code that produced it. // diff --git a/internal/output/reported_test.go b/internal/output/reported_test.go index 44f97a2..ce4af46 100644 --- a/internal/output/reported_test.go +++ b/internal/output/reported_test.go @@ -26,8 +26,8 @@ func TestHumanModeReportsAnAPIErrorOnce(t *testing.T) { if n := strings.Count(printed, "Project not found"); n != 1 { t.Errorf("printed the body %d times, want once:\n%s", n, printed) } - if !strings.Contains(printed, "API Error (HTTP 404):\n") { - t.Errorf("printed %q, want the status line with nothing after it", printed) + if !strings.HasPrefix(printed, "Error: Couldn't run vf | HTTP 404 Not Found\n") { + t.Errorf("printed %q, want the failure's status line first", printed) } if got == nil || got.Error() != "" { t.Fatalf("Error returned %v, want an error marked as already reported", got) @@ -39,7 +39,7 @@ func TestHumanModeReportsAnAPIErrorOnce(t *testing.T) { } // The suppressed line was the only place that said why a status the operation -// never documents is an error. The status line keeps that message. +// never documents is an error. The explanation says it in words. func TestHumanModeNamesAnUndocumentedStatus(t *testing.T) { ResetAgentMode() t.Cleanup(ResetAgentMode) @@ -49,8 +49,8 @@ func TestHumanModeNamesAnUndocumentedStatus(t *testing.T) { got, printed := reportError(t, apiErr, false) - if !strings.Contains(printed, "API Error (HTTP 200): unknown status code returned\n") { - t.Errorf("printed %q, want the SDK's message on the status line", printed) + if !strings.Contains(printed, "unexpected HTTP 200 OK\n") || !strings.Contains(printed, "not with a status this version of vf expects") { + t.Errorf("printed %q, want it to say the status was unexpected, and why that is an error", printed) } if got == nil || got.Error() != "" { t.Fatalf("Error returned %v, want an error marked as already reported", got) @@ -66,8 +66,8 @@ func TestHumanModeReportsAConnectionErrorOnce(t *testing.T) { got, printed := reportError(t, connErr, false) - if want := "\nError: error sending request: dial tcp 127.0.0.1:9: connect: connection refused\n"; printed != want { - t.Errorf("printed %q, want %q", printed, want) + if !strings.HasPrefix(printed, "Error: Couldn't run vf | couldn't reach Voiceflow\n") || strings.Count(printed, "connection refused") != 1 { + t.Errorf("printed %q, want the failure once, with its cause", printed) } if got == nil || got.Error() != "" { t.Fatalf("Error returned %v, want an error marked as already reported", got) diff --git a/internal/sdk/sdkinternal/hooks/registration.go b/internal/sdk/sdkinternal/hooks/registration.go index c4c0335..9145aba 100644 --- a/internal/sdk/sdkinternal/hooks/registration.go +++ b/internal/sdk/sdkinternal/hooks/registration.go @@ -5,7 +5,5 @@ package hooks func initHooks(h *Hooks) { h.registerBeforeRequestHook(&clientTypeHook{}) - teach := &teachHook{} - h.registerBeforeRequestHook(teach) - h.registerAfterErrorHook(teach) + h.registerBeforeRequestHook(&teachHook{}) } diff --git a/internal/sdk/sdkinternal/hooks/teach.go b/internal/sdk/sdkinternal/hooks/teach.go index 374fa3e..308e804 100644 --- a/internal/sdk/sdkinternal/hooks/teach.go +++ b/internal/sdk/sdkinternal/hooks/teach.go @@ -1,25 +1,27 @@ -// This file is not generated by Speakeasy — it implements "errors that teach": -// every failure the CLI surfaces should name its own fix, because for both -// humans and AI coding agents the error text is the documentation they read. +// This file is not generated by Speakeasy — it implements the request-side +// half of "errors that teach": every failure the CLI surfaces should name its +// own fix, because for both humans and AI coding agents the error text is the +// documentation they read. // -// Three behaviors, all request-lifecycle hooks (see registration.go): +// Two behaviors, both before the request is sent (see registration.go): // -// - No credential configured -> fail before the network call with setup -// guidance (the one moment that genuinely needs a human: creating a token). +// - No credential configured -> fail before the network call, with an +// error internal/output recognizes and explains: sign in with +// 'vf auth login', or set VF_TOKEN in CI. // - Malformed credential -> warn once on stderr (legacy Dialog Manager // keys, stray whitespace) but still send the request. -// - 4XX/5XX responses -> inject actionable "hints" and a "docs_url" -// into the JSON error body. internal/output preserves body-provided keys -// in both agent-mode envelopes and pretty output, and server-provided -// hints always win — injection only fills keys the body does not have. +// +// What a failed response means, and what to do about it, is decided in +// internal/output/explain.go, which knows what this hook cannot: the command +// that failed, its flags, and whether the credential is a key or a browser +// session. This hook used to add hints to error bodies too, and the two sets +// disagreed: a 403 told a signed-in user to sign in. package hooks import ( - "bytes" "encoding/json" "fmt" - "io" "net/http" "os" "strconv" @@ -28,9 +30,8 @@ import ( ) const ( - authDocsURL = "https://www.voiceflow.com/docs/api-reference/authentication" - docsCommandBase = "https://www.voiceflow.com/docs/cli/commands" - tokenEnvVar = "VF_TOKEN" + authDocsURL = "https://www.voiceflow.com/docs/api-reference/authentication" + tokenEnvVar = "VF_TOKEN" ) // Once per process rather than per hook: a command that makes many requests @@ -40,21 +41,23 @@ var tokenWarnOnce sync.Once type teachHook struct{} var _ beforeRequestHook = (*teachHook)(nil) -var _ afterErrorHook = (*teachHook)(nil) -// authSetupError carries a structured JSON body so internal/output renders it -// like an API error envelope (Body is extracted via reflection there). +// authSetupError is the request that was not sent because no credential is +// configured. Its Body makes internal/output treat it as an error response, +// and NoCredential is how output.ExplainError recognizes it without importing +// this package. type authSetupError struct { Body string message string } -func (e *authSetupError) Error() string { return e.message } +func (e *authSetupError) Error() string { return e.message } +func (e *authSetupError) NoCredential() bool { return true } // BeforeRequest fails fast when no access token is configured, and warns once // when the configured token is recognizably malformed. Runs after the SDK // populates security, so the Authorization header reflects every source -// (--token flag, VF_TOKEN env, keyring, config file). +// (--token flag, VF_TOKEN env, browser session, keyring, config file). func (h *teachHook) BeforeRequest(_ BeforeRequestContext, req *http.Request) (*http.Request, error) { authorization := req.Header.Get("Authorization") // With no token configured the SDK still writes "Authorization: Bearer " @@ -68,19 +71,13 @@ func (h *teachHook) BeforeRequest(_ BeforeRequestContext, req *http.Request) (*h return req, nil } body, _ := json.Marshal(map[string]interface{}{ - "error": "no access token configured", + "error": "not signed in", "error_type": "authentication_error", - "message": "No access token configured — the request was not sent.", - "hints": []string{ - "Create a personal access token in Voiceflow under Settings → Access tokens (tokens start with vfp_)", - fmt.Sprintf("Then run: export %s=vfp_... (every command also accepts --token)", tokenEnvVar), - "Verify what is configured, without a network call: vf whoami", - }, - "docs_url": authDocsURL, + "message": "No credential is configured, so the request was not sent.", }) return req, &authSetupError{ Body: string(body), - message: fmt.Sprintf("no access token configured — create one under Settings → Access tokens, then export %s=vfp_... (%s)", tokenEnvVar, authDocsURL), + message: fmt.Sprintf("not signed in: run 'vf auth login', or set %s to a personal key (%s)", tokenEnvVar, authDocsURL), } } @@ -88,71 +85,17 @@ func (h *teachHook) BeforeRequest(_ BeforeRequestContext, req *http.Request) (*h switch { case strings.HasPrefix(credential, "VF.DM."): tokenWarnOnce.Do(func() { - fmt.Fprintf(os.Stderr, "Warning: the configured token looks like a legacy Dialog Manager API key (VF.DM....). The CLI needs a personal access token (vfp_...) — create one under Settings → Access tokens: %s\n", authDocsURL) + fmt.Fprintf(os.Stderr, "Warning: the token looks like a legacy Dialog Manager API key (VF.DM....), not a personal key, so Voiceflow will likely reject it. Sign in with 'vf auth login', or use a personal key (vfp_...) from Settings → Personal keys: %s\n", authDocsURL) }) case strings.TrimSpace(token) != token: tokenWarnOnce.Do(func() { - fmt.Fprintln(os.Stderr, "Warning: the configured token has leading or trailing whitespace — the API will likely reject it.") + fmt.Fprintln(os.Stderr, "Warning: the token has a space or newline at its start or end, so Voiceflow will likely reject it. Copy it again without the whitespace.") }) } return req, nil } -// AfterError injects hints and a docs_url into JSON error bodies. Keys already -// present in the body (for example server-provided hints) are never replaced. -func (h *teachHook) AfterError(hookCtx AfterErrorContext, res *http.Response, err error) (*http.Response, error) { - if res == nil || res.Body == nil || res.StatusCode < 400 { - return res, err - } - - raw, readErr := io.ReadAll(res.Body) - res.Body.Close() - restore := func(body []byte) { - res.Body = io.NopCloser(bytes.NewReader(body)) - res.ContentLength = int64(len(body)) - res.Header.Set("Content-Length", strconv.Itoa(len(body))) - } - if readErr != nil { - // io.ReadAll can return bytes alongside an error. Restore whatever - // arrived rather than blanking the body — a truncated error message - // still tells the user more than an empty one. - restore(raw) - return res, err - } - - var parsed map[string]interface{} - if json.Unmarshal(raw, &parsed) != nil || parsed == nil { - restore(raw) - return res, err - } - - changed := false - if _, has := parsed["hints"]; !has { - if hints := hintsForStatus(res.StatusCode, res.Header, hookCtx.OperationID); len(hints) > 0 { - parsed["hints"] = hints - changed = true - } - } - if _, has := parsed["docs_url"]; !has { - if docsURL := docsURLForOperation(hookCtx.OperationID); docsURL != "" { - parsed["docs_url"] = docsURL - changed = true - } - } - - if !changed { - restore(raw) - return res, err - } - if enriched, marshalErr := json.Marshal(parsed); marshalErr == nil { - restore(enriched) - } else { - restore(raw) - } - return res, err -} - // dryRunRequested reports whether --dry-run is on the command line. The hook // has no cobra command reference, and --dry-run is flag-only (no env or config // source), so the process arguments are its single source of truth. @@ -170,125 +113,3 @@ func dryRunRequested() bool { } return false } - -// hintsForStatus returns fix-naming hints for a failed response. Empty for -// statuses where the generic enrichment in internal/output already says -// everything useful (5XX). -func hintsForStatus(statusCode int, headers http.Header, operationID string) []string { - switch statusCode { - case 401: - return []string{ - "Access tokens expire (default 30 days) — this one may have lapsed or been revoked", - fmt.Sprintf("Create a new token in Voiceflow under Settings → Access tokens, then run: export %s=vfp_...", tokenEnvVar), - "See which credential source is being used: vf whoami", - } - case 403: - hints := []string{ - "Your token carries your own account's access — this resource belongs to a workspace or organization your account cannot act on", - } - // Always name a command that exists: workspace list is the widest thing - // any account can run, and it is what reveals the reachable scope. - hints = append(hints, "List what your account can reach: vf workspace list") - return hints - case 404: - hints := []string{"Verify the resource identifier — it may be from another workspace or environment"} - if group := commandGroupForOperation(operationID); hasListCommand(group) { - hints = append(hints, fmt.Sprintf("List available resources: vf %s list", group)) - } - return hints - case 429: - if retryAfter := headers.Get("Retry-After"); retryAfter != "" { - // Retry-After may be delta-seconds or an HTTP-date; echo it verbatim. - return []string{fmt.Sprintf("Rate limited — Retry-After: %s", retryAfter)} - } - return []string{"Rate limited — retry after a short delay"} - case 400, 422: - return []string{ - "Preview the exact request without sending it: add --dry-run", - "Field paths in details[] refer to the API request body — the matching CLI flag usually shares the last path segment (run the command with --help)", - } - default: - return nil - } -} - -// docsGroupPages is the set of command-group pages that exist under -// https://www.voiceflow.com/docs/cli/commands/ (verified against the docs -// site's index). Operations whose group is not listed fall back to overview. -var docsGroupPages = map[string]bool{ - "agent": true, "analytics": true, "api-tool": true, "conversation": true, - "document": true, "environment": true, "evaluation": true, "function": true, - "knowledge-base": true, "mcp-server": true, "mcp-tool": true, "playbook": true, - "project": true, "tool": true, "transcript": true, "variable": true, "workspace": true, -} - -// listCommandGroups is the set of top-level command groups that actually have -// a `list` subcommand — hints must only name commands that exist. -var listCommandGroups = map[string]bool{ - "api-tool": true, "document": true, "environment": true, "evaluation": true, - "function": true, "mcp-server": true, "mcp-tool": true, "playbook": true, - "project": true, "test": true, "tool": true, "variable": true, "workspace": true, -} - -func hasListCommand(group string) bool { return listCommandGroups[group] } - -// commandGroupForOperation derives the CLI command group from an operation ID -// like "StableAPIToolController_list" -> "api-tool". Sub-resource controllers -// (e.g. StableFunctionPathController) resolve to their parent group by -// trimming trailing segments until a known group matches. -func commandGroupForOperation(operationID string) string { - name, _, found := strings.Cut(operationID, "Controller") - if !found { - return "" - } - name = strings.TrimPrefix(name, "Stable") - kebab := camelToKebab(name) - - for kebab != "" { - if docsGroupPages[kebab] || listCommandGroups[kebab] { - return kebab - } - lastDash := strings.LastIndex(kebab, "-") - if lastDash < 0 { - return "" - } - kebab = kebab[:lastDash] - } - return "" -} - -// docsURLForOperation maps an operation to its command group's documentation -// page, falling back to the commands overview. -func docsURLForOperation(operationID string) string { - if group := commandGroupForOperation(operationID); group != "" && docsGroupPages[group] { - return docsCommandBase + "/" + group - } - return docsCommandBase + "/overview" -} - -// camelToKebab converts CamelCase with initialisms to kebab-case: -// "APITool" -> "api-tool", "MCPServer" -> "mcp-server", "Workspace" -> "workspace". -func camelToKebab(name string) string { - var out strings.Builder - runes := []rune(name) - for i, r := range runes { - if i > 0 && isUpper(r) { - prevLower := !isUpper(runes[i-1]) - nextLower := i+1 < len(runes) && !isUpper(runes[i+1]) - if prevLower || nextLower { - out.WriteByte('-') - } - } - out.WriteRune(toLower(r)) - } - return out.String() -} - -func isUpper(r rune) bool { return r >= 'A' && r <= 'Z' } - -func toLower(r rune) rune { - if isUpper(r) { - return r + ('a' - 'A') - } - return r -} diff --git a/test/agent-mode-flag.test.ts b/test/agent-mode-flag.test.ts index 02f93d5..3e72c5e 100644 --- a/test/agent-mode-flag.test.ts +++ b/test/agent-mode-flag.test.ts @@ -68,7 +68,7 @@ describe('--agent-mode', () => { expect(result.exitCode).toBe(1); expect(isEnvelope(result.stderr), result.stderr).toBe(false); - expect(result.stderr).toContain('API Error'); + expect(result.stderr).toContain("you're not signed in"); }); it('turns agent mode on outside an agent', async () => { diff --git a/test/dry-run.test.ts b/test/dry-run.test.ts index 939b28a..697ddf6 100644 --- a/test/dry-run.test.ts +++ b/test/dry-run.test.ts @@ -101,7 +101,7 @@ describe('--dry-run', () => { const result = await vf([...createProject, '--server-url', serverURL]); expect(result.exitCode, result.stderr).toBe(1); - expect(result.stderr).toContain('unknown status code'); + expect(result.stderr).toContain('unexpected HTTP 200'); }); // The rule must not hide real failures: a request that cannot be built fails diff --git a/test/errors-teach.test.ts b/test/errors-teach.test.ts index cd6dd64..cea51de 100644 --- a/test/errors-teach.test.ts +++ b/test/errors-teach.test.ts @@ -1,6 +1,8 @@ -// Hermetic tests for the "errors that teach" hooks (internal/sdk/sdkinternal/ -// hooks/teach.go): no-token preflight, malformed-token warnings, and 4XX hint -// + docs_url injection. Uses a local mock API — no live credentials. +// Hermetic tests for "errors that teach": the no-token preflight and +// malformed-token warnings (internal/sdk/sdkinternal/hooks/teach.go), and the +// explanation, hints and docs_url every failure carries +// (internal/output/explain.go). Uses a local mock API — no live +// credentials. // // Requires the CLI binary at the repo root: go build -o vf ./cmd/vf @@ -48,6 +50,7 @@ beforeAll(async () => { }; if (req.url?.includes('/project/')) return reply(404, { statusCode: 404, message: 'Project not found' }); if (req.url?.includes('/workspace')) return reply(429, { statusCode: 429, message: 'Too many requests' }, { 'Retry-After': '17' }); + if (req.url?.includes('/environment')) return reply(403, { statusCode: 403, message: 'Forbidden resource' }); return reply(401, { statusCode: 401, message: 'Unauthorized' }); }); await new Promise((resolve) => mock.listen(0, '127.0.0.1', resolve)); @@ -67,6 +70,7 @@ describe('no-token preflight', () => { expect(envelope.error_type).toBe('authentication_error'); expect(envelope.message).toContain('request was not sent'); expect(envelope.docs_url).toBe('https://www.voiceflow.com/docs/api-reference/authentication'); + expect(JSON.stringify(envelope.hints)).toContain("Run 'vf auth login' in the background"); expect(JSON.stringify(envelope.hints)).toContain('export VF_TOKEN=vfp_'); }); @@ -153,9 +157,20 @@ describe('error hint injection', () => { const result = await $vf(['playbook', 'list', '--project-id', 'p', '--environment-alias', 'main', '--token', 'vfp_expired', '--server-url', mockURL]); const envelope = parseEnvelope(result.stderr); expect(envelope.error_type).toBe('authentication_error'); - expect(JSON.stringify(envelope.hints)).toContain('expire'); + expect(envelope.explanation).toContain('the token from --token'); + expect(envelope.explanation).toContain('expire'); + expect(JSON.stringify(envelope.hints)).toContain("'vf auth login' signs you in"); expect(JSON.stringify(envelope.hints)).toContain('export VF_TOKEN=vfp_'); }); + + it('explains a 403 as access, not sign-in', async () => { + const result = await $vf(['environment', 'list', '--project-id', 'p', '--token', 'vfp_x', '--server-url', mockURL]); + const envelope = parseEnvelope(result.stderr); + expect(envelope.error_type).toBe('authorization_error'); + expect(envelope.explanation).toContain("isn't allowed to do this"); + expect(JSON.stringify(envelope.hints)).toContain("'vf workspace list' shows the workspaces you can reach"); + expect(JSON.stringify(envelope)).not.toContain('auth login'); // the old hint told a signed-in user to sign in + }); }); describe('agent-mode errors are printed exactly once', () => { @@ -201,16 +216,19 @@ describe('human-mode errors print once', () => { // the "Error: …" line word for word). See internal/output/reported.go. const human = (args: string[]) => $vf([...args, '--agent-mode=false', '--token', 'vfp_x']); - it('prints an API error body once', async () => { + it('prints an API error once, with why and what next', async () => { const result = await human(['project', 'get', '--project-id', 'missing', '--server-url', mockURL]); expect(result.exitCode).toBe(1); - expect(result.stderr).toContain('API Error (HTTP 404)'); + expect(result.stderr).toContain("Error: Couldn't get project | HTTP 404 Not Found"); expect(result.stderr.split('Project not found').length - 1, result.stderr).toBe(1); + expect(result.stderr).toContain("'vf project list' lists the IDs you can use"); + expect(result.stderr).not.toContain('{'); // no raw JSON body for a person }); it('prints a connection error once', async () => { const result = await human(['project', 'get', '--project-id', 'p', '--server-url', 'http://127.0.0.1:1', '--timeout', '5s']); expect(result.exitCode).toBe(1); - expect(result.stderr.split('error sending request').length - 1, result.stderr).toBe(1); + expect(result.stderr).toContain("couldn't reach Voiceflow"); + expect(result.stderr.split('connection refused').length - 1, result.stderr).toBe(1); }); }); From 413553b913d63aa6e71678c76d93714d82c79d05 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:24:57 -0500 Subject: [PATCH 05/30] fix(output): check --output-format and --jq before sending the request MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A --jq that did not parse was found only when Result applied it, after the request had run: 'vf variable create … --jq ".["' created the variable, then failed, and running it again made a second one. An unknown --output-format was never reported; Result fell through to its YAML-like default and exited 0. PrepareCallOpts, which every operation calls before it sends, now rejects both. The filter is compiled as well as parsed, which also catches a function that does not exist. --- internal/output/output.go | 3 ++ internal/output/validate.go | 59 ++++++++++++++++++++++++++++++++ internal/output/validate_test.go | 44 ++++++++++++++++++++++++ 3 files changed, 106 insertions(+) create mode 100644 internal/output/validate.go create mode 100644 internal/output/validate_test.go diff --git a/internal/output/output.go b/internal/output/output.go index 1bed901..3e8d385 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -97,6 +97,9 @@ func WantsRawJSON(cmd *cobra.Command) bool { // Parses --header flags into operations.WithSetHeaders options. // Server resolution and skip-deserialization are handled per-operation. func PrepareCallOpts(cmd *cobra.Command) ([]operations.Option, error) { + if err := ValidateOutputFlags(cmd); err != nil { // validate.go: before the request, not after + return nil, err + } var opts []operations.Option if hdrs, _ := flagutil.GetStringArrayFlag(cmd, "header"); len(hdrs) > 0 { headerMap := make(map[string]string, len(hdrs)) diff --git a/internal/output/validate.go b/internal/output/validate.go new file mode 100644 index 0000000..067ea51 --- /dev/null +++ b/internal/output/validate.go @@ -0,0 +1,59 @@ +// This file is not generated by Speakeasy. It checks the output flags before +// a request is sent, rather than after the response arrives. +// +// Both used to fail late. A typo in --jq was found only when Result applied +// it, after the request had run, so 'vf variable create … --jq ".["' created +// the variable and then reported an error, and running it again made a +// second one. An unknown --output-format was never reported at all: Result +// fell through to its YAML-like default and exited 0. + +package output + +import ( + "fmt" + "strings" + + "github.com/itchyny/gojq" + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/config" + "github.com/voiceflow/cli/internal/flagutil" +) + +// OutputFormats are the values --output-format takes. +var OutputFormats = []string{"pretty", "json", "yaml", "table", "toon"} + +// ValidateOutputFlags rejects an output format or jq filter that cannot be +// used. PrepareCallOpts calls it, so every operation checks before it sends. +func ValidateOutputFlags(cmd *cobra.Command) error { + format, source := "", "--output-format" + if cmd.Flags().Changed("output-format") { + format, _ = flagutil.GetStringFlag(cmd, "output-format") + } else if format = config.GetString("output-format"); format != "" { + source = "the output-format setting (VF_OUTPUT_FORMAT or " + config.GetConfigPath() + ")" + } + if format != "" && !contains(OutputFormats, format) { + return fmt.Errorf("invalid value for %s: %q; valid options: %s", source, format, strings.Join(OutputFormats, ", ")) + } + if expr, _ := flagutil.GetStringFlag(cmd, "jq"); expr != "" { + // Compiling as well as parsing catches a function that does not + // exist, which parses fine. + query, err := gojq.Parse(expr) + if err == nil { + _, err = gojq.Compile(query) + } + if err != nil { + return fmt.Errorf("invalid --jq expression %q: %w", expr, err) + } + } + return nil +} + +func contains(list []string, s string) bool { + for _, v := range list { + if v == s { + return true + } + } + return false +} diff --git a/internal/output/validate_test.go b/internal/output/validate_test.go new file mode 100644 index 0000000..9251b6f --- /dev/null +++ b/internal/output/validate_test.go @@ -0,0 +1,44 @@ +// This file is not generated by Speakeasy. It covers validate.go. + +package output + +import ( + "fmt" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +func outputFlagsCommand(t *testing.T, flags map[string]string) *cobra.Command { + t.Helper() + cmd := &cobra.Command{Use: "list"} + cmd.Flags().String("output-format", "pretty", "") + cmd.Flags().String("jq", "", "") + for name, value := range flags { + if err := cmd.Flags().Set(name, value); err != nil { + t.Fatal(err) + } + } + return cmd +} + +func TestOutputFlagsAreCheckedBeforeTheRequest(t *testing.T) { + for _, ok := range []map[string]string{ + {}, {"output-format": "json"}, {"output-format": "toon"}, {"jq": ".workspaces[].id"}, + } { + if err := ValidateOutputFlags(outputFlagsCommand(t, ok)); err != nil { + t.Errorf("%v: %v", ok, err) + } + } + err := ValidateOutputFlags(outputFlagsCommand(t, map[string]string{"output-format": "nope"})) + if err == nil || !strings.HasPrefix(err.Error(), `invalid value for --output-format: "nope"; valid options: pretty, json, yaml, table, toon`) { + t.Errorf("an unknown format should be refused, got %v", err) + } + for _, jq := range []string{".[", ".counts | no_such_function"} { + err = ValidateOutputFlags(outputFlagsCommand(t, map[string]string{"jq": jq})) + if err == nil || !strings.HasPrefix(err.Error(), fmt.Sprintf("invalid --jq expression %q", jq)) { + t.Errorf("%s: a filter that cannot run should be refused, got %v", jq, err) + } + } +} From 8a97d7cbe1435954ca03267a909597bce16f6117 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:25:10 -0500 Subject: [PATCH 06/30] feat(cli): explain usage errors with a cause and next steps Everything that fails around a request rather than in its response reached main.go as a bare string, the same in both modes: "unknown flag: --nosuch", with no command named and no way on; "missing required flag: --project-id", with no word on where to find one. Agents got prose where they expect an envelope. And a word a command group does not know, 'vf workspace lsit', printed the group's help and exited 0. internal/cli/errors.go explains them the way output.Error explains API errors, drawn for a person or written as JSON in agent mode: - Unknown commands and flags suggest the nearest ("Did you mean 'vf workspace list'?", "Did you mean '--name'?") and name --help. - A group given a word it does not know fails, with a suggestion. - A missing flag says why vf did not ask (agent mode, --no-interactive, not a terminal), names the list command that shows its values ('vf project list'; organizations are on 'vf workspace list'), and says a terminal would have offered a picker. - A flag with no value or a value it cannot parse, a bad --timeout, --jq, --output-format or -H, a broken config file, configure or login with --no-interactive and nothing to save, --email without signup: each names its fix. - An ended or unrenewable browser session says so and says to sign in again; oauth exports ErrSessionEnded and ErrRenewSession for it. - A canceled form reports "Canceled", as the home prompt already did. - The configure and login agent hints name VF_TOKEN and 'vf auth login' rather than "environment variables (prefix: VF_)". The home prompt reports a line's error the same way, and a picker whose list fails says why in one line (output.ShortReason). --- internal/cli/auth.go | 2 +- internal/cli/configure.go | 6 +- internal/cli/errors.go | 396 ++++++++++++++++++++++++++++++++ internal/cli/errors_test.go | 206 +++++++++++++++++ internal/cli/home.go | 8 +- internal/cli/root.go | 5 +- internal/interactive/pickers.go | 4 + internal/oauth/oauth.go | 15 +- test/errors-teach.test.ts | 25 +- 9 files changed, 653 insertions(+), 14 deletions(-) create mode 100644 internal/cli/errors.go create mode 100644 internal/cli/errors_test.go diff --git a/internal/cli/auth.go b/internal/cli/auth.go index 7c5ceed..11d753a 100644 --- a/internal/cli/auth.go +++ b/internal/cli/auth.go @@ -117,7 +117,7 @@ func runAuthLoginCmd(cmd *cobra.Command, args []string) error { []string{ fmt.Sprintf("Run '%s auth login' without --manual/--no-interactive to get a browser sign-in URL to give the user", "vf"), fmt.Sprintf("Pass the token directly: '%s auth login --token '", "vf"), - fmt.Sprintf("Set credentials via environment variables (prefix: %s_)", "VF"), + "Or set VF_TOKEN to a personal key the user creates under Settings → Personal keys", // errors.go: concrete next steps fmt.Sprintf("Run '%s auth whoami' to verify current authentication", "vf"), }, ) diff --git a/internal/cli/configure.go b/internal/cli/configure.go index 38e7261..646917f 100644 --- a/internal/cli/configure.go +++ b/internal/cli/configure.go @@ -45,9 +45,9 @@ func runConfigureCmd(cmd *cobra.Command, args []string) error { "configure_blocked", "the 'configure' command is interactive and cannot be used in agent mode", []string{ - fmt.Sprintf("Set credentials via environment variables (prefix: %s_)", "VF"), - "Pass credentials directly as CLI flags for each command", - fmt.Sprintf("Run '%s whoami' to verify current authentication", "vf"), + "Sign in with 'vf auth login': in agent mode it prints a URL to give the user, then waits for them", // errors.go: concrete next steps + "Or set VF_TOKEN to a personal key the user creates under Settings → Personal keys; every command also accepts --token", + "'vf auth whoami' shows what is configured, without a network call", }, ) } diff --git a/internal/cli/errors.go b/internal/cli/errors.go new file mode 100644 index 0000000..37fcb4a --- /dev/null +++ b/internal/cli/errors.go @@ -0,0 +1,396 @@ +// This file is not generated by Speakeasy. It explains the failures that +// happen around a request rather than in its response: an unknown command or +// flag, a missing or malformed flag, a session that has ended, a broken config +// file, a canceled form. Each gets what output.Error gives an API error: what +// happened, why, and what to do next, drawn for a person or written as JSON +// for an agent (output.Report). +// +// Before this, these errors reached main.go as bare strings, the same text in +// both modes: "unknown flag: --nosuch", with no command named and no way on; +// "missing required flag: --project-id", with no word on where to find one. +// An agent got prose where it expects an envelope. + +package cli + +import ( + "context" + "errors" + "fmt" + "os" + "regexp" + "sort" + "strings" + + "github.com/charmbracelet/huh" + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/config" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/interactive" + "github.com/voiceflow/cli/internal/oauth" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/ui" +) + +func init() { + // output cannot see the browser session (internal/oauth imports output), + // and an explanation of a 401 depends on it. + output.DescribeCredential = describeCredential +} + +// describeCredential says what vf signs requests with, in the order +// client.NewClient picks it: --token, VF_TOKEN, the browser session, then a +// saved token. +func describeCredential(cmd *cobra.Command) output.Credential { + _, source := config.ResolveSecurityCredential(cmd, "token") + switch source { + case "flag": + return output.Credential{Kind: output.CredentialKey, Source: "--token"} + case "env": + return output.Credential{Kind: output.CredentialKey, Source: "VF_TOKEN", EnvWins: true} + } + if s := oauth.CurrentStatus(); s.LoggedIn { + return output.Credential{Kind: output.CredentialSession, Expiry: s.Expiry, Renews: s.Renews} + } + if source == "keyring" || source == "config" { + return output.Credential{Kind: output.CredentialKey, Source: "your saved token"} + } + return output.Credential{} +} + +// renderError explains an error a command returned without printing it, and +// returns it marked as reported so main.go does not print it again. cmd is +// the command cobra resolved; Execute passes ExecuteC's results straight in. +func renderError(cmd *cobra.Command, err error) error { + if err == nil || err.Error() == "" { // nil, or printed already (output/reported.go) + return err + } + if cmd == nil { + cmd = rootCmd + } + if errors.Is(err, huh.ErrUserAborted) || errors.Is(err, context.Canceled) { + fmt.Fprintln(cmd.ErrOrStderr(), output.UI(cmd, cmd.ErrOrStderr()).Status(ui.StatusFailed, "Canceled")) + return output.AlreadyReported(err) + } + var fve *flagutil.FlagValueError + if errors.As(err, &fve) { + if output.IsAgentMode() { + return renderFlagValueError(cmd, err) // flagerrors.go: its envelope is pinned by tests + } + var under []string + if v := fve.DisplayValue(); v != "" { + under = append(under, "you passed: "+v) + } + under = append(under, fve.Hints...) + return output.Report(cmd, output.Explanation{Type: "invalid_flag_value", Title: "invalid value for --" + fve.Flag + ": " + fve.Expected, Why: under}, err) + } + return output.Report(cmd, explainCLIError(cmd, err), err) +} + +var ( + unknownCommandRE = regexp.MustCompile(`^unknown command "([^"]*)" for "([^"]*)"`) + unknownFlagRE = regexp.MustCompile(`^unknown (?:shorthand )?flag: (?:'(.)' in -.*|(--?[^\s=]+))`) + needsValueRE = regexp.MustCompile(`^flag needs an argument: (?:'(.)' in -.*|--?(\S+))`) + badArgumentRE = regexp.MustCompile(`^invalid argument "(.*)" for "(?:-., )?--([^"]+)" flag: (.*)`) + missingFlagRE = regexp.MustCompile(`^missing required flag: --(\S+)`) + configFileRE = regexp.MustCompile(`^failed to (parse|read) config file (\S+): (.*)`) + badTimeoutRE = regexp.MustCompile(`^invalid --timeout value "([^"]*)"`) +) + +// explainCLIError explains an error that is not an API response. It matches +// the messages cobra, pflag and the generated code produce, which carry no +// types to match on. +func explainCLIError(cmd *cobra.Command, err error) output.Explanation { + msg := err.Error() + help := "`" + cmd.CommandPath() + " --help`" + x := output.Explanation{Type: "usage_error", Title: firstLine(msg)} + + if errors.Is(err, oauth.ErrSessionEnded) { + x.Type = "auth_session_ended" + x.Title = "Your browser session has ended" + x.Why = []string{"It expired or was signed out, so vf cleared it."} + x.Next = []string{"Sign in again: `vf auth login`"} + if output.IsAgentMode() { + x.Next = []string{"Run `vf auth login` in the background and give the user the authorization_url it prints", "Or set VF_TOKEN to a personal key the user creates under Settings → Personal keys"} + } + x.Docs = output.AuthDocsURL + return x + } + if errors.Is(err, oauth.ErrRenewSession) { + x.Type = "auth_session_renew_failed" + x.Title = "Couldn't renew your browser session" + x.Why = []string{"Its access token expired, and renewing it failed: " + lastCause(msg) + "."} + x.Next = []string{"Check your internet connection and run it again", "If it keeps failing, sign in again: `vf auth login`"} + return x + } + if errors.Is(err, flagutil.ErrStdinTimeout) { + lines := strings.Split(msg, "\n") + x.Type = "stdin_timeout" + x.Next = trimAll(lines[1:]) + return x + } + + if m := unknownCommandRE.FindStringSubmatch(msg); m != nil { + x.Type = "unknown_command" + x.Title = m[2] + " has no command \"" + m[1] + "\"" + target := cmd + if found, _, findErr := cmd.Root().Find(strings.Fields(strings.TrimPrefix(m[2], cmd.Root().Name()))); findErr == nil && found != nil { + target = found + } + if target.SuggestionsMinimumDistance <= 0 { + target.SuggestionsMinimumDistance = 2 // cobra sets this only on its own error path + } + for _, s := range target.SuggestionsFor(m[1]) { + x.Next = append(x.Next, "Did you mean `"+target.CommandPath()+" "+s+"`?") + } + x.Next = append(x.Next, "`"+target.CommandPath()+" --help` lists its commands") + return x + } + if m := unknownFlagRE.FindStringSubmatch(msg); m != nil { + x.Type = "unknown_flag" + name := m[2] + if m[1] != "" { + name = "-" + m[1] + } + x.Title = cmd.CommandPath() + " has no flag " + name + for _, s := range similarFlags(cmd, strings.TrimLeft(name, "-")) { + x.Next = append(x.Next, "Did you mean `--"+s+"`?") + } + x.Next = append(x.Next, help+" lists its flags") + return x + } + if m := needsValueRE.FindStringSubmatch(msg); m != nil { + name := m[2] + if f := cmd.Flags().ShorthandLookup(m[1]); m[1] != "" && f != nil { + name = f.Name + } + x.Title = "--" + name + " needs a value" + x.Next = []string{"Give it one: `--" + name + " `", help + " shows what it takes"} + return x + } + if m := badArgumentRE.FindStringSubmatch(msg); m != nil { + x.Type = "invalid_flag_value" + x.Title = "invalid value for --" + m[2] + ": \"" + m[1] + "\"" + x.Why = []string{lastCause(m[3]) + "."} + x.Next = []string{help + " shows what each flag takes"} + return x + } + if m := missingFlagRE.FindStringSubmatch(msg); m != nil { + return explainMissingFlag(cmd, m[1]) + } + if m := configFileRE.FindStringSubmatch(msg); m != nil { + x.Type = "config_error" + path := m[2] + x.Why = []string{path, m[3]} + if m[1] == "parse" { + x.Title = "vf's config file isn't valid YAML" + x.Next = []string{"Fix it, or move it aside: `mv " + path + " " + path + ".bak`", "Then `vf auth login` signs you in again, and `vf configure` writes the file anew"} + } else { + x.Title = "Couldn't read vf's config file" + x.Next = []string{"Check that you can read it: `ls -l " + path + "`"} + } + return x + } + if m := badTimeoutRE.FindStringSubmatch(msg); m != nil { + x.Type = "invalid_flag_value" + x.Title = "invalid value for --timeout: \"" + m[1] + "\"" + x.Next = []string{"Give a number and a unit: `--timeout 30s`, `--timeout 2m` or `--timeout 500ms`"} + return x + } + + switch { + case strings.HasPrefix(msg, "invalid --jq expression "), strings.HasPrefix(msg, "invalid jq expression "): + x.Type = "invalid_flag_value" + x.Why = []string{"The request wasn't sent."} + x.Next = []string{"Check the filter's syntax; `--jq .` prints the whole result to start from"} + case strings.HasPrefix(msg, "invalid value for --output-format"), strings.HasPrefix(msg, "invalid value for the output-format setting"): + x.Type = "invalid_flag_value" + x.Title, _, _ = strings.Cut(x.Title, ";") + x.Why = []string{"The request wasn't sent."} + x.Next = []string{"Use one of: `" + strings.Join(output.OutputFormats, "`, `") + "`"} + case strings.HasPrefix(msg, "invalid header format "): + x.Type = "invalid_flag_value" + x.Next = []string{"Write it as a name, a colon and a value: `-H 'X-Name: value'`"} + case strings.HasPrefix(msg, "invalid value for --"): + x.Type = "invalid_flag_value" + x.Next = []string{help + " shows what each flag takes"} + case strings.HasPrefix(msg, "no flags provided;"): + x.Title = "Nothing to save: no flags were given" + x.Why = []string{"With --no-interactive, " + cmd.CommandPath() + " saves only what its flags give it."} + x.Next = []string{"Pass the token: `" + cmd.CommandPath() + " --no-interactive --token `", "Or leave out --no-interactive to be asked for it"} + if cmd.Name() == "login" { + x.Next[1] = "Or leave out --no-interactive to sign in with your browser" + } + case msg == "--email is only used with --signup": + x.Title = "--email only works when creating an account" + x.Next = []string{"To create an account: `vf auth signup --email
`", "To sign in, leave --email out: `vf auth login`"} + case strings.HasPrefix(msg, "signup creates the account in the browser"): + x.Next = []string{"`vf auth signup` on its own opens the signup page", "If you already have an account and a key: `vf auth login --manual`"} + case strings.HasPrefix(msg, "only https://www.voiceflow.com/docs URLs are supported"): + x.Next = []string{"Search the docs instead: `vf docs search `"} + default: + x.Type = "error" + if lines := strings.Split(strings.TrimSpace(msg), "\n"); len(lines) > 1 { + x.Why = trimAll(lines[1:]) + } + } + return x +} + +// explainMissingFlag says where the value of a missing flag comes from: for +// an ID, the list command that shows it; at a terminal, the picker. +func explainMissingFlag(cmd *cobra.Command, flag string) output.Explanation { + x := output.Explanation{ + Type: "missing_flag", + Title: cmd.CommandPath() + " needs --" + flag, + } + switch { + case output.IsAgentMode(): + x.Why = []string{"vf doesn't ask for missing values in agent mode."} + case func() bool { v, _ := flagutil.GetBoolFlag(cmd, "no-interactive"); return v }(): + x.Why = []string{"--no-interactive is set, so vf didn't ask for it."} + case !interactive.IsInteractive(cmd): + x.Why = []string{"vf asks for missing values only at a terminal, and this isn't one."} + } + if list := listCommandFor(cmd, flag); list != "" { + x.Next = append(x.Next, "`"+list+"` shows the values it takes") + } + x.Next = append(x.Next, "Pass it: `"+cmd.CommandPath()+" --"+flag+" `") + if interactive.HasPicker(flag) && !output.IsAgentMode() && !interactive.IsInteractive(cmd) { + x.Next = append(x.Next, "At a terminal, without --no-interactive, vf lets you pick it from a list") + } + return x +} + +// listCommandFor is the command that lists the values an ID flag takes: +// 'vf project list' for --project-id. An organization ID is on every +// workspace, so 'vf workspace list' shows those. +func listCommandFor(cmd *cobra.Command, flag string) string { + noun := strings.TrimSuffix(strings.TrimSuffix(flag, "-id"), "-alias") + if noun == flag { + return "" + } + if noun == "organization" { + noun = "workspace" + } + root := cmd.Root() + if list, _, err := root.Find([]string{noun, "list"}); err == nil && list != nil && list.Name() == "list" { + return list.CommandPath() + } + return "" +} + +// unknownSubcommand finds an argument a command group has no command for. +// A group's RunE prints its help, and cobra hands it any word it does not +// recognize as an argument, so 'vf workspace lsit' printed help and exited 0; +// this makes it the error it is. A group that takes arguments of its own says +// so with Args, and is left alone, as is the root, whose words are the home +// prompt's. +func unknownSubcommand(root *cobra.Command, args []string) (*cobra.Command, error) { + cmd, rest, err := root.Find(args) + if err != nil || cmd == nil || cmd == root || !cmd.HasSubCommands() || cmd.Args != nil { + return nil, nil + } + flags := pflag.NewFlagSet(cmd.Name(), pflag.ContinueOnError) + flags.SetOutput(discard{}) + flags.ParseErrorsAllowlist.UnknownFlags = true + flags.AddFlagSet(cmd.Flags()) + flags.AddFlagSet(cmd.InheritedFlags()) + if flags.Lookup("help") == nil { + flags.BoolP("help", "h", false, "") + } + if flags.Parse(rest) != nil || flags.NArg() == 0 { + return nil, nil + } + if help, _ := flags.GetBool("help"); help { + return nil, nil + } + // cobra never runs, so apply --agent-mode here: the error is reported + // in the mode the command line asked for. + _ = cmd.ParseFlags(rest) + output.InitAgentMode(cmd) + return cmd, fmt.Errorf("unknown command %q for %q", flags.Arg(0), cmd.CommandPath()) +} + +// commandLine is the arguments Execute runs, which cobra reads from os.Args. +func commandLine() []string { return os.Args[1:] } + +type discard struct{} + +func (discard) Write(p []byte) (int, error) { return len(p), nil } + +// similarFlags are cmd's flags whose names are close to name: a typo, or a +// prefix of the real one. +func similarFlags(cmd *cobra.Command, name string) []string { + type scored struct { + name string + d int + } + var found []scored + seen := map[string]bool{} + visit := func(f *pflag.Flag) { + if f.Hidden || seen[f.Name] { + return + } + seen[f.Name] = true + d := levenshtein(name, f.Name) + if d <= 2 || (len(name) >= 3 && strings.HasPrefix(f.Name, name)) { + found = append(found, scored{f.Name, d}) + } + } + cmd.Flags().VisitAll(visit) + cmd.InheritedFlags().VisitAll(visit) + sort.Slice(found, func(i, j int) bool { return found[i].d < found[j].d }) + var out []string + for i := 0; i < len(found) && i < 3; i++ { + out = append(out, found[i].name) + } + return out +} + +func levenshtein(a, b string) int { + prev := make([]int, len(b)+1) + for j := range prev { + prev[j] = j + } + for i := 1; i <= len(a); i++ { + cur := make([]int, len(b)+1) + cur[0] = i + for j := 1; j <= len(b); j++ { + cost := 1 + if a[i-1] == b[j-1] { + cost = 0 + } + cur[j] = min(prev[j]+1, cur[j-1]+1, prev[j-1]+cost) + } + prev = cur + } + return prev[len(b)] +} + +func firstLine(s string) string { + s = strings.TrimSpace(s) + if i := strings.IndexByte(s, '\n'); i >= 0 { + return s[:i] + } + return s +} + +func lastCause(msg string) string { + msg = firstLine(msg) + if i := strings.LastIndex(msg, ": "); i >= 0 { + return msg[i+2:] + } + return msg +} + +func trimAll(lines []string) []string { + out := make([]string, 0, len(lines)) + for _, l := range lines { + if l = strings.TrimSpace(l); l != "" { + out = append(out, l) + } + } + return out +} diff --git a/internal/cli/errors_test.go b/internal/cli/errors_test.go new file mode 100644 index 0000000..3d0a221 --- /dev/null +++ b/internal/cli/errors_test.go @@ -0,0 +1,206 @@ +// This file is not generated by Speakeasy. It covers errors.go. + +package cli + +import ( + "bytes" + "errors" + "fmt" + "strings" + "testing" + + "github.com/charmbracelet/huh" + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/oauth" + "github.com/voiceflow/cli/internal/output" +) + +func testRoot(t *testing.T) *cobra.Command { + t.Helper() + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + return root +} + +func find(t *testing.T, root *cobra.Command, path ...string) *cobra.Command { + t.Helper() + cmd, _, err := root.Find(path) + if err != nil { + t.Fatal(err) + } + return cmd +} + +func explained(x output.Explanation) string { + return strings.Join(append(append([]string{x.Title}, x.Why...), x.Next...), "\n") +} + +// 'vf workspace lsit' used to print the group's help and exit 0. +func TestAWordAGroupDoesNotKnowIsAnError(t *testing.T) { + root := testRoot(t) + for _, args := range [][]string{{"workspace"}, {"workspace", "--help"}, {"workspace", "-h"}, {"workspace", "list"}, {"docs", "search", "publish"}, {"nosuch"}, {}} { + if cmd, err := unknownSubcommand(root, args); err != nil { + t.Errorf("%q: %v (%s)", args, err, cmd.CommandPath()) + } + } + cmd, err := unknownSubcommand(root, []string{"workspace", "--output-format", "json", "lsit"}) + if err == nil || cmd.Name() != "workspace" { + t.Fatalf("an unknown word after a group should be an error, got %v", err) + } + x := explainCLIError(cmd, err) + if x.Title != `vf workspace has no command "lsit"` || !strings.Contains(explained(x), "Did you mean `vf workspace list`?") { + t.Errorf("got:\n%s", explained(x)) + } +} + +func TestUnknownCommandsAndFlagsSuggestTheNearest(t *testing.T) { + root := testRoot(t) + x := explainCLIError(root, errors.New(`unknown command "workspce" for "vf"`)) + if !strings.Contains(explained(x), "Did you mean `vf workspace`?") || x.Type != "unknown_command" { + t.Errorf("command typo:\n%s", explained(x)) + } + + create := find(t, root, "workspace", "create") + x = explainCLIError(create, errors.New("unknown flag: --nmae")) + if x.Title != "vf workspace create has no flag --nmae" || !strings.Contains(explained(x), "Did you mean `--name`?") { + t.Errorf("flag typo:\n%s", explained(x)) + } + x = explainCLIError(create, errors.New("unknown shorthand flag: 'z' in -z")) + if x.Title != "vf workspace create has no flag -z" || !strings.Contains(explained(x), "`vf workspace create --help` lists its flags") { + t.Errorf("shorthand:\n%s", explained(x)) + } + x = explainCLIError(create, errors.New("flag needs an argument: --name")) + if x.Title != "--name needs a value" { + t.Errorf("no value: %q", x.Title) + } + x = explainCLIError(create, errors.New(`invalid argument "maybe" for "-d, --debug" flag: strconv.ParseBool: parsing "maybe": invalid syntax`)) + if x.Title != `invalid value for --debug: "maybe"` || x.Why[0] != "invalid syntax." { + t.Errorf("bad bool: %+v", x) + } +} + +// A missing ID says where to find one, and, off a terminal, that a terminal +// would have offered a list. +func TestAMissingFlagSaysWhereItsValueComesFrom(t *testing.T) { + root := testRoot(t) + get := find(t, root, "project", "get") + if err := get.ParseFlags([]string{"--no-interactive"}); err != nil { + t.Fatal(err) + } + x := explainCLIError(get, errors.New("missing required flag: --project-id")) + all := explained(x) + for _, want := range []string{"vf project get needs --project-id", "--no-interactive is set", "`vf project list` shows the values it takes", "Pass it: `vf project get --project-id `"} { + if !strings.Contains(all, want) { + t.Errorf("missing %q in:\n%s", want, all) + } + } + if got := listCommandFor(get, "organization-id"); got != "vf workspace list" { + t.Errorf("organizations are listed on workspaces, got %q", got) + } + if got := listCommandFor(get, "name"); got != "" { + t.Errorf("--name is not an ID, got %q", got) + } +} + +func TestSessionErrorsSayToSignInAgain(t *testing.T) { + root := testRoot(t) + x := explainCLIError(root, fmt.Errorf("%w: Voiceflow no longer accepts it; run 'vf auth login'", oauth.ErrSessionEnded)) + if x.Title != "Your browser session has ended" || !strings.Contains(explained(x), "`vf auth login`") { + t.Errorf("ended: %+v", x) + } + x = explainCLIError(root, fmt.Errorf("%w: %w", oauth.ErrRenewSession, errors.New("call token endpoint: dial tcp: i/o timeout"))) + if x.Title != "Couldn't renew your browser session" || !strings.Contains(x.Why[0], "i/o timeout") { + t.Errorf("renew: %+v", x) + } +} + +func TestLocalMistakesNameTheFix(t *testing.T) { + root := testRoot(t) + list := find(t, root, "workspace", "list") + cases := map[string]string{ + `invalid --timeout value "abc": time: invalid duration "abc"`: "`--timeout 30s`", + `invalid jq expression ".[": unexpected EOF`: "`--jq .`", + `invalid value for --output-format: "nope"; valid options: pretty, json, yaml, table, toon`: "`pretty`, `json`", + `invalid header format "x": expected "Key: Value"`: "-H 'X-Name: value'", + `failed to parse config file /h/.config/vf/config.yaml: yaml: line 1: did not find expected ']'`: "`mv /h/.config/vf/config.yaml /h/.config/vf/config.yaml.bak`", + "--email is only used with --signup": "`vf auth signup --email
`", + "no flags provided; use flags to set values non-interactively, or remove --no-interactive": "--no-interactive --token ", + "only https://www.voiceflow.com/docs URLs are supported (got https://example.com)": "`vf docs search `", + } + for msg, want := range cases { + if got := explained(explainCLIError(list, errors.New(msg))); !strings.Contains(got, want) { + t.Errorf("%s\n want %q in:\n%s", msg, want, got) + } + } + if x := explainCLIError(list, errors.New(`invalid value for --output-format: "nope"; valid options: a, b`)); x.Title != `invalid value for --output-format: "nope"` { + t.Errorf("the options are a step, not part of the title: %q", x.Title) + } +} + +// An error vf knows nothing more about is shown as it is, with no invented +// advice. +func TestAnUnknownErrorIsShownAsIs(t *testing.T) { + root := testRoot(t) + x := explainCLIError(root, errors.New("something odd\n with detail")) + if x.Title != "something odd" || len(x.Why) != 1 || x.Why[0] != "with detail" || len(x.Next) != 0 { + t.Errorf("got %+v", x) + } +} + +func TestRenderErrorPrintsOnceAndMarksReported(t *testing.T) { + root := testRoot(t) + var stderr bytes.Buffer + root.SetErr(&stderr) + cause := errors.New("unknown flag: --nosuch") + got := renderError(root, cause) + if got == nil || got.Error() != "" || !errors.Is(got, cause) { + t.Fatalf("renderError returned %#v, want the error marked as reported", got) + } + if !strings.HasPrefix(stderr.String(), "Error: vf has no flag --nosuch\n") { + t.Errorf("printed %q", stderr.String()) + } + + stderr.Reset() + if got := renderError(root, fmt.Errorf("interactive prompt: %w", huh.ErrUserAborted)); got == nil || got.Error() != "" { + t.Errorf("a canceled form should be reported, got %#v", got) + } + if stderr.String() != "Error: Canceled\n" { + t.Errorf("canceled: %q", stderr.String()) + } + + stderr.Reset() + reported := output.AlreadyReported(errors.New("x")) + if got := renderError(root, reported); got != reported || stderr.Len() != 0 { + t.Errorf("an error printed already is passed through untouched") + } +} + +func TestDescribeCredentialFollowsNewClientsOrder(t *testing.T) { + root := testRoot(t) + list := find(t, root, "workspace", "list") + if err := list.ParseFlags([]string{"--token", "vfp_x"}); err != nil { + t.Fatal(err) + } + if c := describeCredential(list); c.Kind != output.CredentialKey || c.Source != "--token" { + t.Errorf("--token: %+v", c) + } +} + +func TestSimilarFlags(t *testing.T) { + root := testRoot(t) + create := find(t, root, "workspace", "create") + if got := similarFlags(create, "nam"); len(got) == 0 || got[0] != "name" { + t.Errorf("a prefix: %q", got) + } + if got := similarFlags(create, "zzzzzz"); len(got) != 0 { + t.Errorf("nothing near: %q", got) + } + if levenshtein("lsit", "list") != 2 || levenshtein("", "ab") != 2 { + t.Error("levenshtein") + } +} diff --git a/internal/cli/home.go b/internal/cli/home.go index 924b108..86686fa 100644 --- a/internal/cli/home.go +++ b/internal/cli/home.go @@ -146,14 +146,18 @@ func runLine(u *ui.UI, args []string) { root.SetArgs(args) ctx, stop := interruptible() defer stop() - err = renderFlagValueError(root, root.ExecuteContext(ctx)) + if cmd, err := unknownSubcommand(root, args); err != nil { + _ = renderError(cmd, err) + return + } + cmd, err := root.ExecuteContextC(ctx) switch { case err == nil: case err.Error() == "": // already reported, as in main case ctx.Err() != nil: fmt.Fprintln(os.Stderr, u.Status(ui.StatusFailed, "Canceled")) default: - fmt.Fprintln(os.Stderr, err.Error()) + _ = renderError(cmd, err) // errors.go, as in main } } diff --git a/internal/cli/root.go b/internal/cli/root.go index 6f2dfef..fd55e0c 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -258,7 +258,10 @@ func Execute() error { // Bare `vf` no longer opens the explorer: the root command prints the home // banner and opens the home prompt instead (home.go), and the explorer is // `vf explore`. - return renderFlagValueError(rootCmd, rootCmd.Execute()) // see flagerrors.go + if cmd, err := unknownSubcommand(rootCmd, commandLine()); err != nil { // errors.go: 'vf workspace lsit' fails rather than printing help + return renderError(cmd, err) + } + return renderError(rootCmd.ExecuteC()) // errors.go: what went wrong, why, and what to do next } // initExploreCmd registers the "explore" subcommand. diff --git a/internal/interactive/pickers.go b/internal/interactive/pickers.go index 49665ec..a92c188 100644 --- a/internal/interactive/pickers.go +++ b/internal/interactive/pickers.go @@ -45,6 +45,10 @@ var pickers = map[string]Picker{} // RegisterPicker makes the form offer a list for flag. func RegisterPicker(flag string, p Picker) { pickers[flag] = p } +// HasPicker reports whether the form can offer a list for flag, so an error +// about a missing flag can say so. +func HasPicker(flag string) bool { _, ok := pickers[flag]; return ok } + // typeOwn is the last row of every list, for an ID that is not in it: an // organization with no workspace yet, a project shared by link. const typeOwn = "\x00type" diff --git a/internal/oauth/oauth.go b/internal/oauth/oauth.go index 6536fc2..bc9ca14 100644 --- a/internal/oauth/oauth.go +++ b/internal/oauth/oauth.go @@ -490,6 +490,15 @@ func authorizationURL(md Metadata, clientID, redirectURI, state, challenge strin return md.AuthorizationEndpoint + separator + params.Encode() } +// ErrSessionEnded is a stored session that can no longer be used: it expired +// with no refresh token, or the server refused its refresh token. The session +// has been cleared, and signing in again is the fix. +var ErrSessionEnded = errors.New("your browser session has ended") + +// ErrRenewSession is an expired session whose refresh failed for another +// reason, such as the network; the session is kept, so a retry may work. +var ErrRenewSession = errors.New("couldn't renew your browser session") + // AccessToken returns a valid access token for the stored session, refreshing // it when it is expired or about to expire. It returns ErrNoSession when the // user is not logged in. @@ -518,7 +527,7 @@ func AccessToken(ctx context.Context) (string, error) { } if session.RefreshToken == "" { _ = ClearSession() - return "", fmt.Errorf("OAuth session expired; run 'vf auth login'") + return "", fmt.Errorf("%w: it expired and could not renew; run 'vf auth login'", ErrSessionEnded) } tok, err := refreshTokens(ctx, httpClient, session.TokenEndpoint, session.ClientID, session.RefreshToken, session.Scope, session.Resource) @@ -526,14 +535,14 @@ func AccessToken(ctx context.Context) (string, error) { var tokErr *tokenError if errors.As(err, &tokErr) && tokErr.isInvalidGrant() { _ = ClearSession() - return "", fmt.Errorf("OAuth session is no longer valid; run 'vf auth login'") + return "", fmt.Errorf("%w: Voiceflow no longer accepts it; run 'vf auth login'", ErrSessionEnded) } // A transient failure should not break a command whose token is still // inside its lifetime. if !session.expired(now) { return session.AccessToken, nil } - return "", fmt.Errorf("refresh OAuth session: %w", err) + return "", fmt.Errorf("%w: %w", ErrRenewSession, err) } session.AccessToken = tok.AccessToken diff --git a/test/errors-teach.test.ts b/test/errors-teach.test.ts index cea51de..f76fcdb 100644 --- a/test/errors-teach.test.ts +++ b/test/errors-teach.test.ts @@ -1,8 +1,8 @@ // Hermetic tests for "errors that teach": the no-token preflight and // malformed-token warnings (internal/sdk/sdkinternal/hooks/teach.go), and the // explanation, hints and docs_url every failure carries -// (internal/output/explain.go). Uses a local mock API — no live -// credentials. +// (internal/output/explain.go, internal/cli/errors.go). Uses a local mock +// API — no live credentials. // // Requires the CLI binary at the repo root: go build -o vf ./cmd/vf @@ -111,7 +111,10 @@ describe('required-flag preflight', () => { // Unroutable server: proves the request never leaves the machine. const result = await $vf(['project', 'get', '--token', 'vfp_x', '--server-url', 'http://127.0.0.1:1']); expect(result.exitCode).toBe(1); - expect(result.stderr).toContain('missing required flag: --project-id'); + const envelope = parseEnvelope(result.stderr); + expect(envelope.error_type).toBe('missing_flag'); + expect(envelope.error).toBe('vf project get needs --project-id'); + expect(JSON.stringify(envelope.hints)).toContain("'vf project list' shows the values it takes"); expect(result.stderr).not.toContain('statusCode'); // no server round-trip happened }); @@ -120,7 +123,7 @@ describe('required-flag preflight', () => { VF, ['project', 'get', '--token', 'vfp_x', '--server-url', 'http://127.0.0.1:1'], ); expect(result.exitCode).toBe(1); - expect(result.stderr).toContain('missing required flag: --project-id'); + expect(result.stderr).toContain('needs --project-id'); expect(result.stderr).not.toContain('statusCode'); }); @@ -231,4 +234,18 @@ describe('human-mode errors print once', () => { expect(result.stderr).toContain("couldn't reach Voiceflow"); expect(result.stderr.split('connection refused').length - 1, result.stderr).toBe(1); }); + + it('fails on a word a command group does not know, instead of printing its help', async () => { + const result = await human(['workspace', 'lsit']); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('vf workspace has no command "lsit"'); + expect(result.stderr).toContain("Did you mean 'vf workspace list'?"); + }); + + it('refuses an unusable --jq before sending a write', async () => { + const result = await human(['project', 'create', '--body', '{"name":"x","workspaceID":"w","type":"webchat"}', '--server-url', mockURL, '--jq', '.[']); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('invalid --jq expression'); + expect(result.stderr).toContain("The request wasn't sent."); + }); }); From a7f3c76aaae1ee37f5767a8fcd35b856e66da4f1 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:25:10 -0500 Subject: [PATCH 07/30] docs: specify how errors read, and call personal keys by their name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DESIGN.md gets an Errors section: the ✗ line, the cause under ⎿, next steps with commands in Accent, docs in Muted, the plain form off a terminal and the JSON fields in agent mode. The READMEs pointed at Settings → Access tokens, which the Voiceflow docs now call Personal keys; the npm README also leads with 'vf auth login'. --- README.md | 2 +- internal/ui/DESIGN.md | 51 ++++++++++++++++++++++++++++++++++++++++++- npm/cli/README.md | 8 ++++++- 3 files changed, 58 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 031a7a7..f41252e 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ Download pre-built binaries for your platform from the [releases page](https://g ## Quickstart: zero to a talking agent -Runnable end to end by a person or by a coding agent. You need credentials and [`jq`](https://jqlang.org) (used only to pull IDs out of the JSON responses). At a terminal, `vf auth login` signs you in through the browser and stores the session for you (see [Browser sign-in](#browser-sign-in-oauth2)). For scripts, CI, and coding agents, create a **personal access token** in Voiceflow under **Settings → Access tokens** (tokens start with `vfp_`; they expire, default 30 days), then: +Runnable end to end by a person or by a coding agent. You need credentials and [`jq`](https://jqlang.org) (used only to pull IDs out of the JSON responses). At a terminal, `vf auth login` signs you in through the browser and stores the session for you (see [Browser sign-in](#browser-sign-in-oauth2)). For scripts, CI, and coding agents, create a **personal key** in Voiceflow under **Settings → Personal keys** (keys start with `vfp_`; they expire, default 30 days), then: ```bash export VF_TOKEN=vfp_... # every command also accepts --token diff --git a/internal/ui/DESIGN.md b/internal/ui/DESIGN.md index 6ce32a4..8de886d 100644 --- a/internal/ui/DESIGN.md +++ b/internal/ui/DESIGN.md @@ -88,7 +88,7 @@ Only the glyph takes the state color; the message stays in the default color. - **Results** indent under the line that produced them: `⏺ Running test suite` then ` ⎿ 38 passed · 2 failed`. - **Errors** say what happened, why, and the fix: a `✗` line, a `⎿` line with - the cause, then the command that resolves it in Accent. + the cause, then the command that resolves it in Accent. See "Errors" below. - **Motion**: anything that can take longer than about 300 ms shows `✻` with the elapsed time and how to cancel. Never in a pipe. `ui.Spin` draws it, animating Claude Code's frames (`· ✢ ✳ ✶ ✻ ✽`) on one line it erases when @@ -283,6 +283,55 @@ flag lists). before. While a list loads, the spinner says what it loads (`✻ Loading projects…`). +## Errors + +Every failure answers three questions: what happened, why, and what to do +next. `output.ExplainError` and the CLI's `explainCLIError` build one +`Explanation`, and it is drawn for a person or written as JSON for an agent, +never both: + +``` +✗ Couldn't create workspace · HTTP 401 Unauthorized + ⎿ You're signed in, and your session is current, so this isn't an expired login. + Most likely your account isn't allowed to do this in the workspace or + organization it targets: some actions, such as creating a workspace, need + an admin role there. + Next: + Check your role there, or try the same thing in the Voiceflow app + vf auth whoami shows who you're signed in as + If your access changed recently, sign in again: vf auth logout, then vf auth login + Docs: https://www.voiceflow.com/docs/cli/commands/workspace +``` + +- **The `✗` line** is the command that failed (`Couldn't` + its short help), + then `·` and the kind of failure: `HTTP 404 Not Found`, `timed out`, + `couldn't reach Voiceflow`, `you're not signed in`. A failure that is not a + request names the problem itself: `vf workspace has no command "lsit"`. +- **Under `⎿`**: the server's own message when it says more than the status + (`Project not found`, never `Unauthorized`), then why, then the fields the + server rejected, each with the flag that sets it (`name: Required (--name)`). + No raw JSON: `-o json` and `--debug` have the body. +- **Next** steps are ones a person can take now, most likely first. Commands + are in Accent. A step never sends someone the wrong way: a 403 does not say + to sign in, and a refused browser session is not called an expired token. +- **Docs** in Muted: the command group's page. +- **Why depends on what vf knows**: a 401 reads differently for a key from + `--token`, a `VF_TOKEN` that outranks the session, and a browser session; a + missing ID names the list command that shows it, and, off a terminal, says a + terminal would have offered a picker. +- **Off a terminal** it is `Error: …` and `-`, with commands in 'quotes', so CI + logs stay greppable and steps stay pasteable. +- **In agent mode** the same content is one JSON object on stderr: + `error_type`, `message`, `explanation` (why), `hints` (the next steps, with + commands in 'quotes'), `docs_url`, plus every key the response carried. A + server's own `hints` and `docs_url` win over vf's. +- **Unknown words** suggest the nearest: `Did you mean 'vf workspace list'?`, + `Did you mean '--name'?`. +- **Fail before sending** whatever can be checked locally: a missing + credential, an `--output-format` vf does not have, a `--jq` that will not + compile. A create command that fails after it has created something invites + a second create. + ## Aligning vfe `vfe` already shares the accent, the rounded banner with its title in the diff --git a/npm/cli/README.md b/npm/cli/README.md index 1b1b8e0..5fb9887 100644 --- a/npm/cli/README.md +++ b/npm/cli/README.md @@ -16,7 +16,13 @@ This package installs a prebuilt binary for your platform via an optional depend ## Authenticate -Create a personal access token in Voiceflow under **Settings → Access tokens** (tokens start with `vfp_`), then: +At a terminal, sign in through the browser: + +```bash +vf auth login +``` + +For scripts, CI and coding agents, create a personal key in Voiceflow under **Settings → Personal keys** (keys start with `vfp_`), then: ```bash export VF_TOKEN=vfp_... From 05090d043c5e73816dde0a0f0df085d535c593af Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:46:53 -0500 Subject: [PATCH 08/30] feat(output): name the organization or workspace a refusal targeted A 401 to a current browser session, or a 403, comes with no reason, and the API has no endpoint for organizations or roles. So the explanation was a guess: "most likely your account isn't allowed to do this in the workspace or organization it targets". Now vf looks the target up in your workspaces, the one request an error makes, and says which organization or workspace was refused and whether you're in it: It targeted organization o1 (Acme, Support). You're in 2 of its workspaces, so you're a member, but your role in the organization most likely doesn't allow this. A member is told to ask an owner or admin of that organization; someone with no workspace in it is told to check the ID. A refused key is still a bad key (no lookup), and a picker's one-line warning skips it. The picker list calls now send the command's -H headers too, as the command's own request does. --- internal/cli/errors.go | 60 +++++++++++++++++++ internal/cli/errors_test.go | 31 ++++++++++ internal/cli/pickers.go | 18 +++++- internal/output/explain.go | 101 +++++++++++++++++++++++++++----- internal/output/explain_test.go | 61 +++++++++++++++++++ internal/ui/DESIGN.md | 16 +++-- 6 files changed, 264 insertions(+), 23 deletions(-) diff --git a/internal/cli/errors.go b/internal/cli/errors.go index 37fcb4a..8018eb9 100644 --- a/internal/cli/errors.go +++ b/internal/cli/errors.go @@ -14,12 +14,14 @@ package cli import ( "context" + "encoding/json" "errors" "fmt" "os" "regexp" "sort" "strings" + "time" "github.com/charmbracelet/huh" "github.com/spf13/cobra" @@ -37,6 +39,64 @@ func init() { // output cannot see the browser session (internal/oauth imports output), // and an explanation of a 401 depends on it. output.DescribeCredential = describeCredential + // Nor can it list your workspaces, which says whether you're in the + // organization or workspace a refused request targeted. + output.CheckAccess = checkAccess +} + +// checkAccess finds the organization or workspace cmd targeted among your +// workspaces. It is the one lookup an error makes: a refusal the API gives +// no reason for (a 401 while signed in, a 403) is otherwise a guess. +func checkAccess(cmd *cobra.Command) (output.Access, bool) { + kind, id := accessTarget(cmd) + if id == "" { + return output.Access{}, false + } + ctx := context.Background() + if cmd.Context() != nil { + ctx = cmd.Context() + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + workspaces, err := listWorkspaces(ctx, cmd, "Checking your access…") + if err != nil { + return output.Access{}, false + } + a := output.Access{Kind: kind, ID: id} + var names []string + for _, w := range workspaces { + switch { + case kind == "workspace" && w.ID == id: + a.Name, a.Yours = w.Name, true + case kind == "organization" && w.OrganizationID == id: + names = append(names, w.Name) + } + } + if kind == "organization" { + a.Name, a.Count, a.Yours = workspaceNames(names), len(names), len(names) > 0 + } + return a, true +} + +// accessTarget is the workspace or organization cmd was given, by flag or +// in --body; a workspace, the narrower of the two, wins. +func accessTarget(cmd *cobra.Command) (kind, id string) { + var body map[string]interface{} + if f := cmd.Flags().Lookup("body"); f != nil && f.Value.String() != "" { + _ = json.Unmarshal([]byte(f.Value.String()), &body) + } + for _, t := range []struct{ kind, flag, field string }{ + {"workspace", "workspace-id", "workspaceID"}, + {"organization", "organization-id", "organizationID"}, + } { + if f := cmd.Flags().Lookup(t.flag); f != nil && f.Changed && f.Value.String() != "" { + return t.kind, f.Value.String() + } + if v, ok := body[t.field].(string); ok && v != "" { + return t.kind, v + } + } + return "", "" } // describeCredential says what vf signs requests with, in the order diff --git a/internal/cli/errors_test.go b/internal/cli/errors_test.go index 3d0a221..3a0185a 100644 --- a/internal/cli/errors_test.go +++ b/internal/cli/errors_test.go @@ -191,6 +191,37 @@ func TestDescribeCredentialFollowsNewClientsOrder(t *testing.T) { } } +// checkAccess finds the target among your workspaces (fakeAPI in +// pickers_test.go: o1 has Acme, Support, Sales and Ops; o2 has Lab). +func TestCheckAccessFindsTheTargetAmongYourWorkspaces(t *testing.T) { + srv := fakeAPI(t) + isolate(t) + create := func(flags ...string) *cobra.Command { + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + cmd := find(t, root, "workspace", "create") + if err := cmd.ParseFlags(append([]string{"--server-url", srv.URL, "--token", "vfp_test"}, flags...)); err != nil { + t.Fatal(err) + } + return cmd + } + a, ok := checkAccess(create("--organization-id", "o1")) + if !ok || a != (output.Access{Kind: "organization", ID: "o1", Name: "Acme, Support +2 more", Yours: true, Count: 4}) { + t.Errorf("o1: %+v %v", a, ok) + } + if a, ok = checkAccess(create("--organization-id", "o9")); !ok || a.Yours || a.Count != 0 { + t.Errorf("an organization you have no workspace in: %+v %v", a, ok) + } + if a, ok = checkAccess(create("--body", `{"name":"x","workspaceID":"w3"}`)); !ok || a != (output.Access{Kind: "workspace", ID: "w3", Name: "Lab", Yours: true}) { + t.Errorf("a workspace named in --body: %+v %v", a, ok) + } + if _, ok = checkAccess(create("--name", "x")); ok { + t.Errorf("no target, no lookup") + } +} + func TestSimilarFlags(t *testing.T) { root := testRoot(t) create := find(t, root, "workspace", "create") diff --git a/internal/cli/pickers.go b/internal/cli/pickers.go index 63ecc58..f69023f 100644 --- a/internal/cli/pickers.go +++ b/internal/cli/pickers.go @@ -12,6 +12,7 @@ import ( "github.com/spf13/cobra" "github.com/voiceflow/cli/internal/client" "github.com/voiceflow/cli/internal/interactive" + "github.com/voiceflow/cli/internal/output" "github.com/voiceflow/cli/internal/sdk/models/components" "github.com/voiceflow/cli/internal/sdk/models/operations" ) @@ -36,13 +37,24 @@ func listWorkspaces(ctx context.Context, cmd *cobra.Command, msg string) ([]comp if err != nil { return nil, err } - res, err := s.Workspace.List(client.WithSpinnerMessage(ctx, msg)) + res, err := s.Workspace.List(client.WithSpinnerMessage(ctx, msg), headers(cmd)...) if err != nil || res.StableWorkspaceListResponse == nil { return nil, err } return res.StableWorkspaceListResponse.Workspaces, nil } +// headers sends the command's -H headers with a list call too, as its own +// request will (output.PrepareCallOpts). A bad flag is reported by that +// request, so here it only means no headers. +func headers(cmd *cobra.Command) []operations.Option { + opts, err := output.PrepareCallOpts(cmd) + if err != nil { + return nil + } + return opts +} + func listWorkspaceChoices(ctx context.Context, cmd *cobra.Command, _ map[string]string) ([]interactive.Choice, error) { workspaces, err := listWorkspaces(ctx, cmd, "Loading your workspaces…") if err != nil { @@ -102,7 +114,7 @@ func listProjects(ctx context.Context, cmd *cobra.Command, needs map[string]stri return nil, err } res, err := s.Project.List(client.WithSpinnerMessage(ctx, "Loading projects…"), - operations.StableProjectControllerListRequest{WorkspaceID: needs["workspace-id"]}) + operations.StableProjectControllerListRequest{WorkspaceID: needs["workspace-id"]}, headers(cmd)...) if err != nil || res.StableProjectListResponse == nil { return nil, err } @@ -119,7 +131,7 @@ func listEnvironments(ctx context.Context, cmd *cobra.Command, needs map[string] return nil, err } res, err := s.Environment.List(client.WithSpinnerMessage(ctx, "Loading environments…"), - operations.StableEnvironmentControllerListRequest{ProjectID: needs["project-id"]}) + operations.StableEnvironmentControllerListRequest{ProjectID: needs["project-id"]}, headers(cmd)...) if err != nil || res.StableEnvironmentListResponse == nil { return nil, err } diff --git a/internal/output/explain.go b/internal/output/explain.go index b210f73..9551154 100644 --- a/internal/output/explain.go +++ b/internal/output/explain.go @@ -84,6 +84,25 @@ var DescribeCredential = func(cmd *cobra.Command) Credential { return Credential{} } +// Access is what vf could find out about your access to the organization +// or workspace a command targeted, from the workspaces you can see. The API +// has no endpoint for organizations or roles, so this is as far as vf can +// tell. +type Access struct { + Kind string // "organization" or "workspace" + ID string + Name string // the workspace's name, or an organization's workspaces: "Acme, Support" + Yours bool // you're in the workspace, or in at least one of the organization's workspaces + Count int // for an organization: how many of its workspaces you're in +} + +// CheckAccess looks up Access for the organization or workspace cmd names, +// so a 401 or 403 can say which one was refused and whether you're in it. +// The cli package replaces it with one that lists your workspaces, which +// this package cannot do; ok is false when cmd names neither, or the lookup +// fails. +var CheckAccess = func(cmd *cobra.Command) (a Access, ok bool) { return Access{}, false } + const ( docsCommandBase = "https://www.voiceflow.com/docs/cli/commands" AuthDocsURL = "https://www.voiceflow.com/docs/api-reference/authentication" @@ -107,11 +126,17 @@ func ExplainError(cmd *cobra.Command, err error) Explanation { } func explain(cmd *cobra.Command, err error, status int, body string) Explanation { + return explainWith(cmd, err, status, body, CheckAccess) +} + +// explainWith explains err, calling checkAccess, which may send a request, +// only for a refusal it could explain. +func explainWith(cmd *cobra.Command, err error, status int, body string, checkAccess func(*cobra.Command) (Access, bool)) Explanation { if x, ok := explainNoCredential(cmd, err); ok { return x } if status != 0 { - return explainAPI(cmd, err, status, body, extractErrorResponseHeaders(err)) + return explainAPI(cmd, err, status, body, extractErrorResponseHeaders(err), checkAccess) } if x, ok := explainTransport(cmd, err); ok { return x @@ -122,7 +147,10 @@ func explain(cmd *cobra.Command, err error, status int, body string) Explanation // ShortReason is one line saying why a request failed, for a status line // that reports the failure in passing: "Couldn't list your workspaces: …". func ShortReason(cmd *cobra.Command, err error) string { - x := ExplainError(cmd, err) + // No access lookup: a line in passing does not show it, and it would + // send a request while reporting that one failed. + noLookup := func(*cobra.Command) (Access, bool) { return Access{}, false } + x := explainWith(cmd, err, extractErrorStatusCode(err), extractErrorBody(err), noLookup) if x.Type == "error" { // nothing more to say than the error itself return firstLine(err.Error()) } @@ -136,7 +164,7 @@ func ShortReason(cmd *cobra.Command, err error) string { return reason } -func explainAPI(cmd *cobra.Command, err error, status int, body string, headers http.Header) Explanation { +func explainAPI(cmd *cobra.Command, err error, status int, body string, headers http.Header, checkAccess func(*cobra.Command) (Access, bool)) Explanation { fields := parseObject(body) x := Explanation{ Type: classifyErrorType(status), @@ -168,7 +196,7 @@ func explainAPI(cmd *cobra.Command, err error, status int, body string, headers "`"+cmd.CommandPath()+" --help` lists the flags and the values they take") case status == 401: - x.Why, x.Next = unauthorized(cred) + x.Why, x.Next = unauthorized(cmd, cred, checkAccess) case status == 402: x.Type = "payment_required" @@ -183,11 +211,13 @@ func explainAPI(cmd *cobra.Command, err error, status int, body string, headers case status == 403: x.Why = []string{"You're signed in, but your account isn't allowed to do this. The resource may belong to a workspace or organization you can't act on, or your role there may not include this action."} - if cred.Kind == CredentialKey { - x.Why = append(x.Why, "Personal keys can also be limited to some workspaces, projects and actions; the one from "+cred.Source+" may not cover this.") - } x.Next = []string{"`vf workspace list` shows the workspaces you can reach", "Ask an admin of that workspace or organization for access"} + if a, ok := checkAccess(cmd); ok { + x.Why = []string{"You're signed in, but your account isn't allowed to do this.", accessWhy(a)} + x.Next = accessNext(a) + } if cred.Kind == CredentialKey { + x.Why = append(x.Why, "Personal keys can also be limited to some workspaces, projects and actions; the one from "+cred.Source+" may not cover this.") x.Next = append(x.Next, "Check the key's access in Voiceflow under Settings → Personal keys") } @@ -233,21 +263,25 @@ func explainAPI(cmd *cobra.Command, err error, status int, body string, headers return x } -// unauthorized explains a 401 in terms of the credential that was sent. -func unauthorized(cred Credential) (why, next []string) { +// unauthorized explains a 401 in terms of the credential that was sent and, +// for a session that is current, the organization or workspace refused. +func unauthorized(cmd *cobra.Command, cred Credential, checkAccess func(*cobra.Command) (Access, bool)) (why, next []string) { switch cred.Kind { case CredentialSession: if !cred.Expiry.IsZero() && time.Now().After(cred.Expiry) && !cred.Renews { return []string{"Your browser session has ended."}, []string{"Sign in again: `vf auth login`"} } - return []string{ - "You're signed in, and your session is current, so this isn't an expired login.", - "Most likely your account isn't allowed to do this in the workspace or organization it targets: some actions, such as creating a workspace, need an admin role there.", - }, []string{ - "Check your role there, or try the same thing in the Voiceflow app", - "`vf auth whoami` shows who you're signed in as", - "If your access changed recently, sign in again: `vf auth logout`, then `vf auth login`", + why = []string{"You're signed in, and your session is current, so this isn't an expired login."} + next = []string{"Check your role there, or try the same thing in the Voiceflow app"} + if a, ok := checkAccess(cmd); ok { + why = append(why, accessWhy(a)) + next = accessNext(a) + } else { + why = append(why, "Most likely your account isn't allowed to do this in the workspace or organization it targets: some actions, such as creating a workspace, need an admin role there.") } + return why, append(next, + "`vf auth whoami` shows who you're signed in as", + "If your access changed recently, sign in again: `vf auth logout`, then `vf auth login`") case CredentialKey: why = []string{"Voiceflow didn't accept the token from " + cred.Source + ". Personal keys expire (after 30 days by default) and can be deleted; this one may have lapsed."} if cred.EnvWins { @@ -261,6 +295,41 @@ func unauthorized(cred Credential) (why, next []string) { return []string{"Voiceflow didn't accept the request's credentials."}, []string{"Sign in: `vf auth login`"} } +// accessWhy says which organization or workspace was refused and what your +// workspaces say about your access to it. +func accessWhy(a Access) string { + switch { + case a.Kind == "organization" && a.Yours: + in := "one of its workspaces" + if a.Count > 1 { + in = strconv.Itoa(a.Count) + " of its workspaces" + } + return "It targeted organization " + a.ID + " (" + a.Name + "). You're in " + in + ", so you're a member, but your role in the organization most likely doesn't allow this: some actions, such as creating a workspace, need an organization owner or admin." + case a.Kind == "organization": + return "It targeted organization " + a.ID + ", and none of your workspaces are in it: you may not be a member, or the ID may be wrong." + case a.Yours: + return "It targeted workspace " + a.Name + " (" + a.ID + "). You're in it, so your role there most likely doesn't allow this." + default: + return "It targeted workspace " + a.ID + ", which isn't one of your workspaces: you may not have access to it, or the ID may be wrong." + } +} + +// accessNext is who to ask, or what to check, for the refusal accessWhy +// explains. +func accessNext(a Access) []string { + if a.Yours { + who := "organization " + a.ID + " (" + a.Name + ")" + if a.Kind == "workspace" { + who = "workspace " + a.Name + } + return []string{"Ask an owner or admin of " + who + " for the role this needs, or try the same thing in the Voiceflow app"} + } + return []string{ + "Check the ID: `vf workspace list` shows your workspaces and their organizations", + "If it's right, ask an admin of that " + a.Kind + " to add you", + } +} + // explainNoCredential recognizes the request the SDK refused to send because // no credential is set up (internal/sdk/sdkinternal/hooks/teach.go). func explainNoCredential(cmd *cobra.Command, err error) (Explanation, bool) { diff --git a/internal/output/explain_test.go b/internal/output/explain_test.go index dd3d418..a93dd9e 100644 --- a/internal/output/explain_test.go +++ b/internal/output/explain_test.go @@ -189,6 +189,67 @@ func TestUnauthorizedDependsOnTheCredential(t *testing.T) { } } +// withAccess makes CheckAccess report a for the test, and counts the calls. +func withAccess(t *testing.T, a Access, ok bool) *int { + t.Helper() + saved, calls := CheckAccess, 0 + CheckAccess = func(*cobra.Command) (Access, bool) { calls++; return a, ok } + t.Cleanup(func() { CheckAccess = saved }) + return &calls +} + +// A refusal the API gives no reason for names what it refused, and what +// your workspaces say about your access to it. +func TestARefusalNamesTheOrganizationOrWorkspace(t *testing.T) { + cmd := projectGet(t) + unauthorized := apiError(401, `{"statusCode":401,"message":"Unauthorized"}`, nil) + forbidden := apiError(403, `{"statusCode":403,"message":"Forbidden resource"}`, nil) + withCredential(t, Credential{Kind: CredentialSession, Expiry: time.Now().Add(time.Hour), Renews: true}) + + withAccess(t, Access{Kind: "organization", ID: "o1", Name: "Acme, Support", Yours: true, Count: 2}, true) + member := joined(ExplainError(cmd, unauthorized)) + for _, want := range []string{"isn't an expired login", "It targeted organization o1 (Acme, Support)", "You're in 2 of its workspaces, so you're a member", "organization owner or admin", "Ask an owner or admin of organization o1", "`vf auth whoami`"} { + if !strings.Contains(member, want) { + t.Errorf("a member refused should hear %q:\n%s", want, member) + } + } + if strings.Contains(member, "Most likely your account") { + t.Errorf("the guess is replaced by what vf found:\n%s", member) + } + + withAccess(t, Access{Kind: "organization", ID: "o9"}, true) + stranger := joined(ExplainError(cmd, unauthorized)) + for _, want := range []string{"none of your workspaces are in it", "the ID may be wrong", "`vf workspace list` shows your workspaces and their organizations", "ask an admin of that organization to add you"} { + if !strings.Contains(stranger, want) { + t.Errorf("a non-member should hear %q:\n%s", want, stranger) + } + } + + withAccess(t, Access{Kind: "workspace", ID: "w1", Name: "Acme", Yours: true}, true) + if got := joined(ExplainError(cmd, forbidden)); !strings.Contains(got, "It targeted workspace Acme (w1). You're in it") || !strings.Contains(got, "Ask an owner or admin of workspace Acme") { + t.Errorf("a 403 in your own workspace:\n%s", got) + } + withAccess(t, Access{Kind: "workspace", ID: "w9"}, true) + withCredential(t, Credential{Kind: CredentialKey, Source: "VF_TOKEN", EnvWins: true}) + if got := joined(ExplainError(cmd, forbidden)); !strings.Contains(got, "workspace w9, which isn't one of your workspaces") || !strings.Contains(got, "Settings → Personal keys") { + t.Errorf("a 403 with a key keeps the key's step:\n%s", got) + } + + // A refused key is a bad key, not a role: no lookup. + calls := withAccess(t, Access{Kind: "organization", ID: "o1", Yours: true}, true) + _ = ExplainError(cmd, unauthorized) + if *calls != 0 { + t.Errorf("a 401 with a key should not look up access") + } + // Nor does a line in passing, or an error that isn't a refusal. + withCredential(t, Credential{Kind: CredentialSession, Expiry: time.Now().Add(time.Hour), Renews: true}) + _ = ShortReason(cmd, unauthorized) + _ = ExplainError(cmd, apiError(404, `{}`, nil)) + if *calls != 0 { + t.Errorf("ShortReason and a 404 should not look up access, got %d calls", *calls) + } +} + func TestAServersOwnHintsWin(t *testing.T) { withCredential(t, Credential{}) x := ExplainError(projectGet(t), apiError(404, `{"message":"Gone","hints":["Ask Kim"],"docs_url":"https://example.com/x"}`, nil)) diff --git a/internal/ui/DESIGN.md b/internal/ui/DESIGN.md index 8de886d..226917b 100644 --- a/internal/ui/DESIGN.md +++ b/internal/ui/DESIGN.md @@ -293,11 +293,13 @@ never both: ``` ✗ Couldn't create workspace · HTTP 401 Unauthorized ⎿ You're signed in, and your session is current, so this isn't an expired login. - Most likely your account isn't allowed to do this in the workspace or - organization it targets: some actions, such as creating a workspace, need - an admin role there. + It targeted organization o1 (Acme, Support). You're in 2 of its workspaces, + so you're a member, but your role in the organization most likely doesn't + allow this: some actions, such as creating a workspace, need an + organization owner or admin. Next: - Check your role there, or try the same thing in the Voiceflow app + Ask an owner or admin of organization o1 (Acme, Support) for the role this + needs, or try the same thing in the Voiceflow app vf auth whoami shows who you're signed in as If your access changed recently, sign in again: vf auth logout, then vf auth login Docs: https://www.voiceflow.com/docs/cli/commands/workspace @@ -319,6 +321,12 @@ never both: `--token`, a `VF_TOKEN` that outranks the session, and a browser session; a missing ID names the list command that shows it, and, off a terminal, says a terminal would have offered a picker. +- **A refusal names what it refused.** The API gives no reason for a 401 to a + current session or a 403, and has no endpoint for organizations or roles, + so vf looks the target up in your workspaces, the one request an error + makes: the organization or workspace the command named, and whether you're + in it. A member is told to ask an owner or admin; a stranger to check the + ID. Lines in passing (a picker's warning) skip the lookup. - **Off a terminal** it is `Error: …` and `-`, with commands in 'quotes', so CI logs stay greppable and steps stay pasteable. - **In agent mode** the same content is one JSON object on stderr: From 94ab4db9a4f1d002ef62db4feb233690656faec9 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:02:25 -0500 Subject: [PATCH 09/30] feat(home): carry the current workspace and project to the next command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The home prompt forgot everything between lines: after 'project create' the next command asked for the project again, from a list, as if nothing had happened. The best CLIs keep you at the prompt but carry what you were working on forward: gcloud's current project, kubectl's context, psql's \c. Now what you create or pick in the prompt becomes current (internal/session), for the four levels the pickers know: organization, workspace, project, environment. - A command that needs one uses the current one and says so: "✓ Using project Help bot (p1), the current one". A command that changes or removes what it picks still shows the list, the current one first, so nothing is deleted unseen. - The prompt box's top border shows it: ╭─ workspace Acme › project Help bot ─╮ - 'use' shows it, 'use project' picks a new one, 'use clear' drops it. - Changing a level clears the narrower ones, and deleting the current one forgets it. - It lives only as long as the prompt: a one-shot vf command and agent mode never see it. A create now ends the way the best CLIs end one, wherever pretty output reaches a person: a "✓ Created project Help bot (p1) in workspace Acme" line, the result, then Next: steps. In the prompt the steps leave out the IDs the context fills in; elsewhere they carry them. JSON, --jq, agent mode and a pipe get the result alone. --- internal/cli/home.go | 68 ++++++++- internal/interactive/pickers.go | 95 +++++++++++- internal/interactive/pickers_test.go | 100 ++++++++++++- internal/output/created.go | 209 +++++++++++++++++++++++++++ internal/output/created_test.go | 119 +++++++++++++++ internal/output/output.go | 1 + internal/prompt/prompt.go | 20 ++- internal/prompt/prompt_test.go | 21 +++ internal/session/session.go | 115 +++++++++++++++ internal/session/session_test.go | 78 ++++++++++ internal/ui/DESIGN.md | 42 ++++++ 11 files changed, 853 insertions(+), 15 deletions(-) create mode 100644 internal/output/created.go create mode 100644 internal/output/created_test.go create mode 100644 internal/session/session.go create mode 100644 internal/session/session_test.go diff --git a/internal/cli/home.go b/internal/cli/home.go index 86686fa..cd19b77 100644 --- a/internal/cli/home.go +++ b/internal/cli/home.go @@ -7,18 +7,21 @@ package cli import ( "context" + "errors" "fmt" "io" "os" "os/signal" "strings" + "github.com/charmbracelet/huh" "github.com/spf13/cobra" "github.com/voiceflow/cli/internal/config" "github.com/voiceflow/cli/internal/interactive" "github.com/voiceflow/cli/internal/oauth" "github.com/voiceflow/cli/internal/output" "github.com/voiceflow/cli/internal/prompt" + "github.com/voiceflow/cli/internal/session" "github.com/voiceflow/cli/internal/ui" ) @@ -27,6 +30,7 @@ var homeWords = []prompt.Suggestion{ {Label: "exit", Detail: "Leave vf (or ctrl-d)"}, {Label: "clear", Detail: "Clear the screen"}, {Label: "more", Detail: "Show the rest of folded output (or ctrl-o)"}, + {Label: "use", Detail: "Show or change the current workspace and project"}, } // homeKeys are keys that run a prompt word on an empty line. @@ -65,6 +69,8 @@ func runHome(cmd *cobra.Command) error { func runPrompt(cmd *cobra.Command, u *ui.UI, out io.Writer, state signIn) error { inPrompt = true defer func() { inPrompt = false }() + session.Start() // what later lines use when they need one (internal/session) + defer session.Stop() complete := prompt.Commands(cmd.Root(), homeWords) histFile := historyPath() @@ -78,7 +84,7 @@ func runPrompt(cmd *cobra.Command, u *ui.UI, out io.Writer, state signIn) error line, ok, err := prompt.Read(prompt.Options{ UI: u, In: os.Stdin, Out: out, Width: ui.TerminalWidth(out), Complete: complete, History: history, Placeholder: placeholder, - Keys: homeKeys, + Keys: homeKeys, Context: session.Label(), }) if err != nil || !ok { return err @@ -118,6 +124,10 @@ func runPrompt(cmd *cobra.Command, u *ui.UI, out io.Writer, state signIn) error continue } saveHistory(histFile, line) + if args[0] == "use" { + use(cmd, u, args[1:]) + continue + } runLine(u, args) state = signInState(cmd) // a line may have signed in or out } @@ -161,6 +171,62 @@ func runLine(u *ui.UI, args []string) { } } +// useLevels are the words `use` takes, for the levels it can pick. +var useLevels = map[string]string{ + "organization": "organization-id", + "workspace": "workspace-id", + "project": "project-id", + "environment": "environment-alias", +} + +// use shows the current workspace and project, picks a new one, or clears +// them: `use`, `use project`, `use clear`. +func use(cmd *cobra.Command, u *ui.UI, args []string) { + switch { + case len(args) == 0: + showCurrent(u) + case len(args) == 1 && (args[0] == "clear" || args[0] == "none" || args[0] == "--clear"): + session.Clear("") + fmt.Fprintln(os.Stderr, u.Status(ui.StatusDone, "Nothing is current now: commands ask again")) + case len(args) == 1 && useLevels[args[0]] != "": + output.ResetAgentMode() + it, err := interactive.PickCurrent(cmd, useLevels[args[0]]) + switch { + case err != nil && (errors.Is(err, huh.ErrUserAborted) || errors.Is(err, context.Canceled)): + fmt.Fprintln(os.Stderr, u.Status(ui.StatusFailed, "Canceled")) + case err != nil: + _ = renderError(cmd, err) + case it.Value != "": + fmt.Fprintln(os.Stderr, u.Status(ui.StatusDone, "Using "+args[0]+" "+it.Name+" from now on")) + } + default: + fmt.Fprintln(os.Stderr, u.Status(ui.StatusFailed, "use takes workspace, project, environment, organization or clear")) + } +} + +// showCurrent lists what is current, broadest first. +func showCurrent(u *ui.UI) { + var rows []string + for _, flag := range session.Levels { + if it, ok := session.Get(flag); ok { + row := fmt.Sprintf(" %-12s %s", session.Nouns[flag], it.Name) + if it.Name != it.Value { + row += " " + u.Muted(it.Value) + } + rows = append(rows, row) + } + } + if len(rows) == 0 { + fmt.Fprintln(os.Stderr, u.Muted("Nothing is current yet. Create or pick a workspace or project, and later commands use it; or ")+u.Accent("use project")+u.Muted(" to pick one now.")) + return + } + fmt.Fprintln(os.Stderr, u.Bold("Current:")) + for _, r := range rows { + fmt.Fprintln(os.Stderr, r) + } + fmt.Fprintln(os.Stderr, u.Muted("Commands that need one use these. ")+u.Accent("use project")+u.Muted(" changes the project, ")+u.Accent("use clear")+u.Muted(" drops them.")) +} + // foldLines is how many lines of a result show before the rest folds away: // the terminal's height, less room for the line's echo, the fold line and // the prompt box under them, and never fewer than ten. diff --git a/internal/interactive/pickers.go b/internal/interactive/pickers.go index a92c188..9cb71e0 100644 --- a/internal/interactive/pickers.go +++ b/internal/interactive/pickers.go @@ -22,6 +22,7 @@ import ( "github.com/spf13/cobra" "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/session" "github.com/voiceflow/cli/internal/ui" ) @@ -62,6 +63,10 @@ type picking struct { out io.Writer // status lines: stderr bound map[string]bool picked map[string]string + names map[string]string // what was picked is called, for the context + // purpose describes a list picked for its own sake (`use project`), + // rather than to fill a flag. + purpose string // choose shows a list and ask an input, each in its own form; tests // replace them. @@ -72,9 +77,41 @@ type picking struct { // pickRequired fills the required fields vf can look up, each from a list, // and returns the rest for the form to ask as before. func pickRequired(cmd *cobra.Command, required []fieldInfo) ([]fieldInfo, error) { - p := &picking{cmd: cmd, u: output.UI(cmd, os.Stderr), out: os.Stderr, - bound: map[string]bool{}, picked: map[string]string{}, choose: chooseInForm, ask: askInForm} - return p.fill(required) + return newPicking(cmd).fill(required) +} + +func newPicking(cmd *cobra.Command) *picking { + return &picking{cmd: cmd, u: output.UI(cmd, os.Stderr), out: os.Stderr, + bound: map[string]bool{}, picked: map[string]string{}, names: map[string]string{}, + choose: chooseInForm, ask: askInForm} +} + +// PickCurrent lists flag's values, lets the person choose one, and makes it +// current in the home prompt's context (internal/session): `use project`. +// What it needs comes from the context, or is picked first. The Item is +// empty when nothing was picked. +func PickCurrent(cmd *cobra.Command, flag string) (session.Item, error) { + picker, ok := pickers[flag] + if !ok { + return session.Item{}, fmt.Errorf("vf can't list %s values", flag) + } + p := newPicking(cmd) + p.purpose = "to make it current" + needs := map[string]string{} + for _, n := range picker.Needs { + v, ok, err := p.resolve(n) + if err != nil || !ok { + return session.Item{}, err + } + needs[n] = v + } + v, err := p.pick(flag, picker, needs) + if err != nil || v == "" { + return session.Item{}, err + } + session.Set(flag, v, p.names[flag]) + it, _ := session.Get(flag) + return it, nil } func (p *picking) fill(required []fieldInfo) ([]fieldInfo, error) { @@ -112,6 +149,12 @@ func (p *picking) resolve(flag string) (value string, ok bool, err error) { return f.Value.String(), true, nil } picker := pickers[flag] + // The home prompt's current one, unless the command changes or removes + // what it picks: then the list asks, with the current one first. + if cur, ok := session.Get(flag); ok && !(p.bound[flag] && changesWhatItPicks(p.cmd)) { + fmt.Fprintln(p.out, p.u.Status(ui.StatusDone, "Using "+describe(picker.Noun, cur)+", the current one")) + return p.set(flag, cur.Value) + } needs := map[string]string{} for _, n := range picker.Needs { v, ok, err := p.resolve(n) @@ -128,6 +171,12 @@ func (p *picking) resolve(flag string) (value string, ok bool, err error) { if err != nil { return "", false, err } + session.Set(flag, v, p.names[flag]) // what you pick becomes current + return p.set(flag, v) +} + +// set records v as flag's value, and sets the flag when the command has it. +func (p *picking) set(flag, v string) (string, bool, error) { p.picked[flag] = v if v != "" && p.bound[flag] { if err := p.cmd.Flags().Set(flag, v); err != nil { @@ -137,16 +186,34 @@ func (p *picking) resolve(flag string) (value string, ok bool, err error) { return v, v != "", nil } +// describe is "project Help bot (p1)", or "project p1" when vf knows no name. +func describe(noun string, it session.Item) string { + if it.Name == "" || it.Name == it.Value { + return noun + " " + it.Value + } + return noun + " " + it.Name + " (" + it.Value + ")" +} + // pick lists flag's values and lets the person choose one. A single value is // taken without asking, and said so, unless the command changes or removes // the thing picked: deleting your only project still asks which. A list that // fails or comes back empty falls back to typing the ID. func (p *picking) pick(flag string, picker Picker, needs map[string]string) (string, error) { + if p.names == nil { + p.names = map[string]string{} + } ctx := p.cmd.Context() if ctx == nil { ctx = context.Background() } choices, err := picker.List(ctx, p.cmd, needs) + if cur, ok := session.Get(flag); ok && cur.Name == cur.Value { + for _, c := range choices { // name a current one known only by ID + if c.Value == cur.Value { + session.Set(flag, c.Value, c.Name) + } + } + } switch { case err != nil: fmt.Fprintln(p.out, p.u.Status(ui.StatusWarn, "Couldn't list your "+picker.Plural+": "+output.ShortReason(p.cmd, err))) @@ -158,15 +225,23 @@ func (p *picking) pick(flag string, picker Picker, needs map[string]string) (str c := choices[0] fmt.Fprintln(p.out, p.u.Status(ui.StatusDone, "Using "+picker.Noun+" "+c.Name+" ("+c.Value+"), the only one")) savePick(flag, c.Value) + p.names[flag] = c.Name return c.Value, nil } - choices = lastPickFirst(choices, lastPick(flag)) + first := lastPick(flag) + if cur, ok := session.Get(flag); ok { + first = cur.Value // the current one, for a command that changes it + } + choices = lastPickFirst(choices, first) value := choices[0].Value desc := "/ to filter · enter to pick" - if p.bound[flag] { + switch { + case p.purpose != "": + desc = p.purpose + " · " + desc + case p.bound[flag]: desc = "--" + flag + " · " + desc - } else { + default: desc = "to find the " + strings.Join(boundNouns(p), " and ") + " · " + desc } if err := p.choose(title(picker.Noun), desc, optionsFor(choices), &value); err != nil { @@ -176,6 +251,11 @@ func (p *picking) pick(flag string, picker Picker, needs map[string]string) (str return p.typeID(flag, picker) } savePick(flag, value) + for _, c := range choices { + if c.Value == value { + p.names[flag] = c.Name + } + } return value, nil } @@ -188,7 +268,8 @@ func (p *picking) typeID(flag string, picker Picker) (string, error) { return strings.TrimSpace(value), nil } -func chooseInForm(title, desc string, options []huh.Option[string], value *string) error { +// chooseInForm is a var so tests can answer it. +var chooseInForm = func(title, desc string, options []huh.Option[string], value *string) error { return runField(huh.NewSelect[string](). Title(title). Description(desc). diff --git a/internal/interactive/pickers_test.go b/internal/interactive/pickers_test.go index 02153c6..d5e794f 100644 --- a/internal/interactive/pickers_test.go +++ b/internal/interactive/pickers_test.go @@ -15,6 +15,8 @@ import ( "github.com/charmbracelet/huh" "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/session" "github.com/voiceflow/cli/internal/ui" ) @@ -45,9 +47,9 @@ func (f *fakePicker) register(flag, noun string, needs ...string) *fakePicker { return f } -// session is a picking for a command named name with the given string flags, +// pickSession is a picking for a command named name with the given string flags, // whose lists pick choose(title) and whose inputs type typed. -type session struct { +type pickSession struct { *picking out *bytes.Buffer shown []string // titles of the lists shown, in order @@ -56,12 +58,12 @@ type session struct { typing string } -func newSession(name string, flags ...string) *session { +func newSession(name string, flags ...string) *pickSession { cmd := &cobra.Command{Use: name} for _, f := range flags { cmd.Flags().String(f, "", "") } - s := &session{out: &bytes.Buffer{}, picks: map[string]string{}} + s := &pickSession{out: &bytes.Buffer{}, picks: map[string]string{}} s.picking = &picking{cmd: cmd, u: ui.New(io.Discard, ui.Options{Decorate: true}), out: s.out, bound: map[string]bool{}, picked: map[string]string{}, choose: func(title, _ string, options []huh.Option[string], value *string) error { @@ -95,7 +97,7 @@ func names(fs []fieldInfo) []string { return out } -func flag(s *session, name string) string { return s.cmd.Flags().Lookup(name).Value.String() } +func flag(s *pickSession, name string) string { return s.cmd.Flags().Lookup(name).Value.String() } // environment publish needs an environment and a project. The project needs a // workspace, which publish has no flag for: it is picked on the way, and @@ -238,3 +240,91 @@ func TestOptionsLineUpAndEndWithTypingAnID(t *testing.T) { t.Errorf("details should line up: %q / %q", opts[0].Key, opts[1].Key) } } + +// In the home prompt what you pick becomes current, and the next command +// uses it without asking, and says so. +func TestThePromptsCurrentOneIsUsedAndPicksBecomeCurrent(t *testing.T) { + isolatePicks(t) + session.Start() + t.Cleanup(session.Stop) + (&fakePicker{choices: []Choice{{Value: "w1", Name: "Acme"}, {Value: "w2", Name: "Support"}}}).register("workspace-id", "workspace") + projects := (&fakePicker{choices: []Choice{{Value: "p1", Name: "Bot A"}, {Value: "p2", Name: "Bot B"}}}).register("project-id", "project", "workspace-id") + + s := newSession("get", "project-id") + s.picks["Workspace"], s.picks["Project"] = "w2", "p2" + if _, err := s.fill(fields("project-id")); err != nil { + t.Fatal(err) + } + if got := session.Label(); got != "workspace Support › project Bot B" { + t.Errorf("picks should become current, got %q", got) + } + + next := newSession("get", "project-id") + if _, err := next.fill(fields("project-id")); err != nil { + t.Fatal(err) + } + if len(next.shown) != 0 || flag(next, "project-id") != "p2" || len(projects.calls) != 1 { + t.Errorf("the current project should be used without a list: shown %q, flag %q", next.shown, flag(next, "project-id")) + } + if !strings.Contains(next.out.String(), "Using project Bot B (p2), the current one") { + t.Errorf("and said so, got %q", next.out.String()) + } + + // A command that needs only the workspace takes the current one too. + envs := newSession("list", "workspace-id") + if _, err := envs.fill(fields("workspace-id")); err != nil { + t.Fatal(err) + } + if flag(envs, "workspace-id") != "w2" || len(envs.shown) != 0 { + t.Errorf("current workspace: flag %q, shown %q", flag(envs, "workspace-id"), envs.shown) + } +} + +// Deleting asks even with a current one: the list shows, the current one +// first, so Enter takes it but it is never taken unseen. +func TestDeletingAsksWithTheCurrentOneFirst(t *testing.T) { + isolatePicks(t) + session.Start() + t.Cleanup(session.Stop) + (&fakePicker{choices: []Choice{{Value: "p1", Name: "Bot A"}, {Value: "p2", Name: "Bot B"}}}).register("project-id", "project") + session.Set("project-id", "p2", "Bot B") + + s := newSession("delete", "project-id") + var first string + s.choose = func(title, _ string, options []huh.Option[string], value *string) error { + s.shown = append(s.shown, title) + first = *value + return nil + } + if _, err := s.fill(fields("project-id")); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(s.shown, []string{"Project"}) || first != "p2" || flag(s, "project-id") != "p2" { + t.Errorf("delete should ask, starting on the current one: shown %q, first %q, flag %q", s.shown, first, flag(s, "project-id")) + } +} + +// `use project` picks a project to make current, even when one is. +func TestPickCurrentPicksAgain(t *testing.T) { + isolatePicks(t) + session.Start() + t.Cleanup(session.Stop) + (&fakePicker{choices: []Choice{{Value: "p1", Name: "Bot A"}, {Value: "p2", Name: "Bot B"}}}).register("project-id", "project") + session.Set("project-id", "p1", "Bot A") + saved := chooseInForm + t.Cleanup(func() { chooseInForm = saved }) + chooseInForm = func(_, desc string, _ []huh.Option[string], value *string) error { + if !strings.HasPrefix(desc, "to make it current") { + t.Errorf("desc %q", desc) + } + *value = "p2" + return nil + } + it, err := PickCurrent(&cobra.Command{Use: "vf"}, "project-id") + if err != nil || it != (session.Item{Value: "p2", Name: "Bot B"}) { + t.Errorf("got %+v, %v", it, err) + } + if _, err := PickCurrent(&cobra.Command{Use: "vf"}, "nosuch-id"); err == nil { + t.Error("a flag with no list is an error") + } +} diff --git a/internal/output/created.go b/internal/output/created.go new file mode 100644 index 0000000..7341897 --- /dev/null +++ b/internal/output/created.go @@ -0,0 +1,209 @@ +// This file is not generated by Speakeasy. It finishes a command that made +// or removed something, the way the best CLIs do: a line saying what was +// made, the result, then what to do next. In the home prompt what was made +// also becomes current (internal/session), so the next command uses it +// without asking: +// +// ✓ Created project Help bot (p1) in workspace Acme +// project: +// id: p1 +// … +// Next: +// vf agent read-instructions read its agent's instructions +// vf environment list its environments +// Help bot is now your current project: later commands use it. 'use' changes it. +// +// The lines are status, on stderr, and only for a person reading pretty +// output: JSON, --jq, agent mode and a pipe get the result alone. + +package output + +import ( + "fmt" + "os" + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/session" + "github.com/voiceflow/cli/internal/ui" +) + +// contextFlags are the kinds of thing the home prompt can make current, by +// command group. +var contextFlags = map[string]string{ + "workspace": "workspace-id", + "project": "project-id", + "environment": "environment-alias", +} + +// afterResult runs as Result starts: it prints the line saying what was +// made, and returns what prints once the result has. Result defers the +// returned func ahead of the fold, so it runs after the result is out. +func afterResult(cmd *cobra.Command, res interface{}) func() { + noop := func() {} + if cmd == nil || cmd.Parent() == nil { + return noop + } + switch cmd.Name() { + case "delete": + forgetDeleted(cmd) + return noop + case "create", "clone", "duplicate": + default: + return noop + } + group := cmd.Parent().Name() + obj := createdObject(extractResultContent(res)) + id := firstString(obj, "id", "alias") + if id == "" { + return noop // a dry run, or a response vf can't read a thing from + } + name := firstString(obj, "name") + remember(group, id, name, obj) + if !announces(cmd) { + return noop + } + + u := UI(cmd, os.Stderr) + what := group + " " + id + if name != "" && name != id { + what = group + " " + name + " (" + id + ")" + } + fmt.Fprintln(os.Stderr, u.Status(ui.StatusDone, "Created "+what+within(obj))) + return func() { + tips := nextSteps(cmd, group, id) + if len(tips) > 0 { + fmt.Fprintln(os.Stderr, u.Bold("Next:")) + for _, row := range u.Tips(tips, ui.TerminalWidth(os.Stderr)-2) { + fmt.Fprintln(os.Stderr, " "+row) + } + } + if cur, ok := session.Get(contextFlags[group]); ok && cur.Value == id { + call := cur.Name + if call == "" { + call = id + } + fmt.Fprintln(os.Stderr, u.Muted(call+" is now your current "+group+": later commands use it. ")+u.Accent("use")+u.Muted(" changes it.")) + } + } +} + +// announces is whether a person is reading pretty output, so the lines +// around the result help rather than get in the way. +func announces(cmd *cobra.Command) bool { + jq, _ := cmd.Flags().GetString("jq") + return jq == "" && resolveOutputFormat(cmd) == "pretty" && !IsAgentMode() && UI(cmd, os.Stderr).Decorated() +} + +// createdObject is the thing a create returned: the response itself, or +// the one object it wraps ({"project": {...}}). +func createdObject(content interface{}) map[string]interface{} { + v, err := jsonValue(content) + m, ok := v.(map[string]interface{}) + if err != nil || !ok { + return nil + } + if firstString(m, "id", "alias") != "" || len(m) != 1 { + return m + } + for _, inner := range m { + if obj, ok := inner.(map[string]interface{}); ok { + return obj + } + } + return m +} + +// remember makes what was made current in the home prompt, with what it +// belongs to: a new project's workspace is current too. +func remember(group, id, name string, obj map[string]interface{}) { + flag, ok := contextFlags[group] + if !ok || !session.Active() { + return + } + switch group { + case "workspace": + session.Set("organization-id", firstString(obj, "organizationID"), "") + case "project": + session.Set("workspace-id", firstString(obj, "workspaceID"), "") + } + session.Set(flag, id, name) +} + +// forgetDeleted drops a current thing the command just deleted. +func forgetDeleted(cmd *cobra.Command) { + for _, flag := range session.Levels { + f := cmd.Flags().Lookup(flag) + if f == nil || !f.Changed { + continue + } + if cur, ok := session.Get(flag); ok && cur.Value == f.Value.String() && contextFlags[cmd.Parent().Name()] == flag { + session.Clear(flag) + } + } +} + +// within is " in workspace Acme" for a thing made inside another one. +func within(obj map[string]interface{}) string { + for _, parent := range []struct{ field, flag string }{ + {"workspaceID", "workspace-id"}, {"projectID", "project-id"}, {"organizationID", "organization-id"}, + } { + id := firstString(obj, parent.field) + if id == "" { + continue + } + call := id + if cur, ok := session.Get(parent.flag); ok && cur.Value == id && cur.Name != "" && cur.Name != id { + call = cur.Name + } + return " in " + session.Nouns[parent.flag] + " " + call + } + return "" +} + +// nextSteps are the commands most likely to come next. In the home prompt +// they leave out the IDs the context fills in; elsewhere they carry them. +func nextSteps(cmd *cobra.Command, group, id string) []ui.Tip { + short := session.Active() + with := func(c, flags string) string { + if short { + return c + } + return c + " " + flags + } + switch group { + case "workspace": + return []ui.Tip{ + {Command: with("vf project create", "--workspace-id "+id+" --name "), Does: "add a project to it"}, + {Command: with("vf workspace get", "--workspace-id "+id), Does: "see it"}, + } + case "project": + return []ui.Tip{ + {Command: with("vf agent read-instructions", "--project-id "+id+" --environment-alias "), Does: "read its agent's instructions"}, + {Command: with("vf environment list", "--project-id "+id), Does: "its environments"}, + {Command: with("vf project get", "--project-id "+id), Does: "see it"}, + } + } + var tips []ui.Tip + idFlag := group + "-id" + for _, sibling := range cmd.Parent().Commands() { + switch { + case sibling.Name() == "get" && sibling.Flags().Lookup(idFlag) != nil: + tips = append(tips, ui.Tip{Command: sibling.CommandPath() + " --" + idFlag + " " + id, Does: "see it"}) + case sibling.Name() == "list": + tips = append(tips, ui.Tip{Command: sibling.CommandPath(), Does: "list them"}) + } + } + return tips +} + +// firstString is the first of keys that obj has as a non-empty string. +func firstString(obj map[string]interface{}, keys ...string) string { + for _, k := range keys { + if s, ok := obj[k].(string); ok && strings.TrimSpace(s) != "" { + return s + } + } + return "" +} diff --git a/internal/output/created_test.go b/internal/output/created_test.go new file mode 100644 index 0000000..3962c70 --- /dev/null +++ b/internal/output/created_test.go @@ -0,0 +1,119 @@ +// This file is not generated by Speakeasy. It covers created.go. + +package output + +import ( + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/session" +) + +// group is 'vf ' with create, get, list and delete under it. +func group(name string) map[string]*cobra.Command { + root := &cobra.Command{Use: "vf"} + g := &cobra.Command{Use: name} + root.AddCommand(g) + cmds := map[string]*cobra.Command{} + for _, verb := range []string{"create", "get", "list", "delete"} { + c := &cobra.Command{Use: verb, RunE: func(*cobra.Command, []string) error { return nil }} + c.Flags().String(name+"-id", "", "") + c.Flags().String("jq", "", "") + c.Flags().String("output-format", "pretty", "") + g.AddCommand(c) + cmds[verb] = c + } + return cmds +} + +func projectCreated(id, name, workspace string) operations.StableProjectControllerCreateResponse { + return operations.StableProjectControllerCreateResponse{StableProjectResponse: &components.StableProjectResponse{ + Project: components.StableProject{ID: id, Name: name, WorkspaceID: workspace}, + }} +} + +func TestACreatedProjectBecomesCurrentInThePrompt(t *testing.T) { + session.Start() + t.Cleanup(session.Stop) + session.Set("workspace-id", "w1", "Acme") + cmds := group("project") + + afterResult(cmds["create"], projectCreated("p1", "Help bot", "w1"))() + if got := session.Label(); got != "workspace Acme › project Help bot" { + t.Errorf("a new project and its workspace should be current, got %q", got) + } + + // A project made in another workspace moves the context there. + afterResult(cmds["create"], projectCreated("p2", "Lab bot", "w9"))() + if got := session.Label(); got != "workspace w9 › project Lab bot" { + t.Errorf("got %q", got) + } + + // Deleting the current project forgets it; deleting another doesn't. + del := cmds["delete"] + _ = del.Flags().Set("project-id", "p1") + afterResult(del, nil)() + if _, ok := session.Get("project-id"); !ok { + t.Error("deleting another project keeps the current one") + } + _ = del.Flags().Set("project-id", "p2") + afterResult(del, nil)() + if _, ok := session.Get("project-id"); ok { + t.Error("deleting the current project forgets it") + } + if _, ok := session.Get("workspace-id"); !ok { + t.Error("but not its workspace") + } +} + +func TestOutsideThePromptNothingBecomesCurrent(t *testing.T) { + session.Stop() + afterResult(group("project")["create"], projectCreated("p1", "Help bot", "w1"))() + if session.Label() != "" { + t.Error("a one-shot create keeps no context") + } +} + +func TestCreatedObjectUnwrapsTheResponse(t *testing.T) { + obj := createdObject(extractResultContent(projectCreated("p1", "Help bot", "w1"))) + if firstString(obj, "id") != "p1" || firstString(obj, "name") != "Help bot" || within(obj) != " in workspace w1" { + t.Errorf("got %v, within %q", obj, within(obj)) + } + if obj := createdObject(map[string]interface{}{"id": "v1", "name": "x"}); firstString(obj, "id") != "v1" { + t.Errorf("a bare object is the thing itself: %v", obj) + } + if obj := createdObject(nil); firstString(obj, "id") != "" { + t.Errorf("nothing: %v", obj) + } +} + +// In the prompt the steps leave out what the context fills in; elsewhere +// they carry the IDs, so they paste and run. +func TestNextStepsCarryIDsOutsideThePrompt(t *testing.T) { + cmds := group("project") + session.Stop() + long := nextSteps(cmds["create"], "project", "p1") + if len(long) != 3 || long[1].Command != "vf environment list --project-id p1" { + t.Errorf("one-shot: %+v", long) + } + session.Start() + t.Cleanup(session.Stop) + short := nextSteps(cmds["create"], "project", "p1") + if short[1].Command != "vf environment list" { + t.Errorf("in the prompt: %+v", short) + } + + variable := group("variable") + tips := nextSteps(variable["create"], "variable", "v1") + var got []string + for _, tip := range tips { + got = append(got, tip.Command) + } + if strings.Join(got, "; ") != "vf variable get --variable-id v1; vf variable list" { + t.Errorf("any other group: get and list, got %q", got) + } +} diff --git a/internal/output/output.go b/internal/output/output.go index 3e8d385..845fe1e 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -149,6 +149,7 @@ func ValidateGlobalServerName(cmd *cobra.Command, validNames map[string]string) // Result formats and outputs the response based on the --output-format flag. func Result(cmd *cobra.Command, res interface{}) error { + defer afterResult(cmd, res)() // created.go: what was made, then what to do next out, done := ResultWriter(cmd) // fold.go: folds a long result inside the home prompt defer done() colorFlag, _ := flagutil.GetStringFlag(cmd, "color") diff --git a/internal/prompt/prompt.go b/internal/prompt/prompt.go index d0da95a..7aab2d4 100644 --- a/internal/prompt/prompt.go +++ b/internal/prompt/prompt.go @@ -28,6 +28,9 @@ type Options struct { // Keys enter a word of their own when pressed on an empty line, as if // it were typed and run: {"ctrl+o": "more"}. Keys map[string]string + // Context is set into the box's top border: what the next command uses + // when it needs one and none is given (internal/session). + Context string } // maxRows is how many suggestions the menu shows at once; it scrolls with @@ -56,6 +59,7 @@ type model struct { width int complete Completer keys map[string]string + context string // set into the top border history []string histAt int // len(history) while editing a new line @@ -86,7 +90,7 @@ func newModel(o Options) *model { } in.Cursor.SetMode(cursor.CursorStatic) in.Focus() - m := &model{ui: o.UI, input: in, width: o.Width, complete: o.Complete, keys: o.Keys, history: o.History, histAt: len(o.History)} + m := &model{ui: o.UI, input: in, width: o.Width, complete: o.Complete, keys: o.Keys, context: o.Context, history: o.History, histAt: len(o.History)} m.resize() return m } @@ -435,7 +439,7 @@ func (m *model) View() string { row += strings.Repeat(" ", pad) } lines := []string{ - u.Subtle("╭" + strings.Repeat("─", w-2) + "╮"), + m.topBorder(w), u.Subtle("│") + " " + ansi.Truncate(row, inner, "") + " " + u.Subtle("│"), u.Subtle("╰" + strings.Repeat("─", w-2) + "╯"), } @@ -453,6 +457,18 @@ func (m *model) View() string { return strings.Join(lines, "\n") } +// topBorder is the box's top edge, with the context set into it the way the +// banner sets its title: ╭─ workspace Acme › project Help bot ───╮. +func (m *model) topBorder(w int) string { + u := m.ui + label := ansi.Truncate(m.context, max(w-6, 0), "…") + if label == "" { + return u.Subtle("╭" + strings.Repeat("─", w-2) + "╮") + } + dashes := w - 5 - lipgloss.Width(label) + return u.Subtle("╭─ ") + label + u.Subtle(" "+strings.Repeat("─", max(dashes, 0))+"╮") +} + // footer is the one muted line under the box when no menu is open: how to // find commands while the line is empty, how to run it once it is not. func (m *model) footer() string { diff --git a/internal/prompt/prompt_test.go b/internal/prompt/prompt_test.go index 7dd7d65..ee80da6 100644 --- a/internal/prompt/prompt_test.go +++ b/internal/prompt/prompt_test.go @@ -471,3 +471,24 @@ func TestAKeyRunsItsWordOnAnEmptyLine(t *testing.T) { t.Errorf("with text on the line the key does nothing: done=%v %q", m.done, m.input.Value()) } } + +// The context sits in the box's top border, as the banner's title does in +// its own, and the border keeps its width. +func TestTheContextIsSetIntoTheTopBorder(t *testing.T) { + m := testModel() + m.context = "workspace Acme › project Help bot" + top := strings.SplitN(m.View(), "\n", 2)[0] + if !strings.HasPrefix(top, "╭─ workspace Acme › project Help bot ─") || !strings.HasSuffix(top, "╮") { + t.Errorf("top border: %q", top) + } + if w := lipgloss.Width(top); w != m.boxWidth() { + t.Errorf("border width %d, box %d", w, m.boxWidth()) + } + m.context = strings.Repeat("project x ", 20) + if top := strings.SplitN(m.View(), "\n", 2)[0]; lipgloss.Width(top) != m.boxWidth() || !strings.Contains(top, "…") { + t.Errorf("a long context is cut to fit: %q", top) + } + if top := strings.SplitN(testModel().View(), "\n", 2)[0]; strings.Contains(top, "─ ") { + t.Errorf("no context, a plain border: %q", top) + } +} diff --git a/internal/session/session.go b/internal/session/session.go new file mode 100644 index 0000000..4e6f409 --- /dev/null +++ b/internal/session/session.go @@ -0,0 +1,115 @@ +// This file is not generated by Speakeasy. It keeps the home prompt's +// current organization, workspace, project and environment: what the next +// command in the same prompt uses when it needs one and none is given. +// +// The best CLIs leave you at the prompt after a command, not inside a mode, +// and carry what you were working on forward: gcloud's current project, +// kubectl's context, psql's \c. Here the context starts empty with each +// home prompt and ends with it. A one-shot `vf …` command and agent mode +// never see it, so a script cannot pick up a project from an earlier line. + +package session + +import "strings" + +// Item is one level of the context: an ID and what to call it. +type Item struct { + Value string // the ID, or an environment's alias + Name string // what a person calls it; the ID when vf knows no name +} + +// Levels are the flags the context holds, broadest first. Changing one +// clears the narrower ones: a project from another workspace is not current +// in this one. +var Levels = []string{"organization-id", "workspace-id", "project-id", "environment-alias"} + +// Nouns name each level for a person. +var Nouns = map[string]string{ + "organization-id": "organization", + "workspace-id": "workspace", + "project-id": "project", + "environment-alias": "environment", +} + +var ( + active bool + items = map[string]Item{} +) + +// Start begins an empty context; the home prompt calls it as it opens. +func Start() { active, items = true, map[string]Item{} } + +// Stop ends the context; the home prompt calls it as it closes. +func Stop() { active, items = false, map[string]Item{} } + +// Active is whether a home prompt is keeping a context. +func Active() bool { return active } + +// Get is flag's current value, if the context has one. +func Get(flag string) (Item, bool) { + it, ok := items[flag] + return it, ok && active +} + +// Set makes value current for flag, and clears the narrower levels when it +// changes. name may be "", which keeps a name already known for value. +// Nothing happens outside a home prompt. +func Set(flag, value, name string) { + if !active || value == "" || level(flag) < 0 { + return + } + old, had := items[flag] + if name == "" { + name = value + if had && old.Value == value { + name = old.Name + } + } + if !had || old.Value != value { + for _, narrower := range Levels[level(flag)+1:] { + delete(items, narrower) + } + } + items[flag] = Item{Value: value, Name: name} +} + +// Clear drops flag, and the narrower levels with it; Clear("") drops all. +func Clear(flag string) { + if flag == "" { + items = map[string]Item{} + return + } + if i := level(flag); i >= 0 { + for _, f := range Levels[i:] { + delete(items, f) + } + } +} + +// Label is the context for the prompt's border, broadest first: +// "workspace Acme › project Help bot". An organization shows only when +// nothing narrower is current: it has no name of its own. +func Label() string { + if !active { + return "" + } + var parts []string + for _, f := range Levels[1:] { + if it, ok := items[f]; ok { + parts = append(parts, Nouns[f]+" "+it.Name) + } + } + if it, ok := items["organization-id"]; ok && len(parts) == 0 { + parts = append(parts, "organization "+it.Name) + } + return strings.Join(parts, " › ") +} + +func level(flag string) int { + for i, f := range Levels { + if f == flag { + return i + } + } + return -1 +} diff --git a/internal/session/session_test.go b/internal/session/session_test.go new file mode 100644 index 0000000..a243ba5 --- /dev/null +++ b/internal/session/session_test.go @@ -0,0 +1,78 @@ +// This file is not generated by Speakeasy. It covers session.go. + +package session + +import "testing" + +func TestOutsideTheHomePromptNothingIsKept(t *testing.T) { + Stop() + Set("project-id", "p1", "Help bot") + if _, ok := Get("project-id"); ok || Label() != "" { + t.Error("a one-shot command keeps no context") + } +} + +func TestChangingALevelClearsTheNarrowerOnes(t *testing.T) { + Start() + t.Cleanup(Stop) + Set("workspace-id", "w1", "Acme") + Set("project-id", "p1", "Help bot") + Set("environment-alias", "production", "Production") + if got := Label(); got != "workspace Acme › project Help bot › environment Production" { + t.Errorf("label: %q", got) + } + + Set("workspace-id", "w1", "") // the same workspace: nothing changes, the name stays + if it, _ := Get("workspace-id"); it.Name != "Acme" { + t.Errorf("setting the same ID without a name keeps the name, got %q", it.Name) + } + if _, ok := Get("project-id"); !ok { + t.Error("the same workspace keeps its project") + } + + Set("workspace-id", "w2", "") // another workspace: its projects aren't these + if _, ok := Get("project-id"); ok { + t.Error("a project from another workspace isn't current") + } + if _, ok := Get("environment-alias"); ok { + t.Error("nor its environment") + } + if got := Label(); got != "workspace w2" { + t.Errorf("a workspace with no known name shows its ID, got %q", got) + } +} + +func TestOrganizationShowsOnlyAlone(t *testing.T) { + Start() + t.Cleanup(Stop) + Set("organization-id", "o1", "") + if got := Label(); got != "organization o1" { + t.Errorf("alone: %q", got) + } + Set("workspace-id", "w1", "Acme") + if got := Label(); got != "workspace Acme" { + t.Errorf("beside a workspace the organization adds nothing: %q", got) + } +} + +func TestClear(t *testing.T) { + Start() + t.Cleanup(Stop) + Set("workspace-id", "w1", "Acme") + Set("project-id", "p1", "Help bot") + Clear("project-id") + if _, ok := Get("project-id"); ok { + t.Error("cleared") + } + if _, ok := Get("workspace-id"); !ok { + t.Error("clearing a project keeps its workspace") + } + Clear("") + if Label() != "" { + t.Error("Clear(\"\") drops everything") + } + Set("nosuch-id", "x", "") + if Label() != "" { + t.Error("only the four levels are kept") + } +} diff --git a/internal/ui/DESIGN.md b/internal/ui/DESIGN.md index 226917b..20d67d6 100644 --- a/internal/ui/DESIGN.md +++ b/internal/ui/DESIGN.md @@ -245,6 +245,48 @@ Build workflows: blocks, steps, branches and links workflow --help shows a command's flags ``` +### Current workspace and project + +The prompt keeps you at the prompt after a command, never inside a mode, and +carries what you were working on to the next line, as gcloud's current +project, kubectl's context and psql's `\c` do (`internal/session`): + +``` +✓ Created project Help bot (p1) in workspace Acme +project: + … +Next: + vf agent read-instructions read its agent's instructions + vf environment list its environments + vf project get see it +Help bot is now your current project: later commands use it. use changes it. + +╭─ workspace Acme › project Help bot ─────────────────────────────╮ +│ ❯ Try "workspace list" │ +╰─────────────────────────────────────────────────────────────────╯ +``` + +- **What becomes current:** what you create or pick, for the four levels + the pickers know (organization, workspace, project, environment). A new + project's workspace is current with it. Changing a level clears the + narrower ones: another workspace's project is not current here. Deleting + the current one forgets it. An ID passed as a flag is a one-off and + changes nothing. +- **How it's used:** a command that needs one and was not given it uses the + current one, with a status line (`✓ Using project Help bot (p1), the + current one`). A command that changes or removes what it picks still + shows the list, the current one first: deleting never happens unseen. +- **Always visible:** the box's top border shows it, broadest first. +- **`use`** shows it, `use project` (or workspace, environment, + organization) picks a new one, `use clear` drops it all. +- **Only in the prompt:** it starts empty with each prompt and ends with it. + A one-shot `vf …` and agent mode never see it, so a script cannot pick up + a project from an earlier line. +- **After a create**, anywhere pretty output reaches a person: a `✓ Created` + line, the result, then `Next:` steps. In the prompt the steps leave out + the IDs the context fills in; elsewhere they carry them, so they paste and + run. JSON, `--jq`, agent mode and a pipe get the result alone. + ## Pickers When a command needs an ID it was not given, at a terminal, the form lists From 4a1131246fdbfee970eabb284ff5dc0a33431692 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:06:34 -0500 Subject: [PATCH 10/30] feat(home): suggest the next command for what is current The empty prompt always suggested 'workspace list', even right after creating a project, where the useful next step is working in it. The placeholder now follows the context: 'agent read-instructions' with a current project (the first of a new project's next steps), 'project list' with a workspace, 'workspace list' with nothing, and 'auth login' signed out. Each runs as suggested: the context fills its IDs. --- internal/cli/home.go | 24 ++++++++++++++++++++---- internal/cli/home_test.go | 26 ++++++++++++++++++++++++++ internal/ui/DESIGN.md | 6 ++++-- 3 files changed, 50 insertions(+), 6 deletions(-) diff --git a/internal/cli/home.go b/internal/cli/home.go index cd19b77..acc36c4 100644 --- a/internal/cli/home.go +++ b/internal/cli/home.go @@ -76,10 +76,7 @@ func runPrompt(cmd *cobra.Command, u *ui.UI, out io.Writer, state signIn) error histFile := historyPath() history := loadHistory(histFile) // history.go: kept across sessions for { - placeholder := `Try "workspace list"` - if !state.signed { - placeholder = `Try "auth login"` - } + placeholder := placeholderFor(state) fmt.Fprintln(out) line, ok, err := prompt.Read(prompt.Options{ UI: u, In: os.Stdin, Out: out, Width: ui.TerminalWidth(out), @@ -171,6 +168,25 @@ func runLine(u *ui.UI, args []string) { } } +// placeholderFor is the faint suggestion in an empty prompt: the likely +// next command for what is current, narrowest first, so after creating a +// project it suggests working in it rather than listing workspaces again. +// Each runs with nothing more typed: the context fills its IDs. +func placeholderFor(state signIn) string { + if !state.signed { + return `Try "auth login"` + } + for _, s := range []struct{ flag, try string }{ + {"project-id", "agent read-instructions"}, // the first of a new project's next steps + {"workspace-id", "project list"}, + } { + if _, ok := session.Get(s.flag); ok { + return `Try "` + s.try + `"` + } + } + return `Try "workspace list"` +} + // useLevels are the words `use` takes, for the levels it can pick. var useLevels = map[string]string{ "organization": "organization-id", diff --git a/internal/cli/home_test.go b/internal/cli/home_test.go index 072d6ce..a3aa1d6 100644 --- a/internal/cli/home_test.go +++ b/internal/cli/home_test.go @@ -11,6 +11,7 @@ import ( "github.com/spf13/cobra" "github.com/voiceflow/cli/internal/config" + "github.com/voiceflow/cli/internal/session" "github.com/voiceflow/cli/internal/ui" "github.com/zalando/go-keyring" ) @@ -206,3 +207,28 @@ func TestEveryGroupHasADescription(t *testing.T) { } check(root) } + +// The empty prompt suggests the likely next command for what is current. +func TestThePlaceholderFollowsTheContext(t *testing.T) { + session.Start() + t.Cleanup(session.Stop) + signed := signIn{signed: true} + if got := placeholderFor(signIn{}); got != `Try "auth login"` { + t.Errorf("signed out: %q", got) + } + if got := placeholderFor(signed); got != `Try "workspace list"` { + t.Errorf("nothing current: %q", got) + } + session.Set("workspace-id", "w1", "Acme") + if got := placeholderFor(signed); got != `Try "project list"` { + t.Errorf("a workspace: %q", got) + } + session.Set("project-id", "p1", "Help bot") + if got := placeholderFor(signed); got != `Try "agent read-instructions"` { + t.Errorf("a project: %q", got) + } + session.Set("project-id", "p1", "Help bot") + if got := placeholderFor(signIn{}); got != `Try "auth login"` { + t.Errorf("signed out wins over the context: %q", got) + } +} diff --git a/internal/ui/DESIGN.md b/internal/ui/DESIGN.md index 20d67d6..d2fc746 100644 --- a/internal/ui/DESIGN.md +++ b/internal/ui/DESIGN.md @@ -146,8 +146,10 @@ What bare `vf` prints at a terminal (`internal/cli/home.go`, drawn by Under the banner, when stdin is a terminal and `--no-interactive` is not set, bare `vf` opens a prompt (`internal/prompt`, run by `internal/cli/home.go`). It reads a line, runs it as a vf command with its output inline, and comes back, -like Claude Code's and vfe's prompts. Signed out, the placeholder suggests -`auth login`. +like Claude Code's and vfe's prompts. The placeholder suggests the likely +next command: `auth login` signed out, then by what is current (below): +`agent read-instructions` with a project, `project list` with a workspace, +`workspace list` with nothing. ``` ╭──────────────────────────────────────────────────────────────────────────────╮ From e426421b6ff4f7a448ebefb8c2004a8e352e1be6 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:09:21 -0500 Subject: [PATCH 11/30] feat(home): make creating a project the default first step Signed in with nothing current, the empty prompt suggested 'workspace list'. It now suggests 'project create': making a project is the first thing a signed-in user does, and the picker finds its workspace. Signed out still suggests 'auth login'. --- internal/cli/home.go | 5 +++-- internal/cli/home_test.go | 4 ++-- internal/ui/DESIGN.md | 5 +++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/internal/cli/home.go b/internal/cli/home.go index acc36c4..c162962 100644 --- a/internal/cli/home.go +++ b/internal/cli/home.go @@ -171,7 +171,8 @@ func runLine(u *ui.UI, args []string) { // placeholderFor is the faint suggestion in an empty prompt: the likely // next command for what is current, narrowest first, so after creating a // project it suggests working in it rather than listing workspaces again. -// Each runs with nothing more typed: the context fills its IDs. +// Signed in with nothing current, the default is making a project. Each +// runs with nothing more typed: the context, or a picker, fills its IDs. func placeholderFor(state signIn) string { if !state.signed { return `Try "auth login"` @@ -184,7 +185,7 @@ func placeholderFor(state signIn) string { return `Try "` + s.try + `"` } } - return `Try "workspace list"` + return `Try "project create"` } // useLevels are the words `use` takes, for the levels it can pick. diff --git a/internal/cli/home_test.go b/internal/cli/home_test.go index a3aa1d6..ab935bc 100644 --- a/internal/cli/home_test.go +++ b/internal/cli/home_test.go @@ -216,8 +216,8 @@ func TestThePlaceholderFollowsTheContext(t *testing.T) { if got := placeholderFor(signIn{}); got != `Try "auth login"` { t.Errorf("signed out: %q", got) } - if got := placeholderFor(signed); got != `Try "workspace list"` { - t.Errorf("nothing current: %q", got) + if got := placeholderFor(signed); got != `Try "project create"` { + t.Errorf("signed in with nothing current, make a project: %q", got) } session.Set("workspace-id", "w1", "Acme") if got := placeholderFor(signed); got != `Try "project list"` { diff --git a/internal/ui/DESIGN.md b/internal/ui/DESIGN.md index d2fc746..bba523a 100644 --- a/internal/ui/DESIGN.md +++ b/internal/ui/DESIGN.md @@ -149,7 +149,8 @@ reads a line, runs it as a vf command with its output inline, and comes back, like Claude Code's and vfe's prompts. The placeholder suggests the likely next command: `auth login` signed out, then by what is current (below): `agent read-instructions` with a project, `project list` with a workspace, -`workspace list` with nothing. +and `project create` signed in with nothing current: making a project is +the default first step. ``` ╭──────────────────────────────────────────────────────────────────────────────╮ @@ -264,7 +265,7 @@ Next: Help bot is now your current project: later commands use it. use changes it. ╭─ workspace Acme › project Help bot ─────────────────────────────╮ -│ ❯ Try "workspace list" │ +│ ❯ Try "agent read-instructions" │ ╰─────────────────────────────────────────────────────────────────╯ ``` From 4eeba3af578789aeb45996bcb5c82cfeddfe805e Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:12:19 -0500 Subject: [PATCH 12/30] feat(home): lead with creating a project, in the banner and the prompt Making a project is now the default first step everywhere a signed-in person starts: the banner's "Get started" leads with 'vf project create' in place of 'vf workspace list', and the empty prompt suggests it with a workspace current, as it already did with nothing current. Once a project is current the prompt suggests working in it ('agent read-instructions'). --- internal/cli/home.go | 23 +++++++++-------------- internal/cli/home_test.go | 6 +++--- internal/ui/DESIGN.md | 12 ++++++------ 3 files changed, 18 insertions(+), 23 deletions(-) diff --git a/internal/cli/home.go b/internal/cli/home.go index c162962..1be0b54 100644 --- a/internal/cli/home.go +++ b/internal/cli/home.go @@ -169,21 +169,16 @@ func runLine(u *ui.UI, args []string) { } // placeholderFor is the faint suggestion in an empty prompt: the likely -// next command for what is current, narrowest first, so after creating a -// project it suggests working in it rather than listing workspaces again. -// Signed in with nothing current, the default is making a project. Each -// runs with nothing more typed: the context, or a picker, fills its IDs. +// next command. Signed in, the default is making a project; with a current +// project, it is working in it (the first of a new project's next steps). +// Each runs with nothing more typed: the context, or a picker, fills its +// IDs. func placeholderFor(state signIn) string { - if !state.signed { + switch _, project := session.Get("project-id"); { + case !state.signed: return `Try "auth login"` - } - for _, s := range []struct{ flag, try string }{ - {"project-id", "agent read-instructions"}, // the first of a new project's next steps - {"workspace-id", "project list"}, - } { - if _, ok := session.Get(s.flag); ok { - return `Try "` + s.try + `"` - } + case project: + return `Try "agent read-instructions"` } return `Try "project create"` } @@ -317,7 +312,7 @@ func signInState(cmd *cobra.Command) signIn { func homeBanner(s signIn) ui.Banner { start := []ui.Tip{ - {Command: "vf workspace list", Does: "your workspaces"}, + {Command: "vf project create", Does: "start a new project"}, {Command: "vf explore", Does: "browse every command"}, {Command: "vf docs search ", Does: "search the docs"}, } diff --git a/internal/cli/home_test.go b/internal/cli/home_test.go index ab935bc..a5b331e 100644 --- a/internal/cli/home_test.go +++ b/internal/cli/home_test.go @@ -158,7 +158,7 @@ func TestHomeBannerTipsFollowSignIn(t *testing.T) { if got := commands(signIn{signed: false}); !strings.Contains(got, "vf auth login") || !strings.Contains(got, "vf auth signup") { t.Errorf("signed out, the banner should offer sign-in first: %s", got) } - if got := commands(signIn{signed: true}); strings.Contains(got, "vf auth") || !strings.Contains(got, "vf workspace list") { + if got := commands(signIn{signed: true}); strings.Contains(got, "vf auth") || !strings.HasPrefix(got, "vf project create") { t.Errorf("signed in, the banner should offer work, not sign-in: %s", got) } } @@ -220,8 +220,8 @@ func TestThePlaceholderFollowsTheContext(t *testing.T) { t.Errorf("signed in with nothing current, make a project: %q", got) } session.Set("workspace-id", "w1", "Acme") - if got := placeholderFor(signed); got != `Try "project list"` { - t.Errorf("a workspace: %q", got) + if got := placeholderFor(signed); got != `Try "project create"` { + t.Errorf("a workspace alone: make a project in it, got %q", got) } session.Set("project-id", "p1", "Help bot") if got := placeholderFor(signed); got != `Try "agent read-instructions"` { diff --git a/internal/ui/DESIGN.md b/internal/ui/DESIGN.md index bba523a..0717bf9 100644 --- a/internal/ui/DESIGN.md +++ b/internal/ui/DESIGN.md @@ -111,8 +111,8 @@ What bare `vf` prints at a terminal (`internal/cli/home.go`, drawn by ╭─ Voiceflow CLI v0.350.0 ─────────────────────────────────────────────────────╮ │ │ │ _ __ _ Get started │ -│ /\ /\___ (_) ___ ___ / _| | _____ __ vf workspace list │ -│ \ \ / / _ \| |/ __/ _ \ |_| |/ _ \ \ /\ / / your workspaces │ +│ /\ /\___ (_) ___ ___ / _| | _____ __ vf project create │ +│ \ \ / / _ \| |/ __/ _ \ |_| |/ _ \ \ /\ / / start a new project │ │ \ V / (_) | | (_| __/ _| | (_) \ V V / vf explore │ │ \_/ \___/|_|\___\___|_| |_|\___/ \_/\_/ browse every command │ │ vf docs search │ @@ -130,7 +130,8 @@ What bare `vf` prints at a terminal (`internal/cli/home.go`, drawn by - **Left:** the creator-app wordmark in Accent (the same lines as vfe's banner and the browser console), then the sign-in line. - **Right:** a Bold heading per section; commands in Accent, what they do in - Muted. Signed out, "Get started" offers `vf auth login` and `vf auth signup` + Muted. Signed in, "Get started" leads with `vf project create`, the default + first step; signed out, it offers `vf auth login` and `vf auth signup` first. - **Sign-in** names the credential the next request would send, in the client's order: `--token`, `VF_TOKEN`, a browser session, then a token saved @@ -148,9 +149,8 @@ bare `vf` opens a prompt (`internal/prompt`, run by `internal/cli/home.go`). It reads a line, runs it as a vf command with its output inline, and comes back, like Claude Code's and vfe's prompts. The placeholder suggests the likely next command: `auth login` signed out, then by what is current (below): -`agent read-instructions` with a project, `project list` with a workspace, -and `project create` signed in with nothing current: making a project is -the default first step. +`project create` signed in, the default first step, and +`agent read-instructions` once a project is current. ``` ╭──────────────────────────────────────────────────────────────────────────────╮ From eafeca364cf7229fb7219a4deaba27c06ca5dd22 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:16:56 -0500 Subject: [PATCH 13/30] fix(interactive): offer optional fields only on commands that make or change something The form asked "Fill in N optional field(s)?" after the required ones on every command, reads included. 'agent read-instructions' with a current project and a lone environment filled both required fields itself, then stopped to ask whether to page with --offset and --limit: the one question it asked was about fields no one needed. Now only a command that makes or changes something (create, update, patch, add, set, replace, clone, duplicate, insert, link, move, split, reorder, arrange, assign, merge, publish, connect) offers them, where they matter: a description on create, the field to change on update, where every one is optional. Reads, lists, searches, deletes and runs never ask, and the header no longer counts optional fields it won't ask for. The flags are still there for whoever wants them. --- internal/interactive/interactive.go | 65 ++++++++++++++++++++-------- internal/interactive/pickers_test.go | 29 +++++++++++++ internal/ui/DESIGN.md | 6 +++ 3 files changed, 82 insertions(+), 18 deletions(-) diff --git a/internal/interactive/interactive.go b/internal/interactive/interactive.go index 91e5069..7a6ffe3 100644 --- a/internal/interactive/interactive.go +++ b/internal/interactive/interactive.go @@ -148,6 +148,49 @@ func formTheme() *huh.Theme { return &t } +// fieldsToAsk splits the flags with no value yet into the required ones and +// the optional ones the form offers. Only a command that makes or changes +// something offers optional fields: a description on create, the field to +// change on update (where every one is optional). A read never does: asking +// whether to page `agent read-instructions` with --offset and --limit only +// gets in the way, and the flags are there for whoever wants them. +func fieldsToAsk(cmd *cobra.Command, meta []flagutil.FlagMeta) (required, optional []fieldInfo) { + offers := offersOptional(cmd) + for _, m := range meta { + if isValueResolved(cmd, m) || (!m.Required && !offers) { + continue + } + field, binding := buildFormField(m) + info := fieldInfo{field: field, binding: binding, name: flagDisplayName(m)} + if m.Required { + required = append(required, info) + } else { + optional = append(optional, info) + } + } + return required, optional +} + +// writeVerbs start the names of commands that make or change something. +// Removing (delete, unlink…) and running (execute, send…) are not here: their +// optional fields have defaults that do the expected thing. +var writeVerbs = []string{ + "create", "update", "patch", "add", "set", "replace", "clone", "duplicate", + "insert", "link", "move", "split", "reorder", "arrange", "assign", "merge", "publish", "connect", +} + +// offersOptional is whether cmd makes or changes something: its name is a +// write verb, or starts with one and a dash (update-traffic-split, but not +// settings). +func offersOptional(cmd *cobra.Command) bool { + for _, verb := range writeVerbs { + if cmd.Name() == verb || strings.HasPrefix(cmd.Name(), verb+"-") { + return true + } + } + return false +} + // fieldInfo holds a built form field alongside its display name for the upcoming list. type fieldInfo struct { field huh.Field @@ -189,25 +232,11 @@ func printCommandHeader(cmd *cobra.Command, totalRequired, totalOptional int) { } // PromptAndSetFlags builds a huh form for unresolved required flags (one per form), -// then offers to prompt for optional flags too. Each field is shown in its own -// separate form to avoid multi-group rendering issues. +// then, for a command that makes or changes something, offers to prompt for +// optional flags too. Each field is shown in its own separate form to avoid +// multi-group rendering issues. func PromptAndSetFlags(cmd *cobra.Command, meta []flagutil.FlagMeta) error { - var required []fieldInfo - var optional []fieldInfo - - for _, m := range meta { - if isValueResolved(cmd, m) { - continue - } - - field, binding := buildFormField(m) - info := fieldInfo{field: field, binding: binding, name: flagDisplayName(m)} - if m.Required { - required = append(required, info) - } else { - optional = append(optional, info) - } - } + required, optional := fieldsToAsk(cmd, meta) // only a write offers optional fields if len(required) == 0 && len(optional) == 0 { return nil diff --git a/internal/interactive/pickers_test.go b/internal/interactive/pickers_test.go index d5e794f..944f51b 100644 --- a/internal/interactive/pickers_test.go +++ b/internal/interactive/pickers_test.go @@ -16,6 +16,7 @@ import ( "github.com/charmbracelet/huh" "github.com/spf13/cobra" + "github.com/voiceflow/cli/internal/flagutil" "github.com/voiceflow/cli/internal/session" "github.com/voiceflow/cli/internal/ui" ) @@ -328,3 +329,31 @@ func TestPickCurrentPicksAgain(t *testing.T) { t.Error("a flag with no list is an error") } } + +// Only a command that makes or changes something offers optional fields; a +// read asks for what it needs and nothing more. +func TestOnlyWritesOfferOptionalFields(t *testing.T) { + meta := []flagutil.FlagMeta{ + {FlagName: "project-id", FieldPath: "ProjectID", Kind: flagutil.FlagKindString, Required: true}, + {FlagName: "offset", FieldPath: "Offset", Kind: flagutil.FlagKindString}, + {FlagName: "limit", FieldPath: "Limit", Kind: flagutil.FlagKindString}, + } + ask := func(name string) (int, int) { + cmd := &cobra.Command{Use: name} + for _, m := range meta { + cmd.Flags().String(m.FlagName, "", "") + } + required, optional := fieldsToAsk(cmd, meta) + return len(required), len(optional) + } + for _, read := range []string{"read-instructions", "get", "list", "search-prompt", "execute", "delete", "settings"} { + if r, o := ask(read); r != 1 || o != 0 { + t.Errorf("%s: %d required, %d optional; a read offers no optional fields", read, r, o) + } + } + for _, write := range []string{"create", "update", "update-traffic-split", "patch-instructions", "set-value", "add-tool", "clone", "publish"} { + if r, o := ask(write); r != 1 || o != 2 { + t.Errorf("%s: %d required, %d optional; a write offers them", write, r, o) + } + } +} diff --git a/internal/ui/DESIGN.md b/internal/ui/DESIGN.md index 0717bf9..d28da7c 100644 --- a/internal/ui/DESIGN.md +++ b/internal/ui/DESIGN.md @@ -327,6 +327,12 @@ flag lists). `--no-interactive`. Agents and scripts get the error naming the flag, as before. While a list loads, the spinner says what it loads (`✻ Loading projects…`). +- **Optional fields** are offered ("Fill in 2 optional field(s)?") only by a + command that makes or changes something: create, update, patch, add, set + and the like, where they matter (a description; on update, the field to + change). A read never asks: `agent read-instructions` takes its project and + environment and runs, without asking whether to page with `--offset` and + `--limit`. The header counts only what will be asked. ## Errors From 0f33fe496a17bb9101d904d5cd4de4f68dc23cdb Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:33:29 -0500 Subject: [PATCH 14/30] feat(home): take the main environment, and let flags wait until asked MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A read in the home prompt asked which environment to use every time, and its menu listed flags vf was about to fill as "required". - Commands that don't change environments take the project's main one, with a status line; edits go to its draft and only publishing goes live. Publish, merge, delete and update still ask, main first. - When vf can fill every required flag (from what is current, a default or a list), the menu stays shut after the command: the footer says "enter to run · tab or - for flags", and Enter runs it. Tab or a dash opens it, where a filled flag says with what ("uses Help bot (current)", "uses the main one by default", "you pick it from a list"). - The form's header prints before the first list or field that asks, never over picks taken without asking. --- internal/cli/home.go | 2 +- internal/cli/pickers.go | 3 +- internal/cli/pickers_test.go | 2 +- internal/interactive/interactive.go | 19 ++++++- internal/interactive/pickers.go | 78 +++++++++++++++++++++----- internal/interactive/pickers_test.go | 82 ++++++++++++++++++++++++++++ internal/prompt/complete.go | 42 +++++++++----- internal/prompt/complete_test.go | 18 ++++++ internal/prompt/prompt.go | 25 +++++++-- internal/prompt/prompt_test.go | 34 ++++++++++++ internal/ui/DESIGN.md | 37 +++++++++++-- 11 files changed, 300 insertions(+), 42 deletions(-) diff --git a/internal/cli/home.go b/internal/cli/home.go index 1be0b54..561f87c 100644 --- a/internal/cli/home.go +++ b/internal/cli/home.go @@ -72,7 +72,7 @@ func runPrompt(cmd *cobra.Command, u *ui.UI, out io.Writer, state signIn) error session.Start() // what later lines use when they need one (internal/session) defer session.Stop() - complete := prompt.Commands(cmd.Root(), homeWords) + complete := prompt.CommandsFilling(cmd.Root(), homeWords, interactive.FillNote) histFile := historyPath() history := loadHistory(histFile) // history.go: kept across sessions for { diff --git a/internal/cli/pickers.go b/internal/cli/pickers.go index f69023f..a9c8177 100644 --- a/internal/cli/pickers.go +++ b/internal/cli/pickers.go @@ -29,6 +29,7 @@ func init() { }) interactive.RegisterPicker("environment-alias", interactive.Picker{ Noun: "environment", Plural: "environments", Needs: []string{"project-id"}, List: listEnvironments, + DefaultIs: "the main one", // edits go to its draft; only publishing goes live, and that asks }) } @@ -141,7 +142,7 @@ func listEnvironments(ctx context.Context, cmd *cobra.Command, needs map[string] if e.IsMain { detail += " · main" } - choices = append(choices, interactive.Choice{Value: e.Alias, Name: e.Name, Detail: detail}) + choices = append(choices, interactive.Choice{Value: e.Alias, Name: e.Name, Detail: detail, Default: e.IsMain}) } return choices, nil } diff --git a/internal/cli/pickers_test.go b/internal/cli/pickers_test.go index db67341..da36673 100644 --- a/internal/cli/pickers_test.go +++ b/internal/cli/pickers_test.go @@ -103,7 +103,7 @@ func TestPickersListFromTheAPI(t *testing.T) { t.Fatal(err) } want = []interactive.Choice{ - {Value: "production", Name: "Production", Detail: "production · main"}, + {Value: "production", Name: "Production", Detail: "production · main", Default: true}, {Value: "staging", Name: "Staging", Detail: "staging"}, } if !reflect.DeepEqual(envs, want) { diff --git a/internal/interactive/interactive.go b/internal/interactive/interactive.go index 7a6ffe3..2bd28d6 100644 --- a/internal/interactive/interactive.go +++ b/internal/interactive/interactive.go @@ -242,15 +242,28 @@ func PromptAndSetFlags(cmd *cobra.Command, meta []flagutil.FlagMeta) error { return nil } - // Print the command header once before any forms - printCommandHeader(cmd, len(required), len(optional)) + // The command header comes once, before the first thing that asks: a + // read whose project and environment are taken without asking runs + // with only the pickers' "Using …" lines, and no header over nothing. + // Before a picker's list it has no count, since later picks may be + // taken without asking; before the form's own fields it counts those. + announced := false + announce := func(nRequired, nOptional int) { + if !announced { + announced = true + printCommandHeader(cmd, nRequired, nOptional) + } + } // pickers.go: an ID vf can look up (organization, workspace, project, // environment) is picked from a list; the form asks for the rest. - required, err := pickRequired(cmd, required) + required, err := pickRequired(cmd, required, func() { announce(0, 0) }) if err != nil { return err } + if len(required) > 0 || len(optional) > 0 { + announce(len(required), len(optional)) + } theme := formTheme() width := formWidth() diff --git a/internal/interactive/pickers.go b/internal/interactive/pickers.go index 9cb71e0..00c0507 100644 --- a/internal/interactive/pickers.go +++ b/internal/interactive/pickers.go @@ -31,6 +31,9 @@ type Choice struct { Value string // set on the flag Name string // what a person recognizes: "Support bot" Detail string // shown after it: the ID, which org + // Default is taken without asking by a command that doesn't change what + // it picks: a project's main environment, as Vercel takes Preview. + Default bool } // Picker lists the values a flag can take. @@ -38,7 +41,9 @@ type Picker struct { Noun string // "workspace": the list's title, and "Using workspace …" Plural string // "workspaces": "Couldn't list your workspaces" Needs []string // flags picked first, whose values List reads: a project needs its workspace - List func(ctx context.Context, cmd *cobra.Command, needs map[string]string) ([]Choice, error) + // DefaultIs says why a Default choice was taken: "the main one". + DefaultIs string + List func(ctx context.Context, cmd *cobra.Command, needs map[string]string) ([]Choice, error) } var pickers = map[string]Picker{} @@ -75,9 +80,20 @@ type picking struct { } // pickRequired fills the required fields vf can look up, each from a list, -// and returns the rest for the form to ask as before. -func pickRequired(cmd *cobra.Command, required []fieldInfo) ([]fieldInfo, error) { - return newPicking(cmd).fill(required) +// and returns the rest for the form to ask as before. asking runs before the +// first list or input it shows, not before one it takes without asking. +func pickRequired(cmd *cobra.Command, required []fieldInfo, asking func()) ([]fieldInfo, error) { + p := newPicking(cmd) + choose, ask := p.choose, p.ask + p.choose = func(title, desc string, options []huh.Option[string], value *string) error { + asking() + return choose(title, desc, options, value) + } + p.ask = func(title, desc string, value *string) error { + asking() + return ask(title, desc, value) + } + return p.fill(required) } func newPicking(cmd *cobra.Command) *picking { @@ -194,10 +210,11 @@ func describe(noun string, it session.Item) string { return noun + " " + it.Name + " (" + it.Value + ")" } -// pick lists flag's values and lets the person choose one. A single value is -// taken without asking, and said so, unless the command changes or removes -// the thing picked: deleting your only project still asks which. A list that -// fails or comes back empty falls back to typing the ID. +// pick lists flag's values and lets the person choose one. A single value, +// or a default (a project's main environment), is taken without asking, and +// said so, unless the command changes or removes the thing picked: deleting +// your only project still asks which, and publishing asks which environment. +// A list that fails or comes back empty falls back to typing the ID. func (p *picking) pick(flag string, picker Picker, needs map[string]string) (string, error) { if p.names == nil { p.names = map[string]string{} @@ -222,11 +239,13 @@ func (p *picking) pick(flag string, picker Picker, needs map[string]string) (str fmt.Fprintln(p.out, p.u.Status(ui.StatusWarn, "No "+picker.Plural+" found")) return p.typeID(flag, picker) case len(choices) == 1 && !(p.bound[flag] && changesWhatItPicks(p.cmd)): - c := choices[0] - fmt.Fprintln(p.out, p.u.Status(ui.StatusDone, "Using "+picker.Noun+" "+c.Name+" ("+c.Value+"), the only one")) - savePick(flag, c.Value) - p.names[flag] = c.Name - return c.Value, nil + return p.take(flag, picker, choices[0], "the only one"), nil + case !(p.bound[flag] && changesWhatItPicks(p.cmd)): + for _, c := range choices { + if c.Default { + return p.take(flag, picker, c, picker.DefaultIs), nil + } + } } first := lastPick(flag) @@ -259,6 +278,14 @@ func (p *picking) pick(flag string, picker Picker, needs map[string]string) (str return value, nil } +// take uses c without asking, and says so and why: "the only one". +func (p *picking) take(flag string, picker Picker, c Choice, why string) string { + fmt.Fprintln(p.out, p.u.Status(ui.StatusDone, "Using "+picker.Noun+" "+c.Name+" ("+c.Value+"), "+why)) + savePick(flag, c.Value) + p.names[flag] = c.Name + return c.Value +} + // typeID asks for the ID itself, as the form did before pickers. func (p *picking) typeID(flag string, picker Picker) (string, error) { var value string @@ -291,6 +318,31 @@ func runField(f huh.Field) error { Run() } +// FillNote says what vf puts in flag when cmd runs without it, for the home +// prompt's menu: "uses Help bot (current)", "uses the main one by default", +// "you pick it from a list"; "" when you must give it yourself. +func FillNote(cmd *cobra.Command, flag string) string { + const list = "you pick it from a list" + picker, ok := pickers[flag] + switch { + case !ok: + return "" + case changesWhatItPicks(cmd): + return list // always asked, the current one first + } + if cur, ok := session.Get(flag); ok { + name := cur.Name + if name == "" { + name = cur.Value + } + return "uses " + name + " (current)" + } + if picker.DefaultIs != "" { + return "uses " + picker.DefaultIs + " by default" + } + return list +} + // changesWhatItPicks is whether the command changes or removes what its // flags name, so a lone choice is shown rather than taken. func changesWhatItPicks(cmd *cobra.Command) bool { diff --git a/internal/interactive/pickers_test.go b/internal/interactive/pickers_test.go index 944f51b..0374fee 100644 --- a/internal/interactive/pickers_test.go +++ b/internal/interactive/pickers_test.go @@ -357,3 +357,85 @@ func TestOnlyWritesOfferOptionalFields(t *testing.T) { } } } + +// A project's main environment is taken without asking by a command that +// doesn't change environments, and said so; publishing still asks. +func TestTheMainEnvironmentIsTheDefault(t *testing.T) { + isolatePicks(t) + (&fakePicker{choices: []Choice{{Value: "staging", Name: "Staging"}, {Value: "main", Name: "Main", Default: true}}}).register("environment-alias", "environment") + pickers["environment-alias"] = Picker{Noun: "environment", Plural: "environments", DefaultIs: "the main one", List: pickers["environment-alias"].List} + + read := newSession("read-instructions", "environment-alias") + if _, err := read.fill(fields("environment-alias")); err != nil { + t.Fatal(err) + } + if flag(read, "environment-alias") != "main" || len(read.shown) != 0 || !strings.Contains(read.out.String(), "Using environment Main (main), the main one") { + t.Errorf("a read takes the main environment: flag %q, shown %q, said %q", flag(read, "environment-alias"), read.shown, read.out.String()) + } + + publish := newSession("publish", "environment-alias") + publish.picks["Environment"] = "staging" + if _, err := publish.fill(fields("environment-alias")); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(publish.shown, []string{"Environment"}) || flag(publish, "environment-alias") != "staging" { + t.Errorf("publishing asks which: shown %q, flag %q", publish.shown, flag(publish, "environment-alias")) + } +} + +// The home prompt's menu says what fills a flag you leave out. +func TestFillNoteSaysWhatFillsAFlag(t *testing.T) { + isolatePicks(t) + session.Start() + t.Cleanup(session.Stop) + (&fakePicker{}).register("project-id", "project") + pickers["environment-alias"] = Picker{Noun: "environment", Plural: "environments", DefaultIs: "the main one"} + read, publish := &cobra.Command{Use: "read-instructions"}, &cobra.Command{Use: "publish"} + + for _, c := range []struct { + cmd *cobra.Command + flag, want string + }{ + {read, "name", ""}, // no list: you give it + {read, "project-id", "you pick it from a list"}, + {read, "environment-alias", "uses the main one by default"}, + {publish, "environment-alias", "you pick it from a list"}, // publishing always asks + } { + if got := FillNote(c.cmd, c.flag); got != c.want { + t.Errorf("%s --%s: %q, want %q", c.cmd.Name(), c.flag, got, c.want) + } + } + session.Set("project-id", "p1", "Help bot") + if got := FillNote(read, "project-id"); got != "uses Help bot (current)" { + t.Errorf("the current project: %q", got) + } + if got := FillNote(publish, "project-id"); got != "you pick it from a list" { + t.Errorf("publishing asks even with a current project, so it says so: %q", got) + } +} + +// The form's header comes before a list that asks, not over picks taken +// without asking. +func TestTheHeaderWaitsForSomethingToAsk(t *testing.T) { + isolatePicks(t) + (&fakePicker{choices: []Choice{{Value: "main", Name: "Main"}}}).register("environment-alias", "environment") + saved := chooseInForm + t.Cleanup(func() { chooseInForm = saved }) + chooseInForm = func(_, _ string, options []huh.Option[string], value *string) error { + *value = options[0].Value + return nil + } + cmd := &cobra.Command{Use: "read-instructions"} + cmd.Flags().String("environment-alias", "", "") + headers := 0 + if _, err := pickRequired(cmd, fields("environment-alias"), func() { headers++ }); err != nil || headers != 0 { + t.Errorf("one environment, taken without asking: header %d times, err %v", headers, err) + } + + (&fakePicker{choices: []Choice{{Value: "main", Name: "Main"}, {Value: "staging", Name: "Staging"}}}).register("environment-alias", "environment") + cmd = &cobra.Command{Use: "read-instructions"} + cmd.Flags().String("environment-alias", "", "") + if _, err := pickRequired(cmd, fields("environment-alias"), func() { headers++ }); err != nil || headers != 1 { + t.Errorf("two environments, a list: header %d times, err %v", headers, err) + } +} diff --git a/internal/prompt/complete.go b/internal/prompt/complete.go index 38e0861..fe71828 100644 --- a/internal/prompt/complete.go +++ b/internal/prompt/complete.go @@ -17,7 +17,8 @@ import ( type Suggestion struct { Label string // shown, and inserted in place of the line from From on Detail string // what it does, shown muted - Required bool // a flag the command cannot run without + Required bool // a flag the command cannot run without, that you must give + Filled bool // a required flag vf fills itself; Detail says with what Group bool // a command with commands under it, which does nothing bare From int // byte offset in the line where Label is inserted } @@ -25,6 +26,10 @@ type Suggestion struct { // Completer suggests what can come next in line. type Completer func(line string) []Suggestion +// Filler says what vf puts in a required flag of cmd when it isn't given, +// "Help bot (current)", or "" when you must give it yourself. +type Filler func(cmd *cobra.Command, flag string) string + // deepSearchMin is how many characters a word needs before the menu also // searches below the top level, e.g. "publish" finding "environment publish". const deepSearchMin = 3 @@ -42,7 +47,14 @@ const fuzzyMax = 20 // extra are top-level entries that are not commands, such as the prompt's own // "exit". func Commands(root *cobra.Command, extra []Suggestion) Completer { - return func(line string) []Suggestion { return complete(root, extra, line) } + return CommandsFilling(root, extra, nil) +} + +// CommandsFilling is Commands for a prompt that fills some required flags +// itself (the home prompt: the current project, a list, a default). Those +// show what fills them instead of "required", after the ones you must give. +func CommandsFilling(root *cobra.Command, extra []Suggestion, fill Filler) Completer { + return func(line string) []Suggestion { return complete(root, extra, line, fill) } } type token struct { @@ -50,7 +62,7 @@ type token struct { start int } -func complete(root *cobra.Command, extra []Suggestion, line string) []Suggestion { +func complete(root *cobra.Command, extra []Suggestion, line string, fill Filler) []Suggestion { toks, endsInWord := tokenize(line) partial := token{start: len(line)} if endsInWord { @@ -108,13 +120,13 @@ func complete(root *cobra.Command, extra []Suggestion, line string) []Suggestion case wantsValue: return nil // the word being typed is the previous flag's value case strings.HasPrefix(partial.text, "-"): - return flags(cmd, partial, used) + return flags(cmd, partial, used, fill) case inArgs: return nil case hasSubcommands(cmd): return subcommands(root, cmd, partial, cmdStart, extra) case partial.text == "": - return flags(cmd, partial, used) + return flags(cmd, partial, used, fill) } return nil } @@ -246,14 +258,14 @@ func fuzzyScore(s, p string) (int, bool) { return score*16 - len(s), true } -func flags(cmd *cobra.Command, partial token, used map[string]bool) []Suggestion { +func flags(cmd *cobra.Command, partial token, used map[string]bool, fill Filler) []Suggestion { p := strings.TrimLeft(partial.text, "-") - out := flagsWhere(cmd, partial, used, func(name string) bool { return strings.HasPrefix(name, p) }) + out := flagsWhere(cmd, partial, used, fill, func(name string) bool { return strings.HasPrefix(name, p) }) if len(out) == 0 && len(p) >= fuzzyMin { // No flag starts with it: try it as an abbreviation, "--pid" for // "--project-id". var cands []fuzzyCand - for _, s := range flagsWhere(cmd, partial, used, func(string) bool { return true }) { + for _, s := range flagsWhere(cmd, partial, used, fill, func(string) bool { return true }) { cands = append(cands, fuzzyCand{s, 0}) } out = fuzzyRank(cands, p) @@ -261,10 +273,11 @@ func flags(cmd *cobra.Command, partial token, used map[string]bool) []Suggestion return out } -// flagsWhere is cmd's flags whose names pass keep: required, then optional, -// then, once a dash is typed, the global ones. -func flagsWhere(cmd *cobra.Command, partial token, used map[string]bool, keep func(name string) bool) []Suggestion { - var required, optional, global []Suggestion +// flagsWhere is cmd's flags whose names pass keep: the required ones you +// must give, the required ones vf fills, then optional, then, once a dash is +// typed, the global ones. +func flagsWhere(cmd *cobra.Command, partial token, used map[string]bool, fill Filler, keep func(name string) bool) []Suggestion { + var required, filled, optional, global []Suggestion add := func(f *pflag.Flag, inherited bool) { if f.Hidden || used[f.Name] || f.Name == "help" || !keep(f.Name) { return @@ -273,6 +286,9 @@ func flagsWhere(cmd *cobra.Command, partial token, used map[string]bool, keep fu switch { case inherited: global = append(global, s) + case isRequired(f) && fill != nil && fill(cmd, f.Name) != "": + s.Detail, s.Filled = fill(cmd, f.Name), true + filled = append(filled, s) case isRequired(f): s.Required = true required = append(required, s) @@ -286,7 +302,7 @@ func flagsWhere(cmd *cobra.Command, partial token, used map[string]bool, keep fu if strings.HasPrefix(partial.text, "-") { cmd.InheritedFlags().VisitAll(func(f *pflag.Flag) { add(f, true) }) } - return append(append(required, optional...), global...) + return append(append(append(required, filled...), optional...), global...) } // flagDetail is a flag's usage, first line, without the generated diff --git a/internal/prompt/complete_test.go b/internal/prompt/complete_test.go index 1352049..eb596a2 100644 --- a/internal/prompt/complete_test.go +++ b/internal/prompt/complete_test.go @@ -249,3 +249,21 @@ func TestFuzzyScorePrefersWordStartsAndRuns(t *testing.T) { t.Error("the first letter must start a word") } } + +// A required flag vf fills itself says with what, after the ones you must +// give, and isn't marked required. +func TestFilledFlagsSayWhatFillsThem(t *testing.T) { + fill := func(_ *cobra.Command, flag string) string { + if flag == "project-id" { + return "uses Help bot (current)" + } + return "" + } + got := CommandsFilling(tree(), nil, fill)("environment publish ") + if want := []string{"--environment-id", "--project-id", "--wait"}; !reflect.DeepEqual(labels(got), want) { + t.Fatalf("got %v, want %v", labels(got), want) + } + if !got[0].Required || got[1].Required || !got[1].Filled || got[1].Detail != "uses Help bot (current)" { + t.Errorf("markers: %+v", got[:2]) + } +} diff --git a/internal/prompt/prompt.go b/internal/prompt/prompt.go index 7aab2d4..f1777a9 100644 --- a/internal/prompt/prompt.go +++ b/internal/prompt/prompt.go @@ -71,6 +71,9 @@ type model struct { browsing bool // / or Tab on an empty line opened every command help bool // ? on an empty line opened the shortcuts armed bool // Ctrl-C on an empty line; a second one exits + // quiet: the menu would only list flags nothing needs, after a command + // that can run as typed, so it stays shut until Tab or a dash opens it. + quiet bool searching bool // ctrl-r: searching history, as a shell does query string // what the search looks for @@ -204,11 +207,12 @@ func (m *model) key(k tea.KeyMsg) (tea.Model, tea.Cmd) { if m.menuVisible() && m.enterCompletes() { picked := m.suggestions[m.sel] m.accept() - // Finishing a command that takes nothing more runs it, as Enter - // on a Claude Code slash command does: "vers" runs version. A - // group, or a command with flags to offer, waits for more; so - // does a flag, which waits for its value. - if len(m.suggestions) > 0 || strings.HasPrefix(picked.Label, "-") { + // Finishing a command that needs nothing more runs it, as Enter + // on a Claude Code slash command does: "vers" runs version, and + // "agent read-ins" runs with its project and environment filled + // in. A group, or a command with a flag you must give, waits for + // more; so does a flag, which waits for its value. + if m.menuVisible() || strings.HasPrefix(picked.Label, "-") { return m, nil } } @@ -261,6 +265,15 @@ func (m *model) refresh() { if m.complete != nil && (m.browsing || strings.TrimSpace(before) != "") { m.suggestions = m.complete(before) } + m.quiet = strings.HasSuffix(before, " ") && len(m.suggestions) > 0 + for _, s := range m.suggestions { + if !strings.HasPrefix(s.Label, "-") || s.Required { + m.quiet = false // a command to pick, or a flag you must give + } + } + if m.quiet { + m.dismissed = true // Tab or a dash opens it, as a shell's completion does + } } func (m *model) menuVisible() bool { return !m.dismissed && len(m.suggestions) > 0 } @@ -478,6 +491,8 @@ func (m *model) footer() string { return "Press Ctrl-C again to exit" case m.input.Value() == "": return "/ for commands" + sep + "? for shortcuts" + case m.quiet && !m.menuVisible(): + return "enter to run" + sep + "tab or - for flags" } return "enter to run" + sep + "ctrl-c to clear" } diff --git a/internal/prompt/prompt_test.go b/internal/prompt/prompt_test.go index ee80da6..30a943a 100644 --- a/internal/prompt/prompt_test.go +++ b/internal/prompt/prompt_test.go @@ -10,6 +10,7 @@ import ( tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" + "github.com/spf13/cobra" "github.com/voiceflow/cli/internal/ui" ) @@ -492,3 +493,36 @@ func TestTheContextIsSetIntoTheTopBorder(t *testing.T) { t.Errorf("no context, a plain border: %q", top) } } + +// filling is a prompt that fills every required flag itself, as the home +// prompt does with the current project. +func filling() *model { + m := testModel() + m.complete = CommandsFilling(tree(), extras, func(*cobra.Command, string) string { return "uses Help bot (current)" }) + return m +} + +// When nothing more is needed, a command's flags wait for Tab or a dash, as +// a shell's completion does, and Enter runs it. +func TestFlagsWaitUntilAsked(t *testing.T) { + m := filling().typed("project get ") + if m.menuVisible() || !strings.HasSuffix(m.View(), " enter to run · tab or - for flags") { + t.Fatalf("the flags should wait:\n%s", m.View()) + } + if m.press(tab); !m.menuVisible() || !strings.Contains(m.View(), " ❯ --project-id uses Help bot (current)") { + t.Errorf("tab opens them:\n%s", m.View()) + } + if m := filling().typed("project get -"); !m.menuVisible() || labels(m.suggestions)[0] != "--project-id" { + t.Errorf("a dash opens them: %v", labels(m.suggestions)) + } + if m := filling().typed("project g").press(enter); !m.done || m.line != "project get " { + t.Errorf("finishing the command runs it: done=%v %q", m.done, m.line) + } + if m := testModel().typed("project list "); m.menuVisible() { + t.Errorf("optional flags wait too") + } + // A flag you must give still opens the menu, and Enter waits for it. + if m := testModel().typed("project g").press(enter); m.done || !m.menuVisible() { + t.Errorf("a required flag: done=%v menu=%v", m.done, m.menuVisible()) + } +} diff --git a/internal/ui/DESIGN.md b/internal/ui/DESIGN.md index d28da7c..5dffbd6 100644 --- a/internal/ui/DESIGN.md +++ b/internal/ui/DESIGN.md @@ -163,6 +163,15 @@ next command: `auth login` signed out, then by what is current (below): --description An optional description of what changed in this releas… ``` +In the home prompt vf fills the IDs itself, and the menu says how; publishing +always asks which: + +``` + ❯ --name required · The name of the release created by publishi… + --environment-alias you pick it from a list + --project-id you pick it from a list +``` + - **The box** is the banner's width with a Subtle border; the `❯` is Accent. - **The menu** follows the word being typed: commands while the line names a command (prefix matches, then names containing it, then, from three letters, @@ -175,9 +184,17 @@ next command: `auth login` signed out, then by what is current (below): the menu with all of them, then `exit` and `clear`; typing narrows it. The `/` is not typed into the line, and a pasted `/project list` runs as `project list`. -- **Keys:** Tab or Enter completes the word. Enter on a command that takes - nothing more runs it (`vers` runs `version`); a group or a command with flags - waits for the rest. +- **Keys:** Tab or Enter completes the word. Enter on a command that needs + nothing more runs it (`vers` runs `version`); a group, or a command with a + flag you must give, waits for the rest. +- **Flags wait until asked** when vf can fill every required one (from what + is current, a default, or a list it shows) and the rest are optional, as a + shell's completion waits for Tab: after `agent read-instructions ` the menu + stays shut and the footer says `enter to run · tab or - for flags`. Tab or a + `-` opens it. There a flag vf fills says with what, in place of `required`, + after the ones you must give: `uses Help bot (current)`, `uses the main one + by default`, `you pick it from a list` (always, for a command that changes + what it picks: publish, delete…). - **A group never runs bare**, since all it would do is print its help. Its name typed in full opens it like a partial name, and with its commands in the menu, Enter takes the one the `❯` is on. A command's flags in the menu do not @@ -314,8 +331,18 @@ flag lists). - **One choice** is taken, and a status line says so, unless the command changes or removes what it picks (delete, publish, merge, update…): deleting your only project still asks which. -- **The default** is the last pick: first in the list, where Enter takes it - again, but never taken without asking. Kept in `~/.config/vf/picks.json`, +- **The main environment** is taken, with a status line + (`✓ Using environment main (…), the main one`), by every command that + doesn't change environments: edits go to its draft, and only publishing goes + live. Publish, merge, delete and update still ask, the main one first, as a + project's environments are where a mistake would ship. The default the + menu's flags show (`uses the main one by default`) is this one. +- **The form's header** (the command, what it does, how many fields) comes + before the first list or field that asks, never over picks taken without + asking: a read whose project and environment are filled prints only the + `✓ Using …` lines, then its result. +- **The default** is otherwise the last pick: first in the list, where Enter + takes it again, but never taken without asking. Kept in `~/.config/vf/picks.json`, readable by its owner only. - **Organizations** come from your workspaces. The API has no organizations endpoint and no organization names, so each is named by its workspaces From 6ae782fe810791866df06de1c8a486d6dad40ced Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:48:41 -0500 Subject: [PATCH 15/30] feat(output): show a prompt's page as a document MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit agent read-prompt, agent read-instructions and playbook read-instructions printed the API's page for agents as YAML: each line numbered in the string color, long lines wrapping to column 0, markdown raw, and six fields about the page. At a terminal, in pretty output, the page now reads as a document: - No line numbers; editing works by exact text, so a person needs none. - Markdown rendered in vf's colors by a small renderer (ui/markdown.go) that hides nothing written: headings lose their #s, bullets become •, bold and italic are styled, backticked names and {variables} are Accent, and XML tags like stay, Subtle. Code blocks and table rows are left as written; without color the markers stay. glamour was ruled out: it drops XML tags, runs lines together, and adds 10 MB. - Every line stays a line; only one wider than the box is reflowed, under its own indent or bullet. - One line about the page: "18 lines · 980 characters", or "Lines 1–400 of 1,203 · vf agent read-prompt … --offset 401 for more", then the API's note on links. JSON, YAML, --jq, agent mode and a pipe get the page as the API sent it. --- internal/output/document.go | 145 ++++++++++++++++ internal/output/document_test.go | 98 +++++++++++ internal/output/output.go | 3 + internal/ui/DESIGN.md | 42 +++++ internal/ui/markdown.go | 280 +++++++++++++++++++++++++++++++ internal/ui/markdown_test.go | 77 +++++++++ internal/ui/ui.go | 5 +- 7 files changed, 649 insertions(+), 1 deletion(-) create mode 100644 internal/output/document.go create mode 100644 internal/output/document_test.go create mode 100644 internal/ui/markdown.go create mode 100644 internal/ui/markdown_test.go diff --git a/internal/output/document.go b/internal/output/document.go new file mode 100644 index 0000000..b9955b3 --- /dev/null +++ b/internal/output/document.go @@ -0,0 +1,145 @@ +// This file is not generated by Speakeasy. It shows a page of a prompt or +// instructions (agent read-prompt, agent read-instructions, playbook +// read-instructions) as a document, for a person at a terminal: +// +// Role +// You are a senior support specialist for Acme Corp. You've been +// helping customers for years. +// +// Guardrails +// • Never reveal internal processes or pricing logic. +// +// 18 lines · 980 characters +// +// The API returns the page for agents: each line numbered, then six fields +// about the page. The numbers are for pointing at lines, and editing works +// by exact text (patch-prompt --old-string), so a person doesn't need them. +// JSON, YAML, --jq, agent mode and a pipe still get the page as the API +// sent it, numbers and all. + +package output + +import ( + "io" + "regexp" + "strconv" + "strings" + + "github.com/charmbracelet/x/ansi" + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/session" + "github.com/voiceflow/cli/internal/ui" +) + +// lineNumber is the "12\t" the API puts before each line. +var lineNumber = regexp.MustCompile(`(?m)^\d+\t`) + +// writeDocument writes content as a document when it is a page of a prompt +// or instructions and a person is reading pretty output at a terminal. It +// reports whether it did; if not, the result prints as before. +func writeDocument(cmd *cobra.Command, out io.Writer, content interface{}) bool { + page, ok := content.(*components.StableInstructionsReadResponseV2) + if !ok || page == nil { + return false + } + stdout := cmd.OutOrStdout() + u := UI(cmd, stdout) + if !u.Decorated() { + return false + } + io.WriteString(out, renderDocument(u, page, ui.BoxWidth(ui.TerminalWidth(stdout)), nextPage(cmd, page))) //nolint:errcheck // a terminal write + return true +} + +// renderDocument is the page as a document width columns wide, then a line +// about the page. next is the command that reads the rest, when there is a +// rest. +func renderDocument(u *ui.UI, page *components.StableInstructionsReadResponseV2, width int, next string) string { + var b strings.Builder + text := lineNumber.ReplaceAllString(page.Content, "") + if strings.TrimSpace(text) != "" { + for _, line := range u.Markdown(text, width) { + b.WriteString(line + "\n") + } + b.WriteString("\n") + } + + sep := " " + u.Glyph(ui.Separator) + " " + var about string + switch { + case page.TotalLines == 0: + about = u.Muted("Empty: nothing written yet") + case strings.TrimSpace(text) == "" && page.ReturnedLines == 0: + about = u.Muted("Nothing from line " + thousands(page.Offset) + ": it has " + plural(page.TotalLines, "line")) + case page.Offset <= 1 && !page.HasMore: + about = u.Muted(plural(page.TotalLines, "line") + sep + plural(page.TotalCharacters, "character")) + default: + lines := "Lines " + thousands(page.Offset) + "–" + thousands(page.Offset+page.ReturnedLines-1) + if page.ReturnedLines == 1 { + lines = "Line " + thousands(page.Offset) + } + about = u.Muted(lines + " of " + thousands(page.TotalLines)) + if next != "" { + about += u.Muted(sep) + u.Accent(next) + u.Muted(" for more") + } + } + b.WriteString(about + "\n") + if page.Note != nil && strings.TrimSpace(*page.Note) != "" { + // Muted all through: a name's own color would end the dimming. + for _, line := range u.Markdown(*page.Note, width) { + b.WriteString(u.Muted(ansi.Strip(line)) + "\n") + } + } + return b.String() +} + +// nextPage is the command that reads the page after this one: the same +// command and flags, from the next offset. Inside the home prompt a flag +// that holds what is current is left out, since the prompt fills it. +func nextPage(cmd *cobra.Command, page *components.StableInstructionsReadResponseV2) string { + if !page.HasMore || page.NextOffset == nil { + return "" + } + parts := []string{cmd.CommandPath()} + cmd.LocalNonPersistentFlags().VisitAll(func(f *pflag.Flag) { + if !f.Changed || f.Name == "offset" { + return + } + if cur, ok := session.Get(f.Name); ok && cur.Value == f.Value.String() { + return + } + parts = append(parts, "--"+f.Name, quoteArg(f.Value.String())) + }) + return strings.Join(append(parts, "--offset", strconv.FormatInt(*page.NextOffset, 10)), " ") +} + +func quoteArg(s string) string { + if s != "" && !strings.ContainsAny(s, " \t\"'\\$`") { + return s + } + return strconv.Quote(s) +} + +func plural(n int64, noun string) string { + if n == 1 { + return "1 " + noun + } + return thousands(n) + " " + noun + "s" +} + +// thousands writes n with commas: 1,203. +func thousands(n int64) string { + s := strconv.FormatInt(n, 10) + neg := strings.HasPrefix(s, "-") + s = strings.TrimPrefix(s, "-") + for i := len(s) - 3; i > 0; i -= 3 { + s = s[:i] + "," + s[i:] + } + if neg { + return "-" + s + } + return s +} diff --git a/internal/output/document_test.go b/internal/output/document_test.go new file mode 100644 index 0000000..cb45e80 --- /dev/null +++ b/internal/output/document_test.go @@ -0,0 +1,98 @@ +// This file is not generated by Speakeasy. It covers document.go. + +package output + +import ( + "io" + "regexp" + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/session" + "github.com/voiceflow/cli/internal/ui" +) + +var ansiCodes = regexp.MustCompile(`\x1b\[[0-9;]*m`) + +func page(content string, offset, returned, total, chars int64, next *int64) *components.StableInstructionsReadResponseV2 { + return &components.StableInstructionsReadResponseV2{Content: content, Offset: offset, ReturnedLines: returned, + TotalLines: total, TotalCharacters: chars, HasMore: next != nil, NextOffset: next} +} + +func doc(p *components.StableInstructionsReadResponseV2, next string) string { + u := ui.New(io.Discard, ui.Options{Color: true, Decorate: true}) + return ansiCodes.ReplaceAllString(renderDocument(u, p, 80, next), "") +} + +// The page reads as the document it is: no line numbers, no fields, one +// line about it. +func TestAPageReadsAsADocument(t *testing.T) { + got := doc(page("1\t# Role\n2\t\n3\tYou are kind.\n4\t- Be brief", 1, 4, 4, 32, nil), "") + want := "Role\n\nYou are kind.\n• Be brief\n\n4 lines · 32 characters\n" + if got != want { + t.Errorf("got:\n%s\nwant:\n%s", got, want) + } +} + +func TestAPartPageSaysHowToReadOn(t *testing.T) { + next := int64(401) + got := doc(page("1\tHello", 1, 400, 1203, 50000, &next), "vf agent read-prompt --offset 401") + if !strings.HasSuffix(got, "Lines 1–400 of 1,203 · vf agent read-prompt --offset 401 for more\n") { + t.Errorf("got:\n%s", got) + } + if got := doc(page("7\tHello", 7, 1, 9, 50, nil), ""); got != "Hello\n\nLine 7 of 9\n" { + t.Errorf("one line: %q", got) + } + if got := doc(page("", 1, 0, 0, 0, nil), ""); got != "Empty: nothing written yet\n" { + t.Errorf("empty: %q", got) + } + if got := doc(page("", 50, 0, 18, 980, nil), ""); got != "Nothing from line 50: it has 18 lines\n" { + t.Errorf("past the end: %q", got) + } + note := "`lookup` is a link to a tool." + p := page("1\tCall `lookup`.", 1, 1, 1, 14, nil) + p.Note = ¬e + if got := doc(p, ""); !strings.HasSuffix(got, "1 line · 14 characters\nlookup is a link to a tool.\n") { + t.Errorf("note: %q", got) + } +} + +// The next page's command repeats what was given, except what the home +// prompt fills from what is current. +func TestTheNextPageKeepsTheFlagsGiven(t *testing.T) { + cmd := &cobra.Command{Use: "read-prompt"} + (&cobra.Command{Use: "agent"}).AddCommand(cmd) + cmd.Flags().String("project-id", "", "") + cmd.Flags().String("environment-alias", "", "") + cmd.Flags().Int64("offset", 1, "") + _ = cmd.Flags().Set("project-id", "p1") + _ = cmd.Flags().Set("environment-alias", "my env") + _ = cmd.Flags().Set("offset", "1") + next := int64(401) + p := page("", 1, 400, 900, 9000, &next) + if got := nextPage(cmd, p); got != `agent read-prompt --environment-alias "my env" --project-id p1 --offset 401` { + t.Errorf("got %q", got) + } + session.Start() + t.Cleanup(session.Stop) + session.Set("project-id", "p1", "Help bot") + if got := nextPage(cmd, p); got != `agent read-prompt --environment-alias "my env" --offset 401` { + t.Errorf("in the prompt: %q", got) + } + if got := nextPage(cmd, page("", 1, 4, 4, 9, nil)); got != "" { + t.Errorf("a whole page has no next: %q", got) + } +} + +// Off a terminal the page prints as the API sent it. +func TestOffATerminalThePageIsUnchanged(t *testing.T) { + cmd := &cobra.Command{Use: "read-prompt"} + cmd.Flags().String("color", "auto", "") + cmd.SetOut(io.Discard) + if writeDocument(cmd, io.Discard, page("1\tHi", 1, 1, 1, 2, nil)) { + t.Error("a pipe should get the page as sent") + } +} diff --git a/internal/output/output.go b/internal/output/output.go index 845fe1e..fe5bcef 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -275,6 +275,9 @@ func Result(cmd *cobra.Command, res interface{}) error { } fmt.Fprint(out, toonStr) default: // "pretty" or unset + if writeDocument(cmd, out, content) { // document.go: a prompt's page, as a document + return nil + } if err := prettyPrint(out, content, colorize); err != nil { return err } diff --git a/internal/ui/DESIGN.md b/internal/ui/DESIGN.md index 5dffbd6..1ce1304 100644 --- a/internal/ui/DESIGN.md +++ b/internal/ui/DESIGN.md @@ -57,6 +57,7 @@ yellow, so Warning colors glyphs and short words, never sentences. | Warn | `⚠` | `!` | it worked, but look | | Separator | `·` | `\|` | between inline items | | Empty | `—` | `-` | a value that is not there | +| Bullet | `•` | `-` | a list item in a document | Action follows Claude Code: macOS fonts draw U+23FA as a clean dot, while Windows and many Linux fonts draw it as an emoji or a box. @@ -361,6 +362,47 @@ flag lists). environment and runs, without asking whether to page with `--offset` and `--limit`. The header counts only what will be asked. +## Documents + +A prompt or instructions (`agent read-prompt`, `agent read-instructions`, +`playbook read-instructions`) reads as the document it is +(`internal/output/document.go`, rendered by `internal/ui/markdown.go`): + +``` +Role +You are a senior support specialist for Acme Corp. You've been helping +customers for years and genuinely enjoy solving problems. + + +• Never reveal internal processes, pricing logic, or system + architecture to customers. +• Greet {customer_name} and call lookup_order first. + + +18 lines · 980 characters +``` + +- **For a person, at a terminal, in pretty output.** The API returns the + page for agents, each line numbered then six fields about the page; JSON, + YAML, `--jq`, agent mode and a pipe still get exactly that. Editing works + by exact text (`patch-prompt --old-string`), so a person needs no numbers. +- **Nothing written is hidden.** Headings lose their `#`s (Bold, Accent), + bullets become `•` (Subtle), `**bold**` is Bold and `*italic*` italic. A + backticked name, a link to a tool, playbook or workflow, is Accent, as is + a `{variable}`; an XML tag like `` stays, Subtle. Code blocks and + table rows are left exactly as written. Without color (NO_COLOR) the + markers stay, since nothing else would show what they meant. A general + renderer (glamour, as gh uses) was ruled out: it drops XML tags, runs + lines together, and adds 10 MB. +- **Every line stays a line.** Only a line wider than the box (the + banner's width, up to 100) is reflowed, under its own indent or bullet; + a shorter one is left as written, spaces and all. +- **One line about the page,** Muted: `18 lines · 980 characters` for the + whole document; for part of it, `Lines 1–400 of 1,203 · vf agent + read-prompt --offset 401 for more`, the command repeating the flags given + (the home prompt leaves out what it fills). The API's note on links + follows it, Muted. + ## Errors Every failure answers three questions: what happened, why, and what to do diff --git a/internal/ui/markdown.go b/internal/ui/markdown.go new file mode 100644 index 0000000..fa85be4 --- /dev/null +++ b/internal/ui/markdown.go @@ -0,0 +1,280 @@ +// This file is not generated by Speakeasy. It renders the markdown people +// write in prompts and instructions for a terminal, in vf's own colors. +// +// A prompt is not a web page, so this is not a general markdown renderer +// (glamour, which gh uses, drops the XML tags prompts are often built from, +// and runs lines together). Every source line stays a line, and nothing +// written is hidden: headings lose their #s and bullets become •, but tags +// like and variables like {customer_name} stay, tinted. Without color +// (NO_COLOR) the markers stay too, since nothing else would show what they +// meant. Only a line wider than the terminal is reflowed, under its own +// indent. + +package ui + +import ( + "regexp" + "strings" + + "github.com/charmbracelet/lipgloss" + "github.com/muesli/termenv" +) + +// mdKind is how a run of text inside a line is styled. +type mdKind int + +const ( + mdPlain mdKind = iota + mdBold // **bold** + mdItalic // *italic* + mdName // `name`: code, or a link to a tool, playbook or workflow + mdVar // {customer_name} + mdTag // , +) + +type mdPiece struct { + text string + kind mdKind +} + +var ( + mdHeading = regexp.MustCompile(`^(#{1,6})\s+(.*?)\s*#*\s*$`) + mdRule = regexp.MustCompile(`^\s*([-*_])(\s*[-*_]){2,}\s*$`) + mdItem = regexp.MustCompile(`^(\s*)([-*+]|\d{1,3}[.)])\s+(.*)$`) + mdQuote = regexp.MustCompile(`^(\s*)>\s?(.*)$`) + mdVarRe = regexp.MustCompile(`^\{[A-Za-z_][A-Za-z0-9_.]*\}`) + mdTagRe = regexp.MustCompile(`^]*)?/?>`) +) + +// Markdown renders src, markdown as written in a prompt, as lines at most +// width columns wide (a word longer than that keeps a line of its own). +func (u *UI) Markdown(src string, width int) []string { + var out []string + fenced := false + for _, line := range strings.Split(strings.TrimRight(src, "\n"), "\n") { + line = strings.TrimRight(line, " \t\r") + trimmed := strings.TrimSpace(line) + switch { + case strings.HasPrefix(trimmed, "```") || strings.HasPrefix(trimmed, "~~~"): + fenced = !fenced + out = append(out, u.Subtle(line)) + continue + case fenced: + out = append(out, line) // code, exactly as written + continue + } + line = strings.ReplaceAll(line, "\t", " ") // a tab has no width to wrap under + switch { + case trimmed == "": + out = append(out, "") + case mdHeading.MatchString(line) && u.opts.Color: + text := mdHeading.FindStringSubmatch(line)[2] + for _, l := range flow([]mdPiece{{text: plainText(parseInline(text)), kind: mdPlain}}, width, 0) { + out = append(out, u.heading(l.plain())) + } + case mdRule.MatchString(line): + out = append(out, u.Subtle(strings.Repeat("─", min(width, 40)))) + case strings.HasPrefix(trimmed, "|"): + out = append(out, u.render(u.inline(line))) // a table row: reflowing it would break the columns + case mdItem.MatchString(line): + m := mdItem.FindStringSubmatch(line) + marker, shown := m[2], m[2] // a number stays as written: steps are read in order + if !strings.ContainsAny(marker, ".)") { + marker = u.Glyph(Bullet) + shown = u.Subtle(marker) + } + out = append(out, u.flowed(u.inline(m[3]), width, m[1]+marker+" ", m[1]+shown+" ")...) + case mdQuote.MatchString(line): + m := mdQuote.FindStringSubmatch(line) + bar := "│ " + if !u.opts.Decorate { + bar = "> " + } + out = append(out, u.flowed(u.inline(m[2]), width, m[1]+bar, m[1]+u.Subtle(bar))...) + default: + indent := line[:len(line)-len(strings.TrimLeft(line, " \t"))] + out = append(out, u.flowed(u.inline(trimmed), width, indent, indent)...) + } + } + return out +} + +// flowed renders pieces after a lead (shown as shown), wrapping under it. +func (u *UI) flowed(pieces []mdPiece, width int, lead, shown string) []string { + pad := strings.Repeat(" ", lipgloss.Width(lead)) + var out []string + for i, l := range flow(pieces, width, lipgloss.Width(lead)) { + prefix := pad + if i == 0 { + prefix = shown + } + out = append(out, prefix+u.render(l)) + } + return out +} + +type mdLine []mdPiece + +func (l mdLine) plain() string { return plainText(l) } + +// flow breaks pieces into lines that fit width after lead columns of +// indent or bullet. A line that fits is left exactly as written, spaces and all. +func flow(pieces []mdPiece, width, lead int) []mdLine { + room := max(width-lead, 10) + if lipgloss.Width(plainText(pieces)) <= room { + return []mdLine{pieces} + } + var lines []mdLine + var line mdLine + used := 0 + for _, word := range words(pieces) { + w := lipgloss.Width(plainText(word)) + switch { + case len(line) == 0: + line, used = append(line, word...), w + case used+1+w <= room: + gap := mdPlain + if line[len(line)-1].kind == word[0].kind { + gap = word[0].kind // inside a bold phrase, the space is bold too + } + line = append(append(line, mdPiece{" ", gap}), word...) + used += 1 + w + default: + lines = append(lines, line) + line, used = append(mdLine(nil), word...), w + } + } + return append(lines, line) +} + +// words splits pieces at spaces; a word can mix kinds ("{name}." is a +// variable then a period). +func words(pieces []mdPiece) [][]mdPiece { + var out [][]mdPiece + var cur []mdPiece + for _, p := range pieces { + parts := strings.Split(p.text, " ") + for i, part := range parts { + if i > 0 && len(cur) > 0 { + out = append(out, cur) + cur = nil + } + if part != "" { + cur = append(cur, mdPiece{part, p.kind}) + } + } + } + if len(cur) > 0 { + out = append(out, cur) + } + return out +} + +func plainText(pieces []mdPiece) string { + var b strings.Builder + for _, p := range pieces { + b.WriteString(p.text) + } + return b.String() +} + +// parseInline splits a line into runs: **bold**, *italic*, `names`, +// {variables} and . A marker with no partner is plain text. +func parseInline(s string) []mdPiece { + var out []mdPiece + var plain strings.Builder + emit := func(text string, kind mdKind) { + if plain.Len() > 0 { + out = append(out, mdPiece{plain.String(), mdPlain}) + plain.Reset() + } + if text != "" { + out = append(out, mdPiece{text, kind}) + } + } + for i := 0; i < len(s); { + rest := s[i:] + switch { + case strings.HasPrefix(rest, "`"): + if end := strings.Index(rest[1:], "`"); end > 0 { + emit(rest[1:1+end], mdName) + i += end + 2 + continue + } + case strings.HasPrefix(rest, "**"): + if end := strings.Index(rest[2:], "**"); end > 0 { + emit(rest[2:2+end], mdBold) + i += end + 4 + continue + } + case strings.HasPrefix(rest, "*") && len(rest) > 1 && rest[1] != ' ' && rest[1] != '*': + if end := strings.Index(rest[1:], "*"); end > 0 && rest[end] != ' ' { + emit(rest[1:1+end], mdItalic) + i += end + 2 + continue + } + case strings.HasPrefix(rest, "{"): + if m := mdVarRe.FindString(rest); m != "" { + emit(m, mdVar) + i += len(m) + continue + } + case strings.HasPrefix(rest, "<"): + if m := mdTagRe.FindString(rest); m != "" { + emit(m, mdTag) + i += len(m) + continue + } + } + plain.WriteByte(s[i]) + i++ + } + emit("", mdPlain) + return out +} + +// inline is s's runs. Without color they keep their markers, which are +// then all that shows what they are. +func (u *UI) inline(s string) []mdPiece { + pieces := parseInline(s) + if u.opts.Color { + return pieces + } + marks := map[mdKind]string{mdBold: "**", mdItalic: "*", mdName: "`"} + for i, p := range pieces { + if m := marks[p.kind]; m != "" { + pieces[i].text = m + p.text + m + } + } + return pieces +} + +// render styles a line's runs, merging neighbours of the same kind so a +// bold phrase is one escape sequence, not one per word. +func (u *UI) render(pieces []mdPiece) string { + var b strings.Builder + for i := 0; i < len(pieces); { + j, text := i, "" + for ; j < len(pieces) && pieces[j].kind == pieces[i].kind; j++ { + text += pieces[j].text + } + switch pieces[i].kind { + case mdBold: + text = u.Bold(text) + case mdItalic: + text = u.style(text, termenv.Style.Italic) + case mdName, mdVar: + text = u.Accent(text) + case mdTag: + text = u.Subtle(text) + } + b.WriteString(text) + i = j + } + return b.String() +} + +// heading styles a heading's text: bold, in the accent color. +func (u *UI) heading(s string) string { + return u.style(s, func(t termenv.Style) termenv.Style { return u.fg(AccentHex)(t).Bold() }) +} diff --git a/internal/ui/markdown_test.go b/internal/ui/markdown_test.go new file mode 100644 index 0000000..6dd2b28 --- /dev/null +++ b/internal/ui/markdown_test.go @@ -0,0 +1,77 @@ +// This file is not generated by Speakeasy. It covers markdown.go. + +package ui + +import ( + "io" + "regexp" + "strings" + "testing" +) + +var escapes = regexp.MustCompile(`\x1b\[[0-9;]*m`) + +func plainLines(lines []string) string { + return escapes.ReplaceAllString(strings.Join(lines, "\n"), "") +} + +func mdColored() *UI { return New(io.Discard, Options{Color: true, Decorate: true}) } + +// Nothing a prompt says is hidden: tags and variables stay, and each line +// stays a line. Only markdown's own markers go. +func TestMarkdownHidesNothingWritten(t *testing.T) { + src := "# Role\n\n\nYou are **kind** to {customer_name}.\nCall `lookup_order` *first*.\n\n\n- Be brief\n - Very\n2. Then this" + want := "Role\n\n\nYou are kind to {customer_name}.\nCall lookup_order first.\n\n\n• Be brief\n • Very\n2. Then this" + if got := plainLines(mdColored().Markdown(src, 80)); got != want { + t.Errorf("got:\n%s\nwant:\n%s", got, want) + } +} + +func TestMarkdownStyles(t *testing.T) { + got := strings.Join(mdColored().Markdown("# Role\nYou are **kind** to {name}, always.", 80), "\n") + for _, want := range []string{"\x1b[1m", "kind", "{name}", ""} { + if !strings.Contains(got, want) { + t.Errorf("missing %q in %q", want, got) + } + } + if strings.Contains(got, "**") || strings.Contains(got, "# ") { + t.Errorf("markers should go when there is color: %q", got) + } +} + +// Without color nothing else shows what a marker meant, so it stays. +func TestMarkdownWithoutColorKeepsMarkers(t *testing.T) { + u := New(io.Discard, Options{Decorate: true}) + src := "# Role\nYou are **kind**; call `lookup`.\n- Be brief" + want := "# Role\nYou are **kind**; call `lookup`.\n• Be brief" + if got := strings.Join(u.Markdown(src, 80), "\n"); got != want { + t.Errorf("got:\n%s\nwant:\n%s", got, want) + } +} + +// A long line wraps under its own indent or bullet; a short one is left as +// written, spaces and all. +func TestMarkdownWrapsUnderTheIndent(t *testing.T) { + src := "- Never reveal internal processes, pricing logic, or system architecture.\n> Quoted text that is long enough to wrap here.\nKeep these spaces" + want := "• Never reveal internal processes,\n pricing logic, or system\n architecture.\n│ Quoted text that is long enough to\n wrap here.\nKeep these spaces" + if got := plainLines(mdColored().Markdown(src, 36)); got != want { + t.Errorf("got:\n%s\nwant:\n%s", got, want) + } + for _, l := range mdColored().Markdown(src, 36) { + if n := len([]rune(escapes.ReplaceAllString(l, ""))); n > 36 { + t.Errorf("%d columns: %q", n, l) + } + if codes := escapes.FindAllString(l, -1); len(codes) > 0 && codes[len(codes)-1] != "\x1b[0m" { + t.Errorf("a style runs past the end of the line: %q", l) + } + } +} + +// Code is shown exactly as written, and a lone * is arithmetic, not italic. +func TestMarkdownLeavesCodeAndLoneStarsAlone(t *testing.T) { + src := "```\nx = *y*\n```\n5 * 3 = 15\n| a | **b** |" + want := "```\nx = *y*\n```\n5 * 3 = 15\n| a | b |" + if got := plainLines(mdColored().Markdown(src, 80)); got != want { + t.Errorf("got:\n%s\nwant:\n%s", got, want) + } +} diff --git a/internal/ui/ui.go b/internal/ui/ui.go index ba2ab4b..373835d 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -141,6 +141,7 @@ const ( Warn // it worked, but look Separator // between inline items Empty // a value that is not there + Bullet // a list item in a document ) // Symbol returns the decorated form of g. @@ -171,6 +172,8 @@ func (g Glyph) Symbol() string { return "·" case Empty: return "—" + case Bullet: + return "•" } return "" } @@ -180,7 +183,7 @@ func (g Glyph) ASCII() string { switch g { case Action, Working: return "*" - case Result, Empty: + case Result, Empty, Bullet: return "-" case Pointer: return ">" From e90370cbe74278dff5bdfae157f3e2e0a78d30f3 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:15:57 -0500 Subject: [PATCH 16/30] fix(interactive): name what was picked, and explain older projects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Picking an older project (v3, made before environments) for agent read-instructions printed only "Couldn't list your environments: HTTP 404 Not Found — Project does not have any environments", without saying which project, then asked for an "Environment ID" that couldn't exist. - A pick or a typed ID is said once its form has gone: "✓ Using project Old bot (pold)". - A list that answers 404 for what it lists from (a project with no environments) stops the command instead of asking for an ID. In the home prompt that project stops being current. - The public API doesn't say what kind a project is, so its refusals are read (output/framework.go): a 404 "Project does not have any environments" explains the fixed development, staging and production versions and points to Migrate to environments; a 400 "is not an agent project" explains Conversation Flow and points to the Agentic framework switch. Both offer another project first. - A message the API wrote for an AI agent is said to the person: "Tell the user that X" reads "X". Agent mode gets it as sent. - The typed box for --environment-alias says "alias", not "ID". --- internal/interactive/pickers.go | 39 ++++++++++- internal/interactive/pickers_test.go | 55 ++++++++++++++++ internal/output/explain.go | 12 +++- internal/output/framework.go | 99 ++++++++++++++++++++++++++++ internal/output/framework_test.go | 75 +++++++++++++++++++++ internal/ui/DESIGN.md | 28 ++++++-- 6 files changed, 300 insertions(+), 8 deletions(-) create mode 100644 internal/output/framework.go create mode 100644 internal/output/framework_test.go diff --git a/internal/interactive/pickers.go b/internal/interactive/pickers.go index 00c0507..227605f 100644 --- a/internal/interactive/pickers.go +++ b/internal/interactive/pickers.go @@ -14,6 +14,7 @@ import ( "context" "fmt" "io" + "net/http" "os" "strings" "unicode/utf8" @@ -232,6 +233,18 @@ func (p *picking) pick(flag string, picker Picker, needs map[string]string) (str } } switch { + case err != nil && len(picker.Needs) > 0 && output.StatusCode(err) == http.StatusNotFound: + // What it lists from is the problem: a project with no environments + // (an older one, framework.go) has none to type either. The command + // stops and says why, and in the home prompt the project stops being + // current, so the next command doesn't fail the same way. + err = output.Error(p.cmd, err) + for _, n := range picker.Needs { + if cur, ok := session.Get(n); ok && cur.Value == needs[n] { + session.Clear(n) + } + } + return "", err case err != nil: fmt.Fprintln(p.out, p.u.Status(ui.StatusWarn, "Couldn't list your "+picker.Plural+": "+output.ShortReason(p.cmd, err))) return p.typeID(flag, picker) @@ -273,6 +286,7 @@ func (p *picking) pick(flag string, picker Picker, needs map[string]string) (str for _, c := range choices { if c.Value == value { p.names[flag] = c.Name + p.using(picker, c.Name, value) } } return value, nil @@ -289,10 +303,31 @@ func (p *picking) take(flag string, picker Picker, c Choice, why string) string // typeID asks for the ID itself, as the form did before pickers. func (p *picking) typeID(flag string, picker Picker) (string, error) { var value string - if err := p.ask(title(picker.Noun)+" ID", "--"+flag, &value); err != nil { + kind := " ID" + if strings.HasSuffix(flag, "-alias") { + kind = " alias" // --environment-alias takes main, not an ID + } + if err := p.ask(title(picker.Noun)+kind, "--"+flag, &value); err != nil { return "", fmt.Errorf("interactive prompt: %w", err) } - return strings.TrimSpace(value), nil + value = strings.TrimSpace(value) + p.using(picker, "", value) + return value, nil +} + +// using says what was picked or typed, once its form has gone from the +// screen, so what follows (an error above all) says which one it means: +// "Using project Help bot (p1)". A pick made current (use project) says so +// itself. +func (p *picking) using(picker Picker, name, value string) { + if p.purpose != "" || value == "" { + return + } + what := value + if name != "" && name != value { + what = name + " (" + value + ")" + } + fmt.Fprintln(p.out, p.u.Status(ui.StatusDone, "Using "+picker.Noun+" "+what)) } // chooseInForm is a var so tests can answer it. diff --git a/internal/interactive/pickers_test.go b/internal/interactive/pickers_test.go index 0374fee..2e86562 100644 --- a/internal/interactive/pickers_test.go +++ b/internal/interactive/pickers_test.go @@ -7,6 +7,7 @@ import ( "context" "errors" "io" + "net/http" "os" "path/filepath" "reflect" @@ -17,6 +18,7 @@ import ( "github.com/spf13/cobra" "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/sdk/models/sdkerrors" "github.com/voiceflow/cli/internal/session" "github.com/voiceflow/cli/internal/ui" ) @@ -439,3 +441,56 @@ func TestTheHeaderWaitsForSomethingToAsk(t *testing.T) { t.Errorf("two environments, a list: header %d times, err %v", headers, err) } } + +// A pick says what was picked once its list has gone, so what follows says +// which one it means. +func TestAPickSaysWhatWasPicked(t *testing.T) { + isolatePicks(t) + (&fakePicker{choices: []Choice{{Value: "p1", Name: "Help bot"}, {Value: "p2", Name: "Sales bot"}}}).register("project-id", "project") + s := newSession("read-instructions", "project-id") + s.picks["Project"] = "p2" + if _, err := s.fill(fields("project-id")); err != nil { + t.Fatal(err) + } + if !strings.Contains(s.out.String(), "Using project Sales bot (p2)") { + t.Errorf("said %q", s.out.String()) + } + + typed := newSession("read-instructions", "environment-alias") + (&fakePicker{err: errors.New("offline")}).register("environment-alias", "environment") + typed.typing = "main" + if _, err := typed.fill(fields("environment-alias")); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(typed.asked, []string{"Environment alias"}) || !strings.Contains(typed.out.String(), "Using environment main") { + t.Errorf("asked %q, said %q", typed.asked, typed.out.String()) + } +} + +// When the list it needs answers 404 (a project with no environments), +// typing one would fail too: the command stops instead of asking. +func TestAMissingParentStopsInsteadOfAsking(t *testing.T) { + isolatePicks(t) + notFound := sdkerrors.NewSDKDefaultError("API error occurred", 404, `{"message":"Project does not have any environments"}`, + &http.Response{StatusCode: 404, Header: http.Header{}}) + (&fakePicker{err: notFound}).register("environment-alias", "environment", "project-id") + s := newSession("read-instructions", "project-id", "environment-alias") + _ = s.cmd.Flags().Set("project-id", "p1") + s.cmd.SetErr(io.Discard) + if _, err := s.fill(fields("environment-alias")); err == nil || len(s.asked) != 0 { + t.Errorf("err %v, asked %q", err, s.asked) + } + + // In the home prompt, a project nothing can be done in stops being current. + session.Start() + t.Cleanup(session.Stop) + session.Set("project-id", "p1", "Old bot") + s = newSession("read-instructions", "project-id", "environment-alias") + s.cmd.SetErr(io.Discard) + if _, err := s.fill(fields("environment-alias")); err == nil { + t.Fatal("it should stop") + } + if _, ok := session.Get("project-id"); ok { + t.Error("the project should no longer be current") + } +} diff --git a/internal/output/explain.go b/internal/output/explain.go index 9551154..7b810e1 100644 --- a/internal/output/explain.go +++ b/internal/output/explain.go @@ -144,6 +144,9 @@ func explainWith(cmd *cobra.Command, err error, status int, body string, checkAc return Explanation{Type: "error", Title: action(cmd) + ": " + firstLine(err.Error())} } +// StatusCode is the HTTP status of an API error, or 0 for any other error. +func StatusCode(err error) int { return extractErrorStatusCode(err) } + // ShortReason is one line saying why a request failed, for a status line // that reports the failure in passing: "Couldn't list your workspaces: …". func ShortReason(cmd *cobra.Command, err error) string { @@ -159,7 +162,7 @@ func ShortReason(cmd *cobra.Command, err error) string { reason = x.Title } if x.Message != "" { - reason += " — " + x.Message + reason += " — " + forPeople(x.Message) } return reason } @@ -253,6 +256,11 @@ func explainAPI(cmd *cobra.Command, err error, status int, body string, headers x.Next = []string{"Run it again with `--debug` to see the full request and response"} } + // framework.go: a project of the other kind, which no flag fixes. + if why, next, docs, ok := explainProjectKind(cmd, status, x.Message); ok { + x.Why, x.Next, x.Docs = why, next, docs + } + // A server that says what to do knows better than these defaults. if hints := stringList(fields["hints"]); len(hints) > 0 { x.Next = hints @@ -462,7 +470,7 @@ func Render(cmd *cobra.Command, x Explanation) { var under []string if x.Message != "" { - under = append(under, x.Message) + under = append(under, forPeople(x.Message)) } under = append(under, x.Why...) under = append(under, x.Details...) diff --git a/internal/output/framework.go b/internal/output/framework.go new file mode 100644 index 0000000..e45d2e5 --- /dev/null +++ b/internal/output/framework.go @@ -0,0 +1,99 @@ +// This file is not generated by Speakeasy. It explains the two refusals a +// project of the other kind gets, which no flag can fix. Voiceflow has +// older projects (v3, made before environments, often Conversation Flow) +// and Agent Framework projects (v4), and the public API doesn't say which a +// project is; it says so only in these errors: +// +// - 404 "Project does not have any environments": the project still uses +// the fixed development, staging and production versions, and has no +// environments for any command to address. +// - 400 "Project … is not an agent project": the project uses the +// Conversation Flow framework, and agent and workflow commands work only +// in Agent Framework projects. +// +// Both are fixed in Voiceflow, in the project's settings, or by picking +// another project. + +package output + +import ( + "regexp" + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/session" +) + +const ( + migrateDocsURL = "https://www.voiceflow.com/docs/guides/building-agents/releases/migrate-to-environments" + frameworkDocsURL = "https://www.voiceflow.com/docs/documentation/build/framework/choosing-a-framework" +) + +// explainProjectKind explains a refusal that says the project is of the +// other kind. ok is false for any other error. +func explainProjectKind(cmd *cobra.Command, status int, message string) (why, next []string, docs string, ok bool) { + project := projectNamed(cmd) + switch { + case status == 404 && strings.Contains(message, "does not have any environments"): + return []string{ + capitalize(project) + " is an older Voiceflow project (v3): it still uses the fixed development, staging and production versions, and hasn't moved to environments, which vf's commands work with.", + }, []string{ + anotherProject(cmd), + "Or move it to environments in Voiceflow: Settings → General → Danger zone → Migrate to environments. Update anything that uses the old aliases first", + }, migrateDocsURL, true + case status == 400 && strings.Contains(message, "is not an agent project"): + return []string{ + capitalize(project) + " isn't an Agent Framework project: it uses Conversation Flow, and this works only in Agent Framework projects.", + }, []string{ + anotherProject(cmd), + "Or switch it to the Agentic framework in Voiceflow: Settings → General. The switch can't be undone", + }, frameworkDocsURL, true + } + return nil, nil, "", false +} + +// projectNamed is the project cmd addressed: "project Help bot (p1)" when +// the home prompt knows its name, "project p1", or "this project". +func projectNamed(cmd *cobra.Command) string { + f := cmd.Flags().Lookup("project-id") + if f == nil || f.Value.String() == "" { + return "this project" + } + id := f.Value.String() + if cur, ok := session.Get("project-id"); ok && cur.Value == id && cur.Name != "" && cur.Name != id { + return "project " + cur.Name + " (" + id + ")" + } + return "project " + id +} + +func anotherProject(cmd *cobra.Command) string { + if session.Active() { + return "`use project` picks another project" + } + return "`vf project list` shows your other projects" +} + +func capitalize(s string) string { + if s == "" { + return s + } + return strings.ToUpper(s[:1]) + s[1:] +} + +// The stable API writes some messages for the AI agents that call it: +// "Nothing was written. Tell the user that this project's workflows can only +// be changed on the canvas." A person is the user, so forPeople says it to +// them: "Tell the user that X" and "Tell the user to X" become "X", and an +// instruction only an agent can follow ("Tell the user why") goes. +var ( + tellThatOrTo = regexp.MustCompile(`Tell the user (?:that|to) (\S)`) + tellOther = regexp.MustCompile(`\s*Tell the user\b.*?\.(?:\s|$)`) +) + +func forPeople(msg string) string { + msg = tellThatOrTo.ReplaceAllStringFunc(msg, func(m string) string { + return strings.ToUpper(tellThatOrTo.FindStringSubmatch(m)[1]) + }) + return strings.TrimSpace(tellOther.ReplaceAllString(msg, " ")) +} diff --git a/internal/output/framework_test.go b/internal/output/framework_test.go new file mode 100644 index 0000000..fcaf2e5 --- /dev/null +++ b/internal/output/framework_test.go @@ -0,0 +1,75 @@ +// This file is not generated by Speakeasy. It covers framework.go. + +package output + +import ( + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/session" +) + +func noLookup(*cobra.Command) (Access, bool) { return Access{}, false } + +// A project of the other kind gets a reason and a fix in Voiceflow, not +// "check the ID", which is right. +func TestAnOlderProjectIsExplained(t *testing.T) { + withCredential(t, Credential{Kind: CredentialSession}) + cmd := projectGet(t) + _ = cmd.Flags().Set("project-id", "p1") + + body := `{"statusCode":404,"message":"Project does not have any environments"}` + x := explainWith(cmd, apiError(404, body, nil), 404, body, noLookup) + got := joined(x) + for _, want := range []string{"Project p1 is an older Voiceflow project (v3)", "Migrate to environments", "`vf project list` shows your other projects"} { + if !strings.Contains(got, want) { + t.Errorf("missing %q in:\n%s", want, got) + } + } + if strings.Contains(got, "may be wrong") || x.Docs != migrateDocsURL { + t.Errorf("the ID isn't the problem; docs %q:\n%s", x.Docs, got) + } + + session.Start() + t.Cleanup(session.Stop) + session.Set("project-id", "p1", "Help bot") + got = joined(explainWith(cmd, apiError(404, body, nil), 404, body, noLookup)) + if !strings.Contains(got, "Project Help bot (p1) is an older") || !strings.Contains(got, "`use project` picks another project") { + t.Errorf("in the home prompt it names the project and offers use:\n%s", got) + } +} + +func TestAConversationFlowProjectIsExplained(t *testing.T) { + withCredential(t, Credential{Kind: CredentialSession}) + cmd := projectGet(t) + _ = cmd.Flags().Set("project-id", "p1") + body := `{"statusCode":400,"message":"Project p1 is not an agent project, and the workflow operations work only in agent projects. Nothing was read or written. Tell the user that this project's workflows can only be changed on the canvas."}` + x := explainWith(cmd, apiError(400, body, nil), 400, body, noLookup) + got := joined(x) + for _, want := range []string{"isn't an Agent Framework project: it uses Conversation Flow", "Settings → General. The switch can't be undone"} { + if !strings.Contains(got, want) { + t.Errorf("missing %q in:\n%s", want, got) + } + } + if x.Docs != frameworkDocsURL { + t.Errorf("docs %q", x.Docs) + } +} + +// Messages the API writes for agents are said to the person instead. +func TestMessagesForAgentsAreSaidToPeople(t *testing.T) { + for in, want := range map[string]string{ + "Nothing was written. Tell the user that this project's workflows can only be changed on the canvas.": "Nothing was written. This project's workflows can only be changed on the canvas.", + "It has no value. Tell the user to set the value in the Voiceflow UI.": "It has no value. Set the value in the Voiceflow UI.", + "The block was split. Tell the user you split the block, and why. Then go on.": "The block was split. Then go on.", + "Tell the user why.": "", + "Project not found": "Project not found", + "Call voiceflow_x.get.": "Call voiceflow_x.get.", + } { + if got := forPeople(in); got != want { + t.Errorf("forPeople(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/ui/DESIGN.md b/internal/ui/DESIGN.md index 1ce1304..3057998 100644 --- a/internal/ui/DESIGN.md +++ b/internal/ui/DESIGN.md @@ -348,9 +348,15 @@ flag lists). - **Organizations** come from your workspaces. The API has no organizations endpoint and no organization names, so each is named by its workspaces (`Acme, Support +2 more`), and one you have no workspace in is not listed. -- **Type an ID…** ends every list, for an ID that is not in it. A list that - fails or comes back empty says so (`⚠ Couldn't list your workspaces: …`) - and asks for the ID, as the form did before. +- **Type an ID…** ends every list, for an ID that is not in it (an alias, + for `--environment-alias`). A list that fails or comes back empty says so + (`⚠ Couldn't list your workspaces: …`) and asks for the ID, as the form did + before. One that answers 404 for what it lists from, as a project with no + environments does, stops the command instead: a typed ID would fail the + same way, and the error says why (Errors, below). +- **What was picked or typed is said** once its form has gone from the + screen, `✓ Using project Help bot (p1)`, so the lines after it, an error + above all, say which one they mean. - **Only where the form runs:** at a terminal, outside agent mode, without `--no-interactive`. Agents and scripts get the error naming the flag, as before. While a list loads, the spinner says what it loads @@ -432,7 +438,10 @@ never both: - **Under `⎿`**: the server's own message when it says more than the status (`Project not found`, never `Unauthorized`), then why, then the fields the server rejected, each with the flag that sets it (`name: Required (--name)`). - No raw JSON: `-o json` and `--debug` have the body. + No raw JSON: `-o json` and `--debug` have the body. A message the API wrote + for an AI agent is said to the person: "Tell the user that X" reads "X", + and an instruction only an agent can follow is left out; agent mode gets + the message as sent. - **Next** steps are ones a person can take now, most likely first. Commands are in Accent. A step never sends someone the wrong way: a 403 does not say to sign in, and a refused browser session is not called an expired token. @@ -447,6 +456,17 @@ never both: makes: the organization or workspace the command named, and whether you're in it. A member is told to ask an owner or admin; a stranger to check the ID. Lines in passing (a picker's warning) skip the lookup. +- **A project of the other kind** is named as one, since no flag fixes it. + The public API doesn't say whether a project is an older one (v3, made + before environments, often Conversation Flow) or an Agent Framework one + (v4); its refusals do (`internal/output/framework.go`). A 404 "Project + does not have any environments" says the project still uses the fixed + development, staging and production versions, and points to Migrate to + environments; a 400 "is not an agent project" says it uses Conversation + Flow, and points to the Agentic framework switch, which can't be undone. + Both offer another project first. A project picked in the home prompt + that turns out to have no environments stops being current, so the next + command doesn't fail the same way. - **Off a terminal** it is `Error: …` and `-`, with commands in 'quotes', so CI logs stay greppable and steps stay pasteable. - **In agent mode** the same content is one JSON object on stderr: From 34f1a54c774b56079bd5e4c541aabac34d216639 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:31:20 -0500 Subject: [PATCH 17/30] fix(client): --timeout no longer prints nothing and exits 0 With -o json or --jq, the SDK skips deserialization and returns an unread body, which vf reads after the call. The SDK's own timeout cancels its context as the call returns, so that read raced the cancel: on a real network most runs printed nothing and exited 0, which a script takes for success. --timeout now wraps the HTTP client (timeout.go): the deadline runs until the body is closed, as http.Client.Timeout does. A read that is cut off (deadline, cancel, network timeout) is an error that explain.go reports as a timeout; a body the SDK already read is still "no raw body". The timeout explanation also named an empty server URL ("Check the server URL , which comes from VF_SERVER_URL") when the error carried no URL; it now names the setting's value. --- internal/client/client.go | 7 ++-- internal/client/timeout.go | 57 +++++++++++++++++++++++++++ internal/client/timeout_test.go | 70 +++++++++++++++++++++++++++++++++ internal/output/explain.go | 16 +++++++- internal/output/explain_test.go | 6 +++ internal/output/output.go | 24 +++-------- internal/output/rawbody.go | 44 +++++++++++++++++++++ internal/output/rawbody_test.go | 46 ++++++++++++++++++++++ 8 files changed, 248 insertions(+), 22 deletions(-) create mode 100644 internal/client/timeout.go create mode 100644 internal/client/timeout_test.go create mode 100644 internal/output/rawbody.go create mode 100644 internal/output/rawbody_test.go diff --git a/internal/client/client.go b/internal/client/client.go index 8675b5e..04407fe 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -39,12 +39,12 @@ func NewClient(cmd *cobra.Command) (*sdk.VoiceflowSDK, error) { } // Timeout (always available) + var timeout time.Duration if timeoutStr := resolveStringFlag(cmd, "timeout"); timeoutStr != "" { - timeout, err := time.ParseDuration(timeoutStr) + timeout, err = time.ParseDuration(timeoutStr) if err != nil { return nil, fmt.Errorf("invalid --timeout value %q: %w", timeoutStr, err) } - sdkOpts = append(sdkOpts, sdk.WithTimeout(timeout)) } // Diagnostics and test client composition. @@ -53,7 +53,8 @@ func NewClient(cmd *cobra.Command) (*sdk.VoiceflowSDK, error) { if testClient := testclient.NewTestHTTPClient(); testClient != nil { httpClient = testClient } - httpClient = WrapClientForSpinner(cmd, httpClient) // spinner.go: ✻ while a request is in flight + httpClient = WrapClientForTimeout(httpClient, timeout) // timeout.go: --timeout covers reading the response too + httpClient = WrapClientForSpinner(cmd, httpClient) // spinner.go: ✻ while a request is in flight httpClient = WrapClientForDiagnostics(cmd, httpClient) sdkOpts = append(sdkOpts, sdk.WithClient(httpClient)) return sdk.New(sdkOpts...), nil diff --git a/internal/client/timeout.go b/internal/client/timeout.go new file mode 100644 index 0000000..9dc459f --- /dev/null +++ b/internal/client/timeout.go @@ -0,0 +1,57 @@ +// This file is not generated by Speakeasy. It applies --timeout to the whole +// request, reading the response included. +// +// The SDK's own timeout (sdk.WithTimeout) cancels its context as the call +// returns. With -o json and --jq the SDK skips deserialization and hands back +// an unread body, which vf reads after that, so the read raced the cancel: +// some runs printed nothing and exited 0. Here the deadline runs until the +// body is closed, as http.Client.Timeout does, and a deadline that passes +// mid-read is an error (context.DeadlineExceeded) that explain.go reports as +// a timeout. + +package client + +import ( + "context" + "io" + "net/http" + "sync" + "time" +) + +// WrapClientForTimeout limits each request, response body included, to d. +func WrapClientForTimeout(inner HTTPClient, d time.Duration) HTTPClient { + if d <= 0 { + return inner + } + return &timeoutClient{inner: inner, d: d} +} + +type timeoutClient struct { + inner HTTPClient + d time.Duration +} + +func (c *timeoutClient) Do(req *http.Request) (*http.Response, error) { + ctx, cancel := context.WithTimeout(req.Context(), c.d) + res, err := c.inner.Do(req.WithContext(ctx)) + if err != nil || res == nil || res.Body == nil { + cancel() + return res, err + } + res.Body = &cancelOnClose{ReadCloser: res.Body, cancel: cancel} + return res, nil +} + +// cancelOnClose releases the request's deadline once its body is closed. +type cancelOnClose struct { + io.ReadCloser + cancel context.CancelFunc + once sync.Once +} + +func (b *cancelOnClose) Close() error { + err := b.ReadCloser.Close() + b.once.Do(b.cancel) + return err +} diff --git a/internal/client/timeout_test.go b/internal/client/timeout_test.go new file mode 100644 index 0000000..b7cf90c --- /dev/null +++ b/internal/client/timeout_test.go @@ -0,0 +1,70 @@ +// This file is not generated by Speakeasy. + +package client + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +// slowBody answers with headers at once and the body after delay. +func slowBody(t *testing.T, delay time.Duration) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.(http.Flusher).Flush() + select { + case <-time.After(delay): + _, _ = io.WriteString(w, `{"ok":true}`) + case <-r.Context().Done(): + } + })) + t.Cleanup(srv.Close) + return srv +} + +// The body is read after Do returns, as -o json does: the deadline must +// still allow it. +func TestTimeoutCoversReadingTheBodyLater(t *testing.T) { + srv := slowBody(t, 30*time.Millisecond) + c := WrapClientForTimeout(&http.Client{}, 2*time.Second) + req, _ := http.NewRequest(http.MethodGet, srv.URL, nil) + res, err := c.Do(req) + if err != nil { + t.Fatal(err) + } + time.Sleep(60 * time.Millisecond) // the SDK has returned by now + body, err := io.ReadAll(res.Body) + res.Body.Close() + if err != nil || string(body) != `{"ok":true}` { + t.Fatalf("got %q, %v; want the whole body", body, err) + } +} + +func TestTimeoutCutsOffASlowBody(t *testing.T) { + srv := slowBody(t, 2*time.Second) + c := WrapClientForTimeout(&http.Client{}, 80*time.Millisecond) + req, _ := http.NewRequest(http.MethodGet, srv.URL, nil) + res, err := c.Do(req) + if err != nil { + t.Fatal(err) + } + _, err = io.ReadAll(res.Body) + res.Body.Close() + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("got %v, want context.DeadlineExceeded", err) + } +} + +func TestNoTimeoutLeavesTheClientAlone(t *testing.T) { + inner := &http.Client{} + if WrapClientForTimeout(inner, 0) != HTTPClient(inner) { + t.Fatal("a zero timeout should not wrap the client") + } +} diff --git a/internal/output/explain.go b/internal/output/explain.go index 7b810e1..4e314e2 100644 --- a/internal/output/explain.go +++ b/internal/output/explain.go @@ -380,7 +380,11 @@ func explainTransport(cmd *cobra.Command, err error) (Explanation, bool) { } serverStep := "Check your internet connection, and any VPN or proxy" if source := serverURLSource(cmd); source != "" { - serverStep = "Check the server URL " + target + ", which comes from " + source + named := target + if named == "" { // a body read cut off has no URL in its error: name the setting's value + named = configuredServerURL(cmd) + } + serverStep = "Check the server URL " + named + ", which comes from " + source } var dnsErr *net.DNSError @@ -615,6 +619,16 @@ func serverURLSource(cmd *cobra.Command) string { return "" } +// configuredServerURL is the server URL a person set, wherever they set it. +func configuredServerURL(cmd *cobra.Command) string { + if cmd != nil { + if f := cmd.Flags().Lookup("server-url"); f != nil && f.Changed { + return f.Value.String() + } + } + return config.GetString("server-url") +} + // waitStep says how long to wait before retrying, from a Retry-After header // (seconds, or an HTTP date). func waitStep(retryAfter string) string { diff --git a/internal/output/explain_test.go b/internal/output/explain_test.go index a93dd9e..c5a8f5b 100644 --- a/internal/output/explain_test.go +++ b/internal/output/explain_test.go @@ -315,6 +315,12 @@ func TestRequestsThatGotNoAnswer(t *testing.T) { if x := ExplainError(cmd, cases["timeout"].err); !strings.Contains(x.Why[0], "within --timeout 300ms") { t.Errorf("why = %q, want the timeout named", x.Why) } + + // A body read cut off by --timeout carries no URL: the setting's value is named instead. + cutOff := fmt.Errorf("reading the response: %w", context.DeadlineExceeded) + if x := ExplainError(cmd, cutOff); x.Type != "timeout" || !strings.Contains(strings.Join(x.Next, "\n"), "Check the server URL https://api.example.com, which comes from --server-url") { + t.Errorf("got %+v, want a timeout naming the server URL", x) + } } // Off a terminal: "Error:" and "-" for the glyphs, and commands in quotes, so diff --git a/internal/output/output.go b/internal/output/output.go index fe5bcef..eaf505e 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -160,7 +160,7 @@ func Result(cmd *cobra.Command, res interface{}) error { // === BINARY CHECK (must be before raw passthrough) === // Binary responses (io.ReadCloser, []byte) bypass all formatting. - // This prevents tryReadRawBody from consuming binary as JSON. + // This prevents readRawBody from consuming binary as JSON. if binaryContent := extractResultContent(res); binaryContent != nil { if rc, ok := binaryContent.(io.ReadCloser); ok { defer rc.Close() @@ -178,7 +178,11 @@ func Result(cmd *cobra.Command, res interface{}) error { // Read it directly for lossless JSON output, avoiding the // deserialize-then-reserialize round-trip. if format == "json" || jqExpr != "" { - if rawBody := tryReadRawBody(res); len(rawBody) > 0 { + rawBody, readErr := readRawBody(res) // rawbody.go: a read cut off by --timeout is an error, not empty output + if readErr != nil { + return Error(cmd, readErr) + } + if len(rawBody) > 0 { if includeHeaders { headers := extractResponseHeaders(res) var parsed interface{} @@ -497,22 +501,6 @@ func Error(cmd *cobra.Command, err error) error { return AlreadyReported(err) // see reported.go } -// tryReadRawBody attempts to read the raw HTTP response body from the response -// envelope. Returns the body bytes if the body was unread (skip-deserialization -// was active), or nil if the body was already consumed (normal deserialization). -func tryReadRawBody(res interface{}) []byte { - httpRes := extractHTTPResponse(res) - if httpRes == nil || httpRes.Body == nil { - return nil - } - rawBody, err := io.ReadAll(httpRes.Body) - httpRes.Body.Close() - if err != nil || len(rawBody) == 0 { - return nil - } - return rawBody -} - // derefToStruct dereferences pointer/interface values and validates the result // is a struct. Returns the dereferenced value and true, or a zero Value and false. func derefToStruct(v reflect.Value) (reflect.Value, bool) { diff --git a/internal/output/rawbody.go b/internal/output/rawbody.go new file mode 100644 index 0000000..8a7f384 --- /dev/null +++ b/internal/output/rawbody.go @@ -0,0 +1,44 @@ +// This file is not generated by Speakeasy. It reads the unread response body +// that -o json and --jq print as is. +// +// A body the SDK already read and closed has nothing left, and that stays +// "no raw body" as before. A read cut off by --timeout or Ctrl-C is +// different: swallowing it printed nothing and exited 0, which a script +// takes for success. That is now an error, which explain.go reports as a +// timeout (or a cancel). + +package output + +import ( + "context" + "errors" + "fmt" + "io" + "net" +) + +// readRawBody returns the response's unread body, nil when there is none, +// or an error when reading it was cut off. +func readRawBody(res interface{}) ([]byte, error) { + httpRes := extractHTTPResponse(res) + if httpRes == nil || httpRes.Body == nil { + return nil, nil + } + raw, err := io.ReadAll(httpRes.Body) + httpRes.Body.Close() + if err != nil && cutOff(err) { + return nil, fmt.Errorf("reading the response: %w", err) + } + if err != nil || len(raw) == 0 { + return nil, nil + } + return raw, nil +} + +// cutOff is whether err ended a read early: a deadline, a cancel or a +// network timeout, as opposed to a body that was already read. +func cutOff(err error) bool { + var netErr net.Error + return errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) || + (errors.As(err, &netErr) && netErr.Timeout()) +} diff --git a/internal/output/rawbody_test.go b/internal/output/rawbody_test.go new file mode 100644 index 0000000..6065514 --- /dev/null +++ b/internal/output/rawbody_test.go @@ -0,0 +1,46 @@ +// This file is not generated by Speakeasy. + +package output + +import ( + "context" + "errors" + "io" + "net/http" + "strings" + "testing" +) + +type failingBody struct{ err error } + +func (b failingBody) Read([]byte) (int, error) { return 0, b.err } +func (b failingBody) Close() error { return nil } + +func envelope(body io.ReadCloser) interface{} { + return &struct{ RawResponse *http.Response }{RawResponse: &http.Response{Body: body}} +} + +func TestARawBodyIsRead(t *testing.T) { + got, err := readRawBody(envelope(io.NopCloser(strings.NewReader(`{"a":1}`)))) + if err != nil || string(got) != `{"a":1}` { + t.Fatalf("got %q, %v", got, err) + } +} + +// A read cut off by --timeout used to print nothing and exit 0. +func TestACutOffReadIsAnError(t *testing.T) { + for _, cause := range []error{context.DeadlineExceeded, context.Canceled} { + _, err := readRawBody(envelope(failingBody{cause})) + if !errors.Is(err, cause) { + t.Errorf("%v: got %v, want an error wrapping it", cause, err) + } + } +} + +// A body the SDK already read stays "no raw body", as before. +func TestAnAlreadyReadBodyIsNotAnError(t *testing.T) { + got, err := readRawBody(envelope(failingBody{errors.New("http: read on closed response body")})) + if err != nil || got != nil { + t.Fatalf("got %q, %v; want nothing and no error", got, err) + } +} From dfed2e1686eee223ce5e254e9b48cce5817716d1 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:33:41 -0500 Subject: [PATCH 18/30] fix(flagutil): variant flags on optional unions no longer panic A union that is optional and nullable is an OptionalNullable[T], a map holding *T, not a struct. buildUnionField looked its variants up on the map type, so documented flags such as `message add-variant/update-variant --condition.script.code` and `api-tool create/update --body-param.raw-input.content` crashed vf with a Go stack trace (exit 2). The variants are now looked up on T, and the built *T goes back into the map as its set value (unionnullable.go, two one-line hooks in metadata.go). The union's own JSON flag already worked and is unchanged. A new test sends every dotted variant flag in the command tree through --dry-run; with the fix taken out it reports 16 panics. --- internal/cli/unionflags_test.go | 121 +++++++++++++++++++++++++++++ internal/flagutil/metadata.go | 4 + internal/flagutil/unionnullable.go | 37 +++++++++ 3 files changed, 162 insertions(+) create mode 100644 internal/cli/unionflags_test.go create mode 100644 internal/flagutil/unionnullable.go diff --git a/internal/cli/unionflags_test.go b/internal/cli/unionflags_test.go new file mode 100644 index 0000000..edebcd7 --- /dev/null +++ b/internal/cli/unionflags_test.go @@ -0,0 +1,121 @@ +// This file is not generated by Speakeasy. It covers flagutil/unionnullable.go +// across every command. + +package cli + +import ( + "bytes" + "fmt" + "regexp" + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/output" +) + +var firstOption = regexp.MustCompile(`options: ([^,\s\]]+)`) + +// sampleValue is a value a flag will parse: an enum's first option, a +// number, a bool, or text. +func sampleValue(f *pflag.Flag) string { + if m := firstOption.FindStringSubmatch(f.Usage); m != nil { + return m[1] + } + switch f.Value.Type() { + case "bool": + return "true" + case "int", "int32", "int64", "float32", "float64": + return "1" + } + return "x" +} + +// dryRun runs args with --dry-run in a fresh command tree and reports a +// panic as an error. +func dryRun(args []string) (out string, err error) { + root, err := NewRootCommand() + if err != nil { + return "", err + } + var buf bytes.Buffer + root.SetOut(&buf) + root.SetErr(&buf) + root.SetArgs(append(args, "--dry-run", "--no-interactive")) + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("panic: %v", r) + } + }() + _ = root.Execute() + return buf.String(), nil +} + +// Every documented variant field (--condition.script.code and the like) +// builds a request instead of crashing vf. +func TestEveryVariantFlagBuildsARequest(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", "http://127.0.0.1:1") + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + tried := 0 + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + if !c.Runnable() { + return + } + var required []string + var dotted []*pflag.Flag + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if strings.Contains(f.Name, ".") { + dotted = append(dotted, f) + } + if strings.Contains(f.Usage, "[required]") && !strings.Contains(f.Name, ".") { + required = append(required, "--"+f.Name, sampleValue(f)) + } + }) + path := strings.Fields(c.CommandPath())[1:] + for _, f := range dotted { + args := append(append(append([]string{}, path...), required...), "--"+f.Name, sampleValue(f)) + tried++ + if _, err := dryRun(args); err != nil { + t.Errorf("vf %s: %v", strings.Join(args, " "), err) + } + } + } + walk(root) + if tried < 10 { + t.Fatalf("only %d variant flags found; the walk is broken", tried) + } +} + +// The two flags the usability sweep found crashing now send the variant. +func TestOptionalNullableVariantsAreSent(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", "http://127.0.0.1:1") + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + + cases := map[string][]string{ + `"type": "script"`: {"message", "update-variant", "-m", "m1", "-p", "p1", "-e", "main", "--variant-id", "v1", + "--condition.script.code", "return 1", "--agent-mode=false"}, + `"type": "raw-input"`: {"api-tool", "create", "-p", "p1", "-e", "main", "--name", "t", "--http-method", "post", + "--body-param.raw-input.content", "hello", "--agent-mode=false"}, + } + for want, args := range cases { + out, err := dryRun(args) + if err != nil || !strings.Contains(out, want) { + t.Errorf("vf %s: %v\n%s\nwant the body to carry %s", strings.Join(args, " "), err, out, want) + } + } +} diff --git a/internal/flagutil/metadata.go b/internal/flagutil/metadata.go index 7646d9e..4397654 100644 --- a/internal/flagutil/metadata.go +++ b/internal/flagutil/metadata.go @@ -1174,6 +1174,7 @@ func buildUnionField(cmd *cobra.Command, root reflect.Value, m FlagMeta) error { } // Priority 2 & 3: Per-variant flags (discriminated only) + unionType = unionValueType(unionType) // unionnullable.go: an OptionalNullable[T]'s variants live on T for _, v := range u.Variants { if !HasAnyFlagWithPrefix(cmd, v.FlagName) { continue @@ -1226,6 +1227,9 @@ func buildUnionField(cmd *cobra.Command, root reflect.Value, m FlagMeta) error { // setUnionFieldValue sets a union field on the request struct. // Handles both value (Shape) and pointer (*Shape) field types. func setUnionFieldValue(field reflect.Value, val reflect.Value, isPtr bool) { + if setOptionalNullable(field, val) { // unionnullable.go: an OptionalNullable[T] holds the built *T + return + } if isPtr { // field is *UnionType, val is *UnionType from reflect.New field.Set(val) diff --git a/internal/flagutil/unionnullable.go b/internal/flagutil/unionnullable.go new file mode 100644 index 0000000..13ecd5a --- /dev/null +++ b/internal/flagutil/unionnullable.go @@ -0,0 +1,37 @@ +// This file is not generated by Speakeasy. It lets a union that is optional +// and nullable be built from its variant flags. +// +// Such a field is optionalnullable.OptionalNullable[T]: a map[bool]*T, not a +// struct. buildUnionField looked its variants up on that map type, so a flag +// like `message update-variant --condition.script.code` or `api-tool create +// --body-param.raw-input.content` panicked ("reflect: FieldByName of +// non-struct type"). The variants live on T, and the built *T goes back into +// the map as its set value. The union's own JSON flag (--condition '{…}') +// already worked and is unchanged. + +package flagutil + +import "reflect" + +// unionValueType is the type a union's variants live on: T for an +// OptionalNullable[T], else t itself. +func unionValueType(t reflect.Type) reflect.Type { + if t.Kind() == reflect.Map && t.Key().Kind() == reflect.Bool && + t.Elem().Kind() == reflect.Ptr && t.Elem().Elem().Kind() == reflect.Struct { + return t.Elem().Elem() + } + return t +} + +// setOptionalNullable sets field, an OptionalNullable[T], to hold val, a *T. +// It reports whether field was one; if not, it leaves field alone. +func setOptionalNullable(field, val reflect.Value) bool { + t := field.Type() + if unionValueType(t) == t || val.Kind() != reflect.Ptr || val.Type() != t.Elem() { + return false + } + m := reflect.MakeMapWithSize(t, 1) + m.SetMapIndex(reflect.ValueOf(true), val) + field.Set(m) + return true +} From dc33dce91fb4497e2994ae1c7c0c9864e0f46954 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:34:54 -0500 Subject: [PATCH 19/30] fix(interactive): type a secret's value unseen `vf secret set-value` without --value asked for the secret in a plain text field, so it showed on screen and stayed in the terminal's scrollback. A form field that holds a secret now echoes dots (secretinput.go): the secret commands' generic --value and --default-value, known by their description, and any flag whose name ends in secret, password, token, api key or private key, the rule client/redact.go uses for request bodies. --- internal/interactive/interactive.go | 3 ++ internal/interactive/secretinput.go | 45 +++++++++++++++++++ internal/interactive/secretinput_test.go | 56 ++++++++++++++++++++++++ 3 files changed, 104 insertions(+) create mode 100644 internal/interactive/secretinput.go create mode 100644 internal/interactive/secretinput_test.go diff --git a/internal/interactive/interactive.go b/internal/interactive/interactive.go index 2bd28d6..4824cc3 100644 --- a/internal/interactive/interactive.go +++ b/internal/interactive/interactive.go @@ -553,6 +553,9 @@ func buildStringInput(m flagutil.FlagMeta, title, desc string) (huh.Field, flagB Description(desc). Placeholder(m.DefaultStr). Value(&val) + if isSecretFlag(m) { // secretinput.go: a secret is typed unseen + field = field.EchoMode(huh.EchoModePassword) + } if m.Required { field = field.Validate(func(s string) error { if strings.TrimSpace(s) == "" { diff --git a/internal/interactive/secretinput.go b/internal/interactive/secretinput.go new file mode 100644 index 0000000..728e5e7 --- /dev/null +++ b/internal/interactive/secretinput.go @@ -0,0 +1,45 @@ +// This file is not generated by Speakeasy. It keeps a secret off the screen +// while it is typed into a form. +// +// `vf secret set-value` without --value asked for the value in a plain text +// field, so the secret showed on screen and stayed in the terminal's +// scrollback, unlike `gh secret set`. A field that holds a secret now echoes +// dots. The secret commands carry it in generic fields (--value on +// set-value, --default-value on create), so those are known by their +// description; any other flag is known by its name, as client/redact.go +// knows a secret field in a request body. + +package interactive + +import ( + "strings" + "unicode" + + "github.com/voiceflow/cli/internal/flagutil" +) + +// secretNameEnds end the normalized name of a flag that holds a secret. +var secretNameEnds = []string{"secret", "secretkey", "password", "token", "apikey", "privatekey"} + +// isSecretFlag is whether m's value is a secret, to be typed unseen. +func isSecretFlag(m flagutil.FlagMeta) bool { + name := m.FlagName + if i := strings.LastIndex(name, "."); i >= 0 { + name = name[i+1:] + } + if (name == "value" || name == "default-value") && strings.Contains(strings.ToLower(m.Description), "secret") { + return true + } + norm := strings.Map(func(r rune) rune { + if r == '-' || r == '_' { + return -1 + } + return unicode.ToLower(r) + }, name) + for _, end := range secretNameEnds { + if strings.HasSuffix(norm, end) { + return true + } + } + return false +} diff --git a/internal/interactive/secretinput_test.go b/internal/interactive/secretinput_test.go new file mode 100644 index 0000000..784f423 --- /dev/null +++ b/internal/interactive/secretinput_test.go @@ -0,0 +1,56 @@ +// This file is not generated by Speakeasy. + +package interactive + +import ( + "strings" + "testing" + + "github.com/charmbracelet/huh" + "github.com/charmbracelet/x/ansi" + + "github.com/voiceflow/cli/internal/flagutil" +) + +func TestSecretFlagsAreKnown(t *testing.T) { + secret := []flagutil.FlagMeta{ + // secret set-value and secret create, as generated + {FlagName: "value", Description: "The secret value to store. Write-only — it can never be read back through this API. [required]"}, + {FlagName: "default-value", Description: "The secret's value, written to the 'main' environment's published version."}, + {FlagName: "credentials.api-key-secret"}, + {FlagName: "webhook-secret-key"}, + {FlagName: "password"}, + {FlagName: "access-token"}, + } + plain := []flagutil.FlagMeta{ + {FlagName: "value", Description: "The variable's default value"}, + {FlagName: "name", Description: "The secret's name"}, + {FlagName: "max-tokens"}, + {FlagName: "secret-id"}, + {FlagName: "token-id"}, + } + for _, m := range secret { + if !isSecretFlag(m) { + t.Errorf("--%s should be typed unseen", m.FlagName) + } + } + for _, m := range plain { + if isSecretFlag(m) { + t.Errorf("--%s should show what is typed", m.FlagName) + } + } +} + +// The form field for a secret's value never shows the value. +func TestASecretIsTypedUnseen(t *testing.T) { + m := flagutil.FlagMeta{FlagName: "value", Kind: flagutil.FlagKindString, Required: true, + Description: "The secret value to store. Write-only — it can never be read back through this API. [required]"} + field, binding := buildFormField(m) + *binding.strVal = "hunter2-correct-horse" + input := field.(*huh.Input) + input.Value(binding.strVal) + input.Focus() + if view := ansi.Strip(input.View()); strings.Contains(view, "hunter2") { + t.Errorf("the secret shows on screen:\n%s", view) + } +} From df52ad017ab02b4fbe5968c68b3ddba7b583ffbc Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:39:24 -0500 Subject: [PATCH 20/30] fix(flagutil): give a script's own input back, and read --body - MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A body command read any non-terminal stdin as its body, so a command run from a script took the script's input: `bash < script.sh` lost every line after vf, and `while read -r n; do vf …; done < names.txt` stopped after one pass, both failing as "failed to parse stdin as JSON". When the flags already hold the body and stdin is a file whose contents aren't JSON, vf now seeks the file back and goes on with the flags. Piped JSON still merges with the flags, as the README documents, and a pipe is read as before. `--body -` reads the body from stdin on purpose. --- internal/flagutil/metadata.go | 12 +- internal/flagutil/stdin.go | 74 +++++++++++ internal/flagutil/stdinflags_test.go | 175 +++++++++++++++++++++++++++ 3 files changed, 258 insertions(+), 3 deletions(-) create mode 100644 internal/flagutil/stdinflags_test.go diff --git a/internal/flagutil/metadata.go b/internal/flagutil/metadata.go index 4397654..57d649a 100644 --- a/internal/flagutil/metadata.go +++ b/internal/flagutil/metadata.go @@ -227,7 +227,10 @@ func BuildRequest[T any](cmd *cobra.Command, meta []FlagMeta, bodyFieldPath stri // Priority 1: --body flag (explicit whole-body JSON) if bodyFlagName != "" && FlagChanged(cmd, bodyFlagName) { - bodyJSON, _ := GetStringFlag(cmd, bodyFlagName) + bodyJSON, err := bodyFlagValue(cmd, bodyFlagName) // stdin.go: `--body -` reads stdin + if err != nil { + return nil, err + } if bodyJSON != "" { if bodyFieldPath != "" { bodyField, err := navigateToField(v, bodyFieldPath) @@ -255,7 +258,7 @@ func BuildRequest[T any](cmd *cobra.Command, meta []FlagMeta, bodyFieldPath stri // Bounded: an open pipe that never sends data and never closes would // otherwise block here forever, and in an agent's shell a silent socket // is no body at all. See internal/flagutil/stdin.go. - stdinData, err := readStdinBody(cmd) + stdinData, err := readStdinBodyFor(cmd, meta, bodyFieldPath) // stdin.go: a file that isn't a body goes back to the caller if err != nil { return nil, fmt.Errorf("failed to read stdin: %w", err) } @@ -331,7 +334,10 @@ func BuildRequestBody[T any](cmd *cobra.Command, flagName string, annotations st var requestData string if FlagChanged(cmd, flagName) { - requestData, _ = GetStringFlag(cmd, flagName) + var err error + if requestData, err = bodyFlagValue(cmd, flagName); err != nil { // stdin.go: `--body -` reads stdin + return nil, err + } } else { // Same rules as BuildRequest above. stdin, err := readStdinBody(cmd) diff --git a/internal/flagutil/stdin.go b/internal/flagutil/stdin.go index 5e526c1..b10ae42 100644 --- a/internal/flagutil/stdin.go +++ b/internal/flagutil/stdin.go @@ -38,10 +38,13 @@ package flagutil import ( + "bytes" + "encoding/json" "errors" "fmt" "io" "os" + "strings" "sync" "time" @@ -158,3 +161,74 @@ func (f *firstReadSignal) Read(p []byte) (int, error) { f.once.Do(func() { close(f.arrived) }) return n, err } + +// A file on stdin that isn't a body goes back to the caller. +// +// Stdin is read as the body whenever it isn't a terminal, and piped JSON +// merges with the flags: README, "Request Body Input". So a command run from +// a script took the script's own input. `bash < script.sh` lost every line +// after vf, which vf then refused as JSON, and `while read -r n; do vf …; +// done < names.txt` stopped after one pass. When the flags already hold the +// body, stdin is a file and what vf read isn't JSON, it was never meant as a +// body: vf seeks the file back to where it found it and goes on with the +// flags. A pipe can't be put back, so a pipe is read as before. `--body -` +// reads the body from stdin on purpose, as gh's `--input -` does. + +// readStdinBodyFor is readStdinBody for a command built from meta, with a +// file that isn't a body put back. +func readStdinBodyFor(cmd *cobra.Command, meta []FlagMeta, bodyFieldPath string) ([]byte, error) { + start, seekable := stdinFileOffset(cmd) + data, err := readStdinBody(cmd) + body := bytes.TrimSpace(data) + if err != nil || len(body) == 0 || !seekable || json.Valid(body) || !flagsHoldTheBody(cmd, meta, bodyFieldPath) { + return data, err + } + if _, err := os.Stdin.Seek(start, io.SeekStart); err != nil { + return data, nil // it can't go back, so it is read as before + } + return nil, nil +} + +// stdinFileOffset is where vf's stdin stands, when stdin is a regular file. +func stdinFileOffset(cmd *cobra.Command) (int64, bool) { + if cmd.InOrStdin() != os.Stdin { + return 0, false + } + stat, err := os.Stdin.Stat() + if err != nil || !stat.Mode().IsRegular() { + return 0, false + } + offset, err := os.Stdin.Seek(0, io.SeekCurrent) + return offset, err == nil +} + +// flagsHoldTheBody reports whether body flags were given and every required +// body field is among them. +func flagsHoldTheBody(cmd *cobra.Command, meta []FlagMeta, bodyFieldPath string) bool { + given := false + for _, m := range meta { + if bodyFieldPath != "" && !strings.HasPrefix(m.FieldPath, bodyFieldPath+".") { + continue // a path or query parameter, not part of the body + } + set := FlagChanged(cmd, m.FlagName) || (m.Kind == FlagKindUnion && HasAnyFlagWithPrefix(cmd, m.FlagName+".")) + if set { + given = true + } else if m.Required { + return false + } + } + return given +} + +// bodyFlagValue is the whole-body flag's value; `--body -` reads it from stdin. +func bodyFlagValue(cmd *cobra.Command, name string) (string, error) { + v, _ := GetStringFlag(cmd, name) + if strings.TrimSpace(v) != "-" { + return v, nil + } + data, err := readStdinBounded(cmd.InOrStdin(), 0) + if err != nil { + return "", fmt.Errorf("failed to read stdin for --%s -: %w", name, err) + } + return strings.TrimSpace(string(data)), nil +} diff --git a/internal/flagutil/stdinflags_test.go b/internal/flagutil/stdinflags_test.go new file mode 100644 index 0000000..edf4a89 --- /dev/null +++ b/internal/flagutil/stdinflags_test.go @@ -0,0 +1,175 @@ +// This file is not generated by Speakeasy. It covers readStdinBodyFor and +// bodyFlagValue in stdin.go. + +package flagutil + +import ( + "io" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +type stdinTestBody struct { + Name string `json:"name"` + Value *string `json:"value,omitempty"` +} + +type stdinTestRequest struct { + ProjectID string + Body stdinTestBody +} + +var stdinTestMeta = []FlagMeta{ + {FlagName: "project-id", FieldPath: "ProjectID", Kind: FlagKindString, Required: true}, + {FlagName: "name", FieldPath: "Body.Name", Kind: FlagKindString, Required: true}, + {FlagName: "value", FieldPath: "Body.Value", Kind: FlagKindString, Optional: true}, +} + +// buildWithStdin runs BuildRequest for args with stdin as the command's input. +func buildWithStdin(t *testing.T, stdin io.Reader, args ...string) (*stdinTestRequest, error) { + t.Helper() + cmd := &cobra.Command{Use: "update"} + RegisterFlags(cmd, stdinTestMeta) + cmd.Flags().String("body", "", "Request body as JSON") + cmd.SetIn(stdin) + if err := cmd.ParseFlags(args); err != nil { + t.Fatal(err) + } + return BuildRequest[stdinTestRequest](cmd, stdinTestMeta, "Body", "body") +} + +// stdinFile makes a file holding content vf's stdin, standing at offset, +// as `bash < script.sh` or `while read … done < file` leave it. +func stdinFile(t *testing.T, content string, offset int64) *os.File { + t.Helper() + path := filepath.Join(t.TempDir(), "stdin") + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + if _, err := f.Seek(offset, io.SeekStart); err != nil { + t.Fatal(err) + } + saved := os.Stdin + os.Stdin = f + t.Cleanup(func() { os.Stdin = saved; f.Close() }) + return f +} + +// buildFromStdin runs BuildRequest for args with vf's own stdin. +func buildFromStdin(t *testing.T, args ...string) (*stdinTestRequest, error) { + t.Helper() + cmd := &cobra.Command{Use: "update"} + RegisterFlags(cmd, stdinTestMeta) + cmd.Flags().String("body", "", "Request body as JSON") + if err := cmd.ParseFlags(args); err != nil { + t.Fatal(err) + } + return BuildRequest[stdinTestRequest](cmd, stdinTestMeta, "Body", "body") +} + +// `while read -r n; do vf … --name "$n"; done < names.txt`: the lines after +// this one stay for the loop. +func TestAFileThatIsntABodyGoesBack(t *testing.T) { + const lines = "Alpha\nBeta\nGamma\n" + f := stdinFile(t, lines, int64(len("Alpha\n"))) + req, err := buildFromStdin(t, "--project-id", "p1", "--name", "Alpha") + if err != nil { + t.Fatal(err) + } + if req.Body.Name != "Alpha" { + t.Errorf("body = %+v", req.Body) + } + if at, _ := f.Seek(0, io.SeekCurrent); at != int64(len("Alpha\n")) { + t.Errorf("stdin left at %d, want %d: the loop loses its lines", at, len("Alpha\n")) + } +} + +// A JSON file still merges with the flags, as the README documents. +func TestAJSONFileStillMergesWithTheFlags(t *testing.T) { + stdinFile(t, `{"value":"from-file"}`, 0) + req, err := buildFromStdin(t, "--project-id", "p1", "--name", "from-flag") + if err != nil { + t.Fatal(err) + } + if req.Body.Name != "from-flag" || req.Body.Value == nil || *req.Body.Value != "from-file" { + t.Errorf("body = %+v", req.Body) + } +} + +// Without flags that hold the body, a file that isn't JSON is still an error: +// stdin is all there is. +func TestAFileThatIsntJSONIsAnErrorWhenItIsTheBody(t *testing.T) { + stdinFile(t, "not json\n", 0) + if _, err := buildFromStdin(t, "--project-id", "p1"); err == nil || !strings.Contains(err.Error(), "stdin") { + t.Errorf("err = %v", err) + } +} + +// Piped JSON merges with flags that hold the body, as the README documents. +func TestPipedJSONMergesWithTheFlags(t *testing.T) { + req, err := buildWithStdin(t, strings.NewReader(`{"value":"piped"}`), "--project-id", "p1", "--name", "from-flag") + if err != nil { + t.Fatal(err) + } + if req.Body.Name != "from-flag" || req.Body.Value == nil || *req.Body.Value != "piped" { + t.Errorf("body = %+v", req.Body) + } +} + +// A path parameter alone is not part of the body, so piped JSON is still read. +func TestAPipedBodyIsStillRead(t *testing.T) { + req, err := buildWithStdin(t, strings.NewReader(`{"name":"from-stdin","value":"v"}`), "--project-id", "p1") + if err != nil { + t.Fatal(err) + } + if req.Body.Name != "from-stdin" || req.ProjectID != "p1" { + t.Errorf("request = %+v", req) + } +} + +// A required body field still missing from the flags means stdin may hold it: +// `echo '{"name":"n"}' | vf … --value v` merges the two, as before. +func TestStdinFillsWhatTheFlagsLeaveOut(t *testing.T) { + req, err := buildWithStdin(t, strings.NewReader(`{"name":"from-stdin"}`), "--project-id", "p1", "--value", "flag") + if err != nil { + t.Fatal(err) + } + if req.Body.Name != "from-stdin" || req.Body.Value == nil || *req.Body.Value != "flag" { + t.Errorf("body = %+v", req.Body) + } +} + +// `--body -` reads the body from stdin on purpose. +func TestBodyDashReadsStdin(t *testing.T) { + req, err := buildWithStdin(t, strings.NewReader(`{"name":"dash"}`), "--project-id", "p1", "--body", "-") + if err != nil { + t.Fatal(err) + } + if req.Body.Name != "dash" { + t.Errorf("body = %+v", req.Body) + } +} + +func TestBodyDashReadsStdinForAWholeBodyCommand(t *testing.T) { + cmd := &cobra.Command{Use: "create"} + cmd.Flags().String("body", "", "") + cmd.SetIn(strings.NewReader(`{"name":"whole"}`)) + if err := cmd.ParseFlags([]string{"--body", "-"}); err != nil { + t.Fatal(err) + } + req, err := BuildRequestBody[stdinTestBody](cmd, "body", "", true) + if err != nil { + t.Fatal(err) + } + if req.Name != "whole" { + t.Errorf("body = %+v", req) + } +} From 8d5df87234314273886b158bf8282bf46e244ac3 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:46:32 -0500 Subject: [PATCH 21/30] fix(document): upload a .md file as Markdown `vf document create-text --file faq.md` sent the file as application/octet-stream, because Go's mime table has no .md and macOS lists it nowhere, and the API refused it as "invalid document type". .md and .markdown now go up as text/markdown on every machine; checked against the API, that stores a Markdown document (type "md"). When the API does refuse a file's type, the error now names the file and the types the knowledge base takes, instead of the generic --dry-run and --help hints. --- internal/cli/uploadtypes_test.go | 33 ++++++++++++++++++++++++++ internal/client/uploadtypes.go | 23 ++++++++++++++++++ internal/client/uploadtypes_test.go | 18 +++++++++++++++ internal/output/doctype.go | 36 +++++++++++++++++++++++++++++ internal/output/doctype_test.go | 31 +++++++++++++++++++++++++ internal/output/explain.go | 4 ++++ 6 files changed, 145 insertions(+) create mode 100644 internal/cli/uploadtypes_test.go create mode 100644 internal/client/uploadtypes.go create mode 100644 internal/client/uploadtypes_test.go create mode 100644 internal/output/doctype.go create mode 100644 internal/output/doctype_test.go diff --git a/internal/cli/uploadtypes_test.go b/internal/cli/uploadtypes_test.go new file mode 100644 index 0000000..d91cd50 --- /dev/null +++ b/internal/cli/uploadtypes_test.go @@ -0,0 +1,33 @@ +// This file is not generated by Speakeasy. It covers client/uploadtypes.go +// through the command that uploads a file. + +package cli + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// `vf document create-text --file faq.md` sends the file as Markdown. +func TestAMarkdownFileUploadsAsMarkdown(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", "http://127.0.0.1:1") + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + + file := filepath.Join(t.TempDir(), "faq.md") + if err := os.WriteFile(file, []byte("# FAQ\n"), 0o600); err != nil { + t.Fatal(err) + } + out, err := dryRun([]string{"document", "create-text", "-p", "p1", "-e", "main", "--file", file, "--agent-mode=false"}) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(out, "Content-Type: text/markdown") { + t.Errorf("the file part is not sent as Markdown:\n%s", out) + } +} diff --git a/internal/client/uploadtypes.go b/internal/client/uploadtypes.go new file mode 100644 index 0000000..2e08738 --- /dev/null +++ b/internal/client/uploadtypes.go @@ -0,0 +1,23 @@ +// This file is not generated by Speakeasy. It names the type of a Markdown +// file that `vf document create-text --file` uploads. +// +// The SDK labels each uploaded file with mime.TypeByExtension, and Go knows +// only a handful of extensions itself; the rest come from the machine's own +// mime.types file, if it has one. On a Mac `.md` is in none of them, so +// `--file faq.md` went up as application/octet-stream and the API refused it +// with "invalid document type", while the same file renamed to .txt uploaded. +// Labelled text/markdown, it uploads as a Markdown document (type "md") on +// every machine, rather than only where a mime.types file happens to list it. + +package client + +import "mime" + +// markdownExtensions are uploaded as Markdown. +var markdownExtensions = []string{".md", ".markdown"} + +func init() { + for _, ext := range markdownExtensions { + _ = mime.AddExtensionType(ext, "text/markdown; charset=utf-8") + } +} diff --git a/internal/client/uploadtypes_test.go b/internal/client/uploadtypes_test.go new file mode 100644 index 0000000..8326171 --- /dev/null +++ b/internal/client/uploadtypes_test.go @@ -0,0 +1,18 @@ +// This file is not generated by Speakeasy. + +package client + +import ( + "mime" + "testing" +) + +// A Markdown file uploads as Markdown wherever vf runs, not as +// application/octet-stream, which the API refuses. +func TestMarkdownUploadsAsMarkdown(t *testing.T) { + for _, ext := range []string{".md", ".markdown", ".MD"} { + if got := mime.TypeByExtension(ext); got != "text/markdown; charset=utf-8" { + t.Errorf("%s uploads as %q", ext, got) + } + } +} diff --git a/internal/output/doctype.go b/internal/output/doctype.go new file mode 100644 index 0000000..e478a6a --- /dev/null +++ b/internal/output/doctype.go @@ -0,0 +1,36 @@ +// This file is not generated by Speakeasy. It explains a file the knowledge +// base won't take. +// +// `vf document create-text --file notes.rtf` came back "invalid document type" +// with only the generic hints (--dry-run, --help), and nothing said that the +// extension was the problem: vf labels an uploaded file by its extension, and +// the knowledge base takes .txt, .md, .pdf and .docx files. A .md file failed +// the same way until client/uploadtypes.go. + +package output + +import ( + "path/filepath" + "strings" + + "github.com/spf13/cobra" +) + +// documentTypes are the file types the knowledge base takes. +const documentTypes = ".txt, .md, .pdf or .docx" + +// explainDocumentType recognizes the API refusing an uploaded file's type. +func explainDocumentType(cmd *cobra.Command, status int, message string) (why, next []string, ok bool) { + if status != 400 || !strings.Contains(strings.ToLower(message), "invalid document type") { + return nil, nil, false + } + file := "This file" + if f := cmd.Flags().Lookup("file"); f != nil && f.Value.String() != "" { + file = filepath.Base(f.Value.String()) + } + return []string{ + file + " isn't a type the knowledge base takes. vf names a file's type from its extension, and the knowledge base takes " + documentTypes + " files.", + }, []string{ + "Save it as " + documentTypes + ", converting it if need be, then run it again", + }, true +} diff --git a/internal/output/doctype_test.go b/internal/output/doctype_test.go new file mode 100644 index 0000000..00f9752 --- /dev/null +++ b/internal/output/doctype_test.go @@ -0,0 +1,31 @@ +// This file is not generated by Speakeasy. It covers doctype.go. + +package output + +import ( + "strings" + "testing" + + "github.com/spf13/cobra" +) + +// A file the knowledge base won't take is named, with the types it does take. +func TestAnUnacceptedFileTypeIsExplained(t *testing.T) { + withCredential(t, Credential{Kind: CredentialSession}) + document := &cobra.Command{Use: "document"} + cmd := &cobra.Command{Use: "create-text", Run: func(*cobra.Command, []string) {}} + cmd.Flags().String("file", "", "") + document.AddCommand(cmd) + _ = cmd.Flags().Set("file", "/home/me/kb/notes.rtf") + + body := `{"statusCode":400,"message":"invalid document type"}` + got := joined(explainWith(cmd, apiError(400, body, nil), 400, body, noLookup)) + for _, want := range []string{"notes.rtf isn't a type the knowledge base takes", ".txt, .md, .pdf or .docx"} { + if !strings.Contains(got, want) { + t.Errorf("missing %q in:\n%s", want, got) + } + } + if strings.Contains(got, "--dry-run") { + t.Errorf("the generic hints don't help here:\n%s", got) + } +} diff --git a/internal/output/explain.go b/internal/output/explain.go index 4e314e2..fa8c125 100644 --- a/internal/output/explain.go +++ b/internal/output/explain.go @@ -260,6 +260,10 @@ func explainAPI(cmd *cobra.Command, err error, status int, body string, headers if why, next, docs, ok := explainProjectKind(cmd, status, x.Message); ok { x.Why, x.Next, x.Docs = why, next, docs } + // doctype.go: a file the knowledge base doesn't take. + if why, next, ok := explainDocumentType(cmd, status, x.Message); ok { + x.Why, x.Next = why, next + } // A server that says what to do knows better than these defaults. if hints := stringList(fields["hints"]); len(hints) > 0 { From c83e6684b2575bcac3c6cc0614071a701ca5522c Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:49:52 -0500 Subject: [PATCH 22/30] fix(output): Ctrl-C during a request says Canceled MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ctrl-C while a request ran in the home prompt read as a network failure: "Couldn't get project · couldn't reach Voiceflow ⎿ context canceled. Check your internet connection". A canceled request now reads "✗ Canceled", as a form or picker closed with Ctrl-C already does. A request cut off by --timeout is still explained as timing out. --- internal/output/canceled.go | 28 +++++++++++++++++++++++ internal/output/canceled_test.go | 39 ++++++++++++++++++++++++++++++++ internal/output/explain.go | 3 +++ 3 files changed, 70 insertions(+) create mode 100644 internal/output/canceled.go create mode 100644 internal/output/canceled_test.go diff --git a/internal/output/canceled.go b/internal/output/canceled.go new file mode 100644 index 0000000..ae25075 --- /dev/null +++ b/internal/output/canceled.go @@ -0,0 +1,28 @@ +// This file is not generated by Speakeasy. It keeps Ctrl-C from reading as a +// network failure. +// +// Ctrl-C during a request in the home prompt cancels the request's context, +// and the SDK returns that as a transport error. explainTransport took it for +// a request that got no answer: "Couldn't list projects · couldn't reach +// Voiceflow … Check your internet connection". The person stopped it +// themselves, so vf says "Canceled", as it already does for a form or picker +// closed with Ctrl-C (cli/errors.go) and for any other command stopped in the +// home prompt (cli/home.go). A request cut off by --timeout is +// DeadlineExceeded, not Canceled, and is still explained as timing out. + +package output + +import ( + "context" + "errors" + + "github.com/spf13/cobra" +) + +// explainCanceled recognizes a request the person canceled. +func explainCanceled(_ *cobra.Command, err error) (Explanation, bool) { + if !errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return Explanation{}, false + } + return Explanation{Type: "canceled", Title: "Canceled"}, true +} diff --git a/internal/output/canceled_test.go b/internal/output/canceled_test.go new file mode 100644 index 0000000..8ca9e13 --- /dev/null +++ b/internal/output/canceled_test.go @@ -0,0 +1,39 @@ +// This file is not generated by Speakeasy. It covers canceled.go. + +package output + +import ( + "bytes" + "context" + "fmt" + "net/url" + "strings" + "testing" +) + +// Ctrl-C during a request reads "Canceled", not "couldn't reach Voiceflow". +func TestACanceledRequestIsNotANetworkFailure(t *testing.T) { + ResetAgentMode() + t.Cleanup(ResetAgentMode) + cmd := projectGet(t) + var out bytes.Buffer + cmd.SetErr(&out) + + err := fmt.Errorf("error sending request: %w", &url.Error{Op: "Get", URL: "https://api.voiceflow.com/v2/x", Err: context.Canceled}) + if reported := Error(cmd, err); reported == nil || reported.Error() != "" { + t.Fatalf("want the error reported, got %v", reported) + } + got := out.String() + if !strings.Contains(got, "Canceled") || strings.Contains(got, "reach") || strings.Contains(got, "internet") { + t.Errorf("got:\n%s", got) + } + if x := ExplainError(cmd, err); x.Type != "canceled" { + t.Errorf("type %q", x.Type) + } + + // A request cut off by --timeout still times out. + deadline := &url.Error{Op: "Get", URL: "https://api.voiceflow.com/v2/x", Err: context.DeadlineExceeded} + if x := ExplainError(cmd, deadline); x.Type != "timeout" { + t.Errorf("a timeout reads as %q", x.Type) + } +} diff --git a/internal/output/explain.go b/internal/output/explain.go index fa8c125..e494dd4 100644 --- a/internal/output/explain.go +++ b/internal/output/explain.go @@ -138,6 +138,9 @@ func explainWith(cmd *cobra.Command, err error, status int, body string, checkAc if status != 0 { return explainAPI(cmd, err, status, body, extractErrorResponseHeaders(err), checkAccess) } + if x, ok := explainCanceled(cmd, err); ok { // canceled.go: Ctrl-C isn't a network failure + return x + } if x, ok := explainTransport(cmd, err); ok { return x } From 60bd6209a7184e3ab7538d995f9532527af026c1 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:58:40 -0500 Subject: [PATCH 23/30] fix(ui): stop the 5s terminal query on every command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bubble Tea's init asks the terminal for its background colour (OSC 11 plus a cursor-position query) and waits up to 5s for the answer. It ran before main on every command, so under a terminal that doesn't answer (`script`, `docker run -t`, some CI ptys, emacs shells) even `vf version` and `-o json` took 5s, and a late answer could leak into the shell as `]11;rgb:…`. termbg/hold, which Go initializes before Bubble Tea, sets TERM=dumb so termenv skips the query; termbg's init, after Bubble Tea's, restores TERM and termenv's colour profile. termbg.Detect asks the real question once, just before a form, the home prompt or the explorer takes the terminal, the only places that draw adaptive colours. A test checks the init order and that TERM comes back unchanged. Under `script`: 5.02s → 0.01s for `vf version`, with the same colours. --- internal/cli/auth.go | 2 + internal/cli/configure.go | 2 + internal/cli/termquery_test.go | 68 +++++++++++++++++++++++++++++ internal/explorer/explorer.go | 2 + internal/interactive/interactive.go | 2 + internal/prompt/prompt.go | 2 + internal/termbg/hold/hold.go | 38 ++++++++++++++++ internal/termbg/termbg.go | 49 +++++++++++++++++++++ 8 files changed, 165 insertions(+) create mode 100644 internal/cli/termquery_test.go create mode 100644 internal/termbg/hold/hold.go create mode 100644 internal/termbg/termbg.go diff --git a/internal/cli/auth.go b/internal/cli/auth.go index 11d753a..d1c37de 100644 --- a/internal/cli/auth.go +++ b/internal/cli/auth.go @@ -11,6 +11,7 @@ import ( "github.com/voiceflow/cli/internal/config" "github.com/voiceflow/cli/internal/oauth" "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/termbg" "golang.org/x/term" "os" ) @@ -243,6 +244,7 @@ func authIsInteractive(cmd *cobra.Command) bool { // authFormTheme builds the form theme for auth login. func authFormTheme() *huh.Theme { + termbg.Detect() // ../termbg: ask the terminal's background before the form takes the terminal t := *huh.ThemeBase() accent := lipgloss.Color("#397DFF") diff --git a/internal/cli/configure.go b/internal/cli/configure.go index 646917f..ca05b6f 100644 --- a/internal/cli/configure.go +++ b/internal/cli/configure.go @@ -10,6 +10,7 @@ import ( "github.com/spf13/cobra" "github.com/voiceflow/cli/internal/config" "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/termbg" "github.com/voiceflow/cli/internal/usage" "golang.org/x/term" "os" @@ -158,6 +159,7 @@ func configureIsInteractive(cmd *cobra.Command) bool { // configureFormTheme builds the form theme for the configure command. func configureFormTheme() *huh.Theme { + termbg.Detect() // ../termbg: ask the terminal's background before the form takes the terminal t := *huh.ThemeBase() accent := lipgloss.Color("#397DFF") diff --git a/internal/cli/termquery_test.go b/internal/cli/termquery_test.go new file mode 100644 index 0000000..bd33c1f --- /dev/null +++ b/internal/cli/termquery_test.go @@ -0,0 +1,68 @@ +// This file is not generated by Speakeasy. It covers termbg and termbg/hold +// with the packages vf itself links. + +package cli + +import ( + "os" + "os/exec" + "regexp" + "testing" +) + +var initLine = regexp.MustCompile(`(?m)^init (\S+) @`) + +// Bubble Tea asks the terminal for its background in its init, and waits up +// to 5 seconds for an answer. termbg/hold must initialize before it, so that +// the question isn't asked, and termbg after it, to put TERM back. Go picks +// the order, so this checks the one it picked. +func TestNoTerminalQueryAtStartup(t *testing.T) { + cmd := exec.Command(os.Args[0], "-test.run=^$") + cmd.Env = append(os.Environ(), "GODEBUG=inittrace=1") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + at := map[string]int{} + for i, m := range initLine.FindAllStringSubmatch(string(out), -1) { + at[m[1]] = i + 1 + } + hold := at["github.com/voiceflow/cli/internal/termbg/hold"] + tea := at["github.com/charmbracelet/bubbletea"] + termbg := at["github.com/voiceflow/cli/internal/termbg"] + if hold == 0 || tea == 0 || termbg == 0 { + t.Fatalf("missing from the init trace: hold %d, bubbletea %d, termbg %d", hold, tea, termbg) + } + if !(hold < tea && tea < termbg) { + t.Errorf("init order hold %d, bubbletea %d, termbg %d: want hold, then Bubble Tea, then termbg", hold, tea, termbg) + } +} + +// TERM is as it was by the time vf runs. +func TestTERMIsPutBack(t *testing.T) { + if os.Getenv("VF_TEST_PRINT_TERM") == "1" { + term, ok := os.LookupEnv("TERM") + if !ok { + term = "" + } + os.Stdout.WriteString("TERM=" + term + "\n") + return + } + for _, term := range []string{"xterm-256color", ""} { + cmd := exec.Command(os.Args[0], "-test.run=^TestTERMIsPutBack$") + env := []string{"VF_TEST_PRINT_TERM=1", "HOME=" + t.TempDir()} + want := "TERM=" + if term != "" { + env = append(env, "TERM="+term) + want = "TERM=" + term + } + cmd.Env = env + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + if !regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(want) + `$`).Match(out) { + t.Errorf("started with %q, saw:\n%s", want, out) + } + } +} diff --git a/internal/explorer/explorer.go b/internal/explorer/explorer.go index 51e524b..4b652f0 100644 --- a/internal/explorer/explorer.go +++ b/internal/explorer/explorer.go @@ -8,6 +8,7 @@ import ( tea "github.com/charmbracelet/bubbletea" "github.com/spf13/cobra" + "github.com/voiceflow/cli/internal/termbg" ) // Run launches the interactive explorer TUI. @@ -15,6 +16,7 @@ import ( func Run(root *cobra.Command, version string) ([]string, error) { tree := BuildTree(root) m := newModel(tree, version) + termbg.Detect() // ../termbg: ask the terminal's background before the explorer takes the terminal p := tea.NewProgram(m, tea.WithAltScreen(), tea.WithMouseCellMotion()) result, err := p.Run() if err != nil { diff --git a/internal/interactive/interactive.go b/internal/interactive/interactive.go index 4824cc3..b058668 100644 --- a/internal/interactive/interactive.go +++ b/internal/interactive/interactive.go @@ -19,6 +19,7 @@ import ( "github.com/voiceflow/cli/internal/config" "github.com/voiceflow/cli/internal/flagutil" "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/termbg" ) // IsInteractive returns true when the CLI should use interactive features. @@ -100,6 +101,7 @@ func formWidth() int { // formTheme builds the interactive prompt theme. // Colors are injected at generation time from the interactiveTheme config. func formTheme() *huh.Theme { + termbg.Detect() // ../termbg: ask the terminal's background before the form takes the terminal t := *huh.ThemeBase() accent := lipgloss.Color("#397DFF") diff --git a/internal/prompt/prompt.go b/internal/prompt/prompt.go index f1777a9..ce8b080 100644 --- a/internal/prompt/prompt.go +++ b/internal/prompt/prompt.go @@ -13,6 +13,7 @@ import ( tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" "github.com/charmbracelet/x/ansi" + "github.com/voiceflow/cli/internal/termbg" "github.com/voiceflow/cli/internal/ui" ) @@ -45,6 +46,7 @@ const maxRows = 8 // like a shell session. func Read(opts Options) (line string, ok bool, err error) { m := newModel(opts) + termbg.Detect() // ../termbg: ask the terminal's background before the prompt takes the terminal final, err := tea.NewProgram(m, tea.WithInput(opts.In), tea.WithOutput(opts.Out)).Run() if err != nil { return "", false, err diff --git a/internal/termbg/hold/hold.go b/internal/termbg/hold/hold.go new file mode 100644 index 0000000..bede8f9 --- /dev/null +++ b/internal/termbg/hold/hold.go @@ -0,0 +1,38 @@ +// This file is not generated by Speakeasy. It holds back the terminal query +// Bubble Tea makes in its init; see ../termbg.go. +// +// It imports nothing but os, so Go initializes it before Bubble Tea: Bubble +// Tea waits on os/signal, which waits on os and sorts after this package's +// path, and Go initializes the first package, by path, whose imports are +// ready. Its init sets TERM=dumb, the one setting termenv takes to mean "don't +// query this terminal", and termbg's init, which runs after Bubble Tea's, +// puts TERM back. TestNoTerminalQueryAtStartup in the cli package fails if +// the order ever changes. + +package hold + +import "os" + +var ( + held bool + term string + hadTerm bool +) + +func init() { + term, hadTerm = os.LookupEnv("TERM") + held = os.Setenv("TERM", "dumb") == nil +} + +// Release puts TERM back as it was. +func Release() { + if !held { + return + } + held = false + if hadTerm { + _ = os.Setenv("TERM", term) + } else { + _ = os.Unsetenv("TERM") + } +} diff --git a/internal/termbg/termbg.go b/internal/termbg/termbg.go new file mode 100644 index 0000000..3beb175 --- /dev/null +++ b/internal/termbg/termbg.go @@ -0,0 +1,49 @@ +// This file is not generated by Speakeasy. It keeps vf from asking the +// terminal for its background colour unless a form is about to use it. +// +// Bubble Tea asks in its own init (tea_init.go): it writes OSC 11 and a +// cursor-position query, then waits up to 5 seconds for the answers. That ran +// before main on every command, `vf version` and `-o json` included, so a +// terminal that doesn't answer (`docker run -t`, some CI ptys, emacs shells, +// `script`) held every command for 5 seconds, and a late answer could land in +// the shell as `]11;rgb:…`. +// +// The answer only picks the light or dark shade of Lip Gloss's adaptive +// colours, which only forms, the home prompt and the explorer draw. So the +// question is held back at startup (hold/hold.go), and Lip Gloss keeps the +// answer it gives when a terminal doesn't reply: dark. Detect asks the real +// question, once, just before a form or view starts, while the terminal is +// still free to answer. Over a terminal that never answers, only that first +// form waits. + +package termbg + +import ( + "os" + "sync" + + _ "github.com/charmbracelet/bubbletea" // so this init runs after Bubble Tea's + "github.com/charmbracelet/lipgloss" + "github.com/muesli/termenv" + + "github.com/voiceflow/cli/internal/termbg/hold" +) + +func init() { + hold.Release() // Bubble Tea's init has asked, and been told not to wait + // termenv set up its default output while TERM was held; give it the + // colour profile it would have had. + out := termenv.DefaultOutput() + out.Profile = out.EnvColorProfile() +} + +var once sync.Once + +// Detect asks the terminal for its background, once, and has Lip Gloss's +// adaptive colours follow it. Call it before a form or view takes over the +// terminal: once Bubble Tea is reading input, it would eat the answer. +func Detect() { + once.Do(func() { + lipgloss.SetHasDarkBackground(termenv.NewOutput(os.Stdout).HasDarkBackground()) + }) +} From a1d689296aa16c7c00e4b8132aea6399e2162150 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:00:47 -0500 Subject: [PATCH 24/30] fix(sdk): escape an ID that goes in the URL path A path parameter went into the URL as it was, so `vf playbook get --playbook-id "a/b?x=1#frag"` asked for /v2/stable/playbook/a/b?x=1#frag: the "/" reached another endpoint, and the "?" and "#" replaced the real query, dropping projectID and environmentAlias. Each value is now escaped as one path segment, as serialized parameters already were. --- internal/cli/pathescape_test.go | 29 +++++++++++++++++++ internal/sdk/sdkinternal/utils/pathescape.go | 19 ++++++++++++ .../sdk/sdkinternal/utils/pathescape_test.go | 28 ++++++++++++++++++ internal/sdk/sdkinternal/utils/pathparams.go | 4 +-- 4 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 internal/cli/pathescape_test.go create mode 100644 internal/sdk/sdkinternal/utils/pathescape.go create mode 100644 internal/sdk/sdkinternal/utils/pathescape_test.go diff --git a/internal/cli/pathescape_test.go b/internal/cli/pathescape_test.go new file mode 100644 index 0000000..0f19725 --- /dev/null +++ b/internal/cli/pathescape_test.go @@ -0,0 +1,29 @@ +// This file is not generated by Speakeasy. It covers +// sdk/sdkinternal/utils/pathescape.go through a command. + +package cli + +import ( + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// An ID holding "/", "?" or "#" stays in its path segment, and the query +// still carries the project and environment. +func TestAnIDCantLeaveItsPathSegment(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", "http://127.0.0.1:1") + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + + out, err := dryRun([]string{"playbook", "get", "--project-id", "p1", "-e", "main", "--playbook-id", "a/b?x=1#frag", "--agent-mode=false"}) + if err != nil { + t.Fatal(err) + } + want := "/playbook/a%2Fb%3Fx=1%23frag?" + if !strings.Contains(out, want) || !strings.Contains(out, "projectID=p1") || !strings.Contains(out, "environmentAlias=main") { + t.Errorf("want %s with projectID and environmentAlias in:\n%s", want, out) + } +} diff --git a/internal/sdk/sdkinternal/utils/pathescape.go b/internal/sdk/sdkinternal/utils/pathescape.go new file mode 100644 index 0000000..4dca7cd --- /dev/null +++ b/internal/sdk/sdkinternal/utils/pathescape.go @@ -0,0 +1,19 @@ +// This file is not generated by Speakeasy. It keeps a path parameter in its +// own path segment. +// +// GenerateURL put a simple path parameter's value into the URL as it was, so +// `vf playbook get --playbook-id "a/b?x=1#frag"` asked for +// /v2/stable/playbook/a/b?x=1#frag: the "/" reached another endpoint, and the +// "?" and "#" dropped the real query, projectID and environmentAlias included. +// `vf environment delete --environment-alias "a/b"` was sent as a DELETE to a +// path Voiceflow doesn't have. Serialized parameters were already escaped +// (pathparams.go); a plain value now is too, as one segment. + +package utils + +import "net/url" + +// pathSegment is v escaped to stand as one path segment. +func pathSegment(v string) string { + return url.PathEscape(v) +} diff --git a/internal/sdk/sdkinternal/utils/pathescape_test.go b/internal/sdk/sdkinternal/utils/pathescape_test.go new file mode 100644 index 0000000..03f3dbc --- /dev/null +++ b/internal/sdk/sdkinternal/utils/pathescape_test.go @@ -0,0 +1,28 @@ +// This file is not generated by Speakeasy. It covers pathescape.go. + +package utils + +import ( + "context" + "testing" +) + +type pathEscapeRequest struct { + PlaybookID string `pathParam:"style=simple,explode=false,name=playbookID"` + EnvironmentAlias string `queryParam:"style=form,explode=true,name=environmentAlias"` +} + +// An ID stays in its own path segment, whatever it holds. +func TestAPathValueIsOneSegment(t *testing.T) { + cases := map[string]string{ + "a/b?x=1#frag": "https://api.example.com/v2/stable/playbook/a%2Fb%3Fx=1%23frag", + "has spaces": "https://api.example.com/v2/stable/playbook/has%20spaces", + "6b0cb6cc5d0b": "https://api.example.com/v2/stable/playbook/6b0cb6cc5d0b", + } + for id, want := range cases { + got, err := GenerateURL(context.Background(), "https://api.example.com", "/v2/stable/playbook/{playbookID}", pathEscapeRequest{PlaybookID: id}, nil) + if err != nil || got != want { + t.Errorf("%q: got %q, %v; want %q", id, got, err, want) + } + } +} diff --git a/internal/sdk/sdkinternal/utils/pathparams.go b/internal/sdk/sdkinternal/utils/pathparams.go index 24ede7a..363a9da 100644 --- a/internal/sdk/sdkinternal/utils/pathparams.go +++ b/internal/sdk/sdkinternal/utils/pathparams.go @@ -118,7 +118,7 @@ func getSimplePathParams(parentName string, objType reflect.Type, objValue refle if nullableValue, ok := optionalnullable.AsOptionalNullable(objValue); ok { // Handle optionalnullable.OptionalNullable[T] using GetUntyped method if value, isSet := nullableValue.GetUntyped(); isSet && value != nil { - pathParams[parentName] = valToString(value) + pathParams[parentName] = pathSegment(valToString(value)) // pathescape.go: one value, one path segment } // If not set or explicitly null, return nil (skip parameter) return pathParams @@ -173,7 +173,7 @@ func getSimplePathParams(parentName string, objType reflect.Type, objValue refle pathParams[parentName] = strings.Join(ppVals, ",") } default: - pathParams[parentName] = valToString(objValue.Interface()) + pathParams[parentName] = pathSegment(valToString(objValue.Interface())) // pathescape.go: one value, one path segment } return pathParams From f7206d132b56d393edcab1e4471a518d97427c18 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:52:03 -0500 Subject: [PATCH 25/30] fix(flagutil)!: body flags turn off reading stdin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit vf read any non-terminal stdin as a body to merge under the flags, so: - `sleep 15 | vf … --name x` waited 10s for a body that never came - `cmd | while read -r n; do vf … --name "$n"; done` ran once: the first vf swallowed the loop's remaining lines - `bash < script.sh` lost the lines after the first vf call Now stdin is read only when no body flag is given, or when asked for with `--body -`. Piped JSON with no flags is still the body, unchanged. When body flags are given and stdin is a file holding a JSON body, vf leaves it unread and prints a note saying to add `--body -`. Every --body flag's help now says how stdin is read. BREAKING CHANGE: piped JSON is no longer merged with body flags on its own. `echo '{…}' | vf --name x` used to merge the two; add `--body -` to keep that: `echo '{…}' | vf --body - --name x`. Flags still win over the piped body. --- README.md | 29 +++--- internal/cli/bodyhelp.go | 31 ++++++ internal/cli/bodyhelp_test.go | 34 ++++++ internal/cli/root.go | 1 + internal/flagutil/metadata.go | 8 +- internal/flagutil/stdin.go | 89 ++++++++-------- internal/flagutil/stdinflags_test.go | 148 ++++++++++++++++----------- test/stdin-handling.test.ts | 37 ++++++- 8 files changed, 251 insertions(+), 126 deletions(-) create mode 100644 internal/cli/bodyhelp.go create mode 100644 internal/cli/bodyhelp_test.go diff --git a/README.md b/README.md index f41252e..690a16b 100644 --- a/README.md +++ b/README.md @@ -764,29 +764,32 @@ Individual flags override `--body` values: vf --body '{"name": "John", "age": 30}' --name "Jane" ``` -### Stdin piping (lowest priority) +### Stdin -Pipe JSON into any command that accepts a request body: +With no body flags, piped JSON is the body: ```bash echo '{"name": "John", "age": 30}' | vf + +# Read body from a file +vf < request.json + +# Pipe from another command +curl -s https://example.com/data.json | vf ``` -Individual flags override stdin values: +Body flags turn stdin off, so a command run from a script or a loop never takes input that wasn't meant for it: ```bash -# Result: {name: "Jane", age: 30} -echo '{"name": "John", "age": 30}' | vf --name "Jane" +# Each pass gets its own line; vf leaves the rest for the loop +cat names.txt | while read -r name; do vf --name "$name"; done ``` -This is useful for chaining commands, reading from files, or scripting: +To merge piped JSON with flags, read it with `--body -`. Individual flags still win: ```bash -# Read body from a file -vf < request.json - -# Pipe from another command -curl -s https://example.com/data.json | vf +# Result: {name: "Jane", age: 30} +echo '{"name": "John", "age": 30}' | vf --body - --name "Jane" ``` ### Priority @@ -796,8 +799,8 @@ When multiple input methods are used, the priority is: | Priority | Source | Description | |----------|--------|-------------| | 1 (highest) | Individual flags | `--name "Jane"` always wins | -| 2 | `--body` flag | Whole-body JSON via flag | -| 3 (lowest) | Stdin | Piped JSON input | +| 2 | `--body` flag | Whole-body JSON via flag, or stdin with `--body -` | +| 3 (lowest) | Stdin | Piped JSON, read only when no body flag is given | diff --git a/internal/cli/bodyhelp.go b/internal/cli/bodyhelp.go new file mode 100644 index 0000000..1a307c8 --- /dev/null +++ b/internal/cli/bodyhelp.go @@ -0,0 +1,31 @@ +// This file is not generated by Speakeasy. It has every --body flag say how +// stdin is read. +// +// The generated help said the body "can also be provided via stdin", which was +// true of any non-terminal stdin, merged with the flags. Now body flags turn +// stdin off and `--body -` reads it (flagutil/stdin.go), and the help says so. + +package cli + +import ( + "strings" + + "github.com/spf13/cobra" +) + +// bodyFlagHelp is what --body says on every command that takes a body. +const bodyFlagHelp = "Request body as JSON (alternative to individual flags). --body - reads it from stdin; piped stdin is read on its own only when no body flag is given." + +// describeBodyFlags gives every generated --body flag bodyFlagHelp. +func describeBodyFlags(root *cobra.Command) { + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + if f := c.LocalFlags().Lookup("body"); f != nil && strings.HasPrefix(f.Usage, "Request body as JSON") { + f.Usage = bodyFlagHelp + } + for _, sub := range c.Commands() { + walk(sub) + } + } + walk(root) +} diff --git a/internal/cli/bodyhelp_test.go b/internal/cli/bodyhelp_test.go new file mode 100644 index 0000000..b023e84 --- /dev/null +++ b/internal/cli/bodyhelp_test.go @@ -0,0 +1,34 @@ +// This file is not generated by Speakeasy. It covers bodyhelp.go. + +package cli + +import ( + "testing" + + "github.com/spf13/cobra" +) + +// Every --body flag says that `--body -` reads stdin. +func TestEveryBodyFlagSaysHowStdinIsRead(t *testing.T) { + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + found := 0 + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + if f := c.LocalFlags().Lookup("body"); f != nil { + found++ + if f.Usage != bodyFlagHelp { + t.Errorf("vf %s --body: %q", c.CommandPath(), f.Usage) + } + } + for _, sub := range c.Commands() { + walk(sub) + } + } + walk(root) + if found < 100 { + t.Fatalf("only %d --body flags found; the walk is broken", found) + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index fd55e0c..9ba0105 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -239,6 +239,7 @@ func NewRootCommand() (*cobra.Command, error) { _ = rootCmd.PersistentFlags().SetAnnotation(ga.flag, "speakeasy:group", []string{ga.group}) } + describeBodyFlags(rootCmd) // bodyhelp.go: --body says how stdin is read rootCmd.SetUsageTemplate(groupedUsageTemplate()) return rootCmd, nil diff --git a/internal/flagutil/metadata.go b/internal/flagutil/metadata.go index 57d649a..71496d8 100644 --- a/internal/flagutil/metadata.go +++ b/internal/flagutil/metadata.go @@ -254,11 +254,11 @@ func BuildRequest[T any](cmd *cobra.Command, meta []FlagMeta, bodyFieldPath stri // flag) have no body for stdin to fill — consuming piped JSON there would // both surprise pipelines and re-relax required path/query params via the // bodyPrePopulated relaxation below. - if !bodyPrePopulated && (bodyFieldPath != "" || bodyFlagName != "") { + if !bodyPrePopulated && (bodyFieldPath != "" || bodyFlagName != "") && !bodyFlagsGiven(cmd, meta, bodyFieldPath) { // stdin.go: body flags turn stdin off; `--body -` turns it on // Bounded: an open pipe that never sends data and never closes would // otherwise block here forever, and in an agent's shell a silent socket // is no body at all. See internal/flagutil/stdin.go. - stdinData, err := readStdinBodyFor(cmd, meta, bodyFieldPath) // stdin.go: a file that isn't a body goes back to the caller + stdinData, err := readStdinBody(cmd) if err != nil { return nil, fmt.Errorf("failed to read stdin: %w", err) } @@ -281,6 +281,10 @@ func BuildRequest[T any](cmd *cobra.Command, meta []FlagMeta, bodyFieldPath stri } } + if !bodyPrePopulated && bodyFlagsGiven(cmd, meta, bodyFieldPath) { + warnUnreadBody(cmd, bodyFlagName) // stdin.go: a JSON file on stdin that the flags left unread + } + // When body provided via --body flag or stdin, relax Required checks for body fields // so builders don't error for fields already populated if bodyPrePopulated { diff --git a/internal/flagutil/stdin.go b/internal/flagutil/stdin.go index b10ae42..d6988b0 100644 --- a/internal/flagutil/stdin.go +++ b/internal/flagutil/stdin.go @@ -162,62 +162,57 @@ func (f *firstReadSignal) Read(p []byte) (int, error) { return n, err } -// A file on stdin that isn't a body goes back to the caller. +// Body flags turn stdin off; `--body -` turns it back on. // -// Stdin is read as the body whenever it isn't a terminal, and piped JSON -// merges with the flags: README, "Request Body Input". So a command run from -// a script took the script's own input. `bash < script.sh` lost every line -// after vf, which vf then refused as JSON, and `while read -r n; do vf …; -// done < names.txt` stopped after one pass. When the flags already hold the -// body, stdin is a file and what vf read isn't JSON, it was never meant as a -// body: vf seeks the file back to where it found it and goes on with the -// flags. A pipe can't be put back, so a pipe is read as before. `--body -` -// reads the body from stdin on purpose, as gh's `--input -` does. - -// readStdinBodyFor is readStdinBody for a command built from meta, with a -// file that isn't a body put back. -func readStdinBodyFor(cmd *cobra.Command, meta []FlagMeta, bodyFieldPath string) ([]byte, error) { - start, seekable := stdinFileOffset(cmd) - data, err := readStdinBody(cmd) - body := bytes.TrimSpace(data) - if err != nil || len(body) == 0 || !seekable || json.Valid(body) || !flagsHoldTheBody(cmd, meta, bodyFieldPath) { - return data, err - } - if _, err := os.Stdin.Seek(start, io.SeekStart); err != nil { - return data, nil // it can't go back, so it is read as before +// Stdin used to be read as the body whenever it wasn't a terminal, and merged +// with the flags. So a command run from a script or an agent's shell took +// input that was never meant for it: `sleep 15 | vf variable update … +// --default-value x` waited 10 seconds and failed, `bash < script.sh` lost +// every line after vf, and `cmd | while read -r n; do vf … --name "$n"; done` +// stopped after one pass. Now a command given any body flag doesn't read +// stdin at all, as gh reads it only for `--input -`. With no body flags, +// piped stdin is still the body, so `echo '{…}' | vf ` and +// `vf < body.json` work as before. To merge piped JSON with flags, +// which used to happen on its own, pass `--body -`: the flags still win. + +// bodyFlagsGiven reports whether any flag that fills part of the body was +// given. Path and query parameters aren't part of the body. +func bodyFlagsGiven(cmd *cobra.Command, meta []FlagMeta, bodyFieldPath string) bool { + for _, m := range meta { + if bodyFieldPath != "" && !strings.HasPrefix(m.FieldPath, bodyFieldPath+".") { + continue + } + if FlagChanged(cmd, m.FlagName) || (m.Kind == FlagKindUnion && HasAnyFlagWithPrefix(cmd, m.FlagName+".")) { + return true + } } - return nil, nil + return false } -// stdinFileOffset is where vf's stdin stands, when stdin is a regular file. -func stdinFileOffset(cmd *cobra.Command) (int64, bool) { - if cmd.InOrStdin() != os.Stdin { - return 0, false +// warnUnreadBody notes on stderr that a JSON body waiting in a file on stdin +// wasn't read, because body flags were given: `vf … --name x < body.json`, +// which used to merge the file in. It looks with ReadAt, which leaves the +// file where it was, and says nothing for a script or a list of lines, or for +// a pipe, which can't be looked into without taking what it holds. +func warnUnreadBody(cmd *cobra.Command, bodyFlagName string) { + if cmd.InOrStdin() != os.Stdin || bodyFlagName == "" { + return } stat, err := os.Stdin.Stat() if err != nil || !stat.Mode().IsRegular() { - return 0, false + return } - offset, err := os.Stdin.Seek(0, io.SeekCurrent) - return offset, err == nil -} - -// flagsHoldTheBody reports whether body flags were given and every required -// body field is among them. -func flagsHoldTheBody(cmd *cobra.Command, meta []FlagMeta, bodyFieldPath string) bool { - given := false - for _, m := range meta { - if bodyFieldPath != "" && !strings.HasPrefix(m.FieldPath, bodyFieldPath+".") { - continue // a path or query parameter, not part of the body - } - set := FlagChanged(cmd, m.FlagName) || (m.Kind == FlagKindUnion && HasAnyFlagWithPrefix(cmd, m.FlagName+".")) - if set { - given = true - } else if m.Required { - return false - } + at, err := os.Stdin.Seek(0, io.SeekCurrent) + if err != nil || stat.Size()-at <= 0 || stat.Size()-at > 1<<20 { + return + } + rest := make([]byte, stat.Size()-at) + if n, err := os.Stdin.ReadAt(rest, at); err != nil && n < len(rest) { + return + } + if body := bytes.TrimSpace(rest); len(body) > 0 && body[0] == '{' && json.Valid(body) { + fmt.Fprintf(cmd.ErrOrStderr(), "Note: stdin holds a JSON body, which isn't read when body flags are given. To merge it with the flags, add --%s -\n", bodyFlagName) } - return given } // bodyFlagValue is the whole-body flag's value; `--body -` reads it from stdin. diff --git a/internal/flagutil/stdinflags_test.go b/internal/flagutil/stdinflags_test.go index edf4a89..a4ce7e6 100644 --- a/internal/flagutil/stdinflags_test.go +++ b/internal/flagutil/stdinflags_test.go @@ -1,14 +1,17 @@ -// This file is not generated by Speakeasy. It covers readStdinBodyFor and -// bodyFlagValue in stdin.go. +// This file is not generated by Speakeasy. It covers bodyFlagsGiven, +// warnUnreadBody and bodyFlagValue in stdin.go. package flagutil import ( + "bytes" "io" "os" "path/filepath" "strings" + "sync/atomic" "testing" + "time" "github.com/spf13/cobra" ) @@ -29,20 +32,41 @@ var stdinTestMeta = []FlagMeta{ {FlagName: "value", FieldPath: "Body.Value", Kind: FlagKindString, Optional: true}, } -// buildWithStdin runs BuildRequest for args with stdin as the command's input. -func buildWithStdin(t *testing.T, stdin io.Reader, args ...string) (*stdinTestRequest, error) { +// watchedReader is stdin that records whether vf read it. +type watchedReader struct { + r io.Reader + read atomic.Bool +} + +func (w *watchedReader) Read(p []byte) (int, error) { + w.read.Store(true) + return w.r.Read(p) +} + +// stdinCommand is an update command over meta, with --body as the generated +// commands register it. +func stdinCommand(t *testing.T, args ...string) (*cobra.Command, *bytes.Buffer) { t.Helper() cmd := &cobra.Command{Use: "update"} RegisterFlags(cmd, stdinTestMeta) cmd.Flags().String("body", "", "Request body as JSON") - cmd.SetIn(stdin) + var stderr bytes.Buffer + cmd.SetErr(&stderr) if err := cmd.ParseFlags(args); err != nil { t.Fatal(err) } + return cmd, &stderr +} + +// buildWithStdin runs BuildRequest for args with stdin as the command's input. +func buildWithStdin(t *testing.T, stdin io.Reader, args ...string) (*stdinTestRequest, error) { + t.Helper() + cmd, _ := stdinCommand(t, args...) + cmd.SetIn(stdin) return BuildRequest[stdinTestRequest](cmd, stdinTestMeta, "Body", "body") } -// stdinFile makes a file holding content vf's stdin, standing at offset, +// stdinFile makes a file holding content vf's own stdin, standing at offset, // as `bash < script.sh` or `while read … done < file` leave it. func stdinFile(t *testing.T, content string, offset int64) *os.File { t.Helper() @@ -63,69 +87,55 @@ func stdinFile(t *testing.T, content string, offset int64) *os.File { return f } -// buildFromStdin runs BuildRequest for args with vf's own stdin. -func buildFromStdin(t *testing.T, args ...string) (*stdinTestRequest, error) { - t.Helper() - cmd := &cobra.Command{Use: "update"} - RegisterFlags(cmd, stdinTestMeta) - cmd.Flags().String("body", "", "Request body as JSON") - if err := cmd.ParseFlags(args); err != nil { - t.Fatal(err) - } - return BuildRequest[stdinTestRequest](cmd, stdinTestMeta, "Body", "body") -} +// `sleep 15 | vf … --name x`: body flags leave a silent pipe alone. +func TestBodyFlagsDontWaitOnStdin(t *testing.T) { + silent, w := io.Pipe() + defer w.Close() + stdin := &watchedReader{r: silent} -// `while read -r n; do vf … --name "$n"; done < names.txt`: the lines after -// this one stay for the loop. -func TestAFileThatIsntABodyGoesBack(t *testing.T) { - const lines = "Alpha\nBeta\nGamma\n" - f := stdinFile(t, lines, int64(len("Alpha\n"))) - req, err := buildFromStdin(t, "--project-id", "p1", "--name", "Alpha") + start := time.Now() + req, err := buildWithStdin(t, stdin, "--project-id", "p1", "--name", "greeting", "--value", "hi") if err != nil { t.Fatal(err) } - if req.Body.Name != "Alpha" { - t.Errorf("body = %+v", req.Body) + if took := time.Since(start); took > time.Second { + t.Errorf("waited %s on a silent stdin", took) } - if at, _ := f.Seek(0, io.SeekCurrent); at != int64(len("Alpha\n")) { - t.Errorf("stdin left at %d, want %d: the loop loses its lines", at, len("Alpha\n")) - } -} - -// A JSON file still merges with the flags, as the README documents. -func TestAJSONFileStillMergesWithTheFlags(t *testing.T) { - stdinFile(t, `{"value":"from-file"}`, 0) - req, err := buildFromStdin(t, "--project-id", "p1", "--name", "from-flag") - if err != nil { - t.Fatal(err) + if stdin.read.Load() { + t.Error("read stdin although body flags were given") } - if req.Body.Name != "from-flag" || req.Body.Value == nil || *req.Body.Value != "from-file" { + if req.Body.Name != "greeting" || req.Body.Value == nil || *req.Body.Value != "hi" { t.Errorf("body = %+v", req.Body) } } -// Without flags that hold the body, a file that isn't JSON is still an error: -// stdin is all there is. -func TestAFileThatIsntJSONIsAnErrorWhenItIsTheBody(t *testing.T) { - stdinFile(t, "not json\n", 0) - if _, err := buildFromStdin(t, "--project-id", "p1"); err == nil || !strings.Contains(err.Error(), "stdin") { - t.Errorf("err = %v", err) +// `cmd | while read -r n; do vf … --name "$n"; done`: the loop keeps its +// lines, and so does a script run with `bash < script.sh`. +func TestBodyFlagsLeaveTheCallersInput(t *testing.T) { + stdin := &watchedReader{r: strings.NewReader("Beta\nGamma\n")} + if _, err := buildWithStdin(t, stdin, "--project-id", "p1", "--name", "Alpha"); err != nil { + t.Fatal(err) + } + if stdin.read.Load() { + t.Error("read the caller's stdin although body flags were given") } -} -// Piped JSON merges with flags that hold the body, as the README documents. -func TestPipedJSONMergesWithTheFlags(t *testing.T) { - req, err := buildWithStdin(t, strings.NewReader(`{"value":"piped"}`), "--project-id", "p1", "--name", "from-flag") - if err != nil { + f := stdinFile(t, "Alpha\nBeta\nGamma\n", int64(len("Alpha\n"))) + cmd, stderr := stdinCommand(t, "--project-id", "p1", "--name", "Alpha") + if _, err := BuildRequest[stdinTestRequest](cmd, stdinTestMeta, "Body", "body"); err != nil { t.Fatal(err) } - if req.Body.Name != "from-flag" || req.Body.Value == nil || *req.Body.Value != "piped" { - t.Errorf("body = %+v", req.Body) + if at, _ := f.Seek(0, io.SeekCurrent); at != int64(len("Alpha\n")) { + t.Errorf("stdin moved to %d: the loop loses its lines", at) + } + if stderr.Len() > 0 { + t.Errorf("lines that aren't a body need no note: %q", stderr) } } -// A path parameter alone is not part of the body, so piped JSON is still read. -func TestAPipedBodyIsStillRead(t *testing.T) { +// With no body flags, piped stdin is the body, as before. A path parameter +// isn't a body flag. +func TestWithoutBodyFlagsStdinIsTheBody(t *testing.T) { req, err := buildWithStdin(t, strings.NewReader(`{"name":"from-stdin","value":"v"}`), "--project-id", "p1") if err != nil { t.Fatal(err) @@ -135,27 +145,43 @@ func TestAPipedBodyIsStillRead(t *testing.T) { } } -// A required body field still missing from the flags means stdin may hold it: -// `echo '{"name":"n"}' | vf … --value v` merges the two, as before. -func TestStdinFillsWhatTheFlagsLeaveOut(t *testing.T) { - req, err := buildWithStdin(t, strings.NewReader(`{"name":"from-stdin"}`), "--project-id", "p1", "--value", "flag") +// Without body flags, a stdin that isn't JSON is still an error: it is all +// there is. +func TestWithoutBodyFlagsStdinThatIsntJSONIsAnError(t *testing.T) { + if _, err := buildWithStdin(t, strings.NewReader("not json\n"), "--project-id", "p1"); err == nil || !strings.Contains(err.Error(), "stdin") { + t.Errorf("err = %v", err) + } +} + +// `echo '{…}' | vf … --body - --name x` merges, and the flags win. +func TestBodyDashMergesWithTheFlags(t *testing.T) { + req, err := buildWithStdin(t, strings.NewReader(`{"name":"from-stdin","value":"piped"}`), "--project-id", "p1", "--body", "-", "--name", "from-flag") if err != nil { t.Fatal(err) } - if req.Body.Name != "from-stdin" || req.Body.Value == nil || *req.Body.Value != "flag" { + if req.Body.Name != "from-flag" || req.Body.Value == nil || *req.Body.Value != "piped" { t.Errorf("body = %+v", req.Body) } } -// `--body -` reads the body from stdin on purpose. -func TestBodyDashReadsStdin(t *testing.T) { - req, err := buildWithStdin(t, strings.NewReader(`{"name":"dash"}`), "--project-id", "p1", "--body", "-") +// `vf … --name x < body.json` used to merge the file in. It no longer does, +// and says how to. +func TestAnUnreadJSONFileIsNoted(t *testing.T) { + f := stdinFile(t, `{"name":"from-file"}`, 0) + cmd, stderr := stdinCommand(t, "--project-id", "p1", "--name", "from-flag") + req, err := BuildRequest[stdinTestRequest](cmd, stdinTestMeta, "Body", "body") if err != nil { t.Fatal(err) } - if req.Body.Name != "dash" { + if req.Body.Name != "from-flag" { t.Errorf("body = %+v", req.Body) } + if !strings.Contains(stderr.String(), "add --body -") { + t.Errorf("no note: %q", stderr) + } + if at, _ := f.Seek(0, io.SeekCurrent); at != 0 { + t.Errorf("looking moved stdin to %d", at) + } } func TestBodyDashReadsStdinForAWholeBodyCommand(t *testing.T) { diff --git a/test/stdin-handling.test.ts b/test/stdin-handling.test.ts index 6bad149..9db6d7f 100644 --- a/test/stdin-handling.test.ts +++ b/test/stdin-handling.test.ts @@ -15,6 +15,9 @@ // // So: cold producers, through `sh -c`, asserting the body actually arrived. // +// Stdin is read only when no body flag is given, or with `--body -`; the last +// two groups cover that. +// // Requires the CLI binary at the repo root: go build -o vf ./cmd/vf import { execa } from 'execa'; @@ -141,10 +144,16 @@ describe("stdin in an agent's shell", () => { // Only a socket is cut short. A shell pipe is what `producer | vf` gives vf, // in agent mode too, so a producer slower than the socket's wait still has - // its body read, and merged with the flags as the README documents. - it('still reads a slow shell producer, merged with the flags', async () => { + // its body read. + it('still reads a slow shell producer', async () => { + const result = await pipeline(`sh -c 'sleep 1; echo "{\\"prompt\\":\\"from-slow-pipe\\"}"'`, { env: AGENT }); + expect(result.timedOut).toBe(false); + expect(sentPrompt(result.stderr + result.stdout), 'slow body dropped in agent mode').toBe('from-slow-pipe'); + }); + + it('merges a slow shell producer with the flags when asked with --body -', async () => { const result = await pipeline(`sh -c 'sleep 1; echo "{\\"prompt\\":\\"from-slow-pipe\\"}"'`, { - flags: '--instructions from-flag', + flags: '--body - --instructions from-flag', env: AGENT, }); expect(result.timedOut).toBe(false); @@ -153,6 +162,28 @@ describe("stdin in an agent's shell", () => { }); }); +// Body flags turn stdin off; `--body -` turns it back on. Stdin that a +// script or a loop is reading was never meant as vf's body. +describe('body flags leave stdin alone', () => { + it('takes the body from the flags while an open pipe stays silent', async () => { + // The producer outlives the 10s stdin budget, so a vf that read stdin would + // fail here; one that leaves it alone sends the flags. + const result = await pipeline('sleep 11', { flags: '--prompt from-flag', timeout: 40_000 }); + expect(result.timedOut).toBe(false); + expect(result.exitCode, result.stderr).toBe(0); + expect(sentPrompt(result.stderr + result.stdout)).toBe('from-flag'); + }); + + it('leaves a while-read loop its lines', async () => { + const result = await execa({ reject: false, timeout: 20_000, stdin: 'ignore' })('sh', [ + '-c', + `printf 'one\\ntwo\\nthree\\n' | while read -r n; do ${VF} ${ARGS} --prompt "$n" 2>&1; done`, + ]); + const prompts = [...result.stdout.matchAll(/"prompt":\s*"([^"]*)"/g)].map((m) => m[1]); + expect(prompts, result.stdout).toEqual(['one', 'two', 'three']); + }); +}); + describe('backward compatibility', () => { // execa's `input:` is how the rest of the suite pipes stdin. It must keep // working, but it is deliberately NOT counted as coverage for the cases above. From df865fd378c81db2aa285ef323c3f91445ad84b7 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:02:00 -0500 Subject: [PATCH 26/30] fix(flagutil): say when body flags left a piped body unread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Body flags turn off reading stdin, so `echo '{"name":…,"color":…}' | vf variable create -n x` failed with "needs --color-param" and no word that the piped body was skipped. A missing body flag now says that body flags were given, so stdin wasn't read, and to add `--body -` to read it. It says so only for a pipe or a redirected file, never for a terminal, /dev/null or an agent's socket, and only on the error, so a `while read` loop that succeeds stays quiet. `--body -` with an empty stdin said "needs --name"; it now says stdin was empty and shows how to pipe the body in. --- internal/cli/errors.go | 9 ++++ internal/cli/stdinhint_test.go | 68 ++++++++++++++++++++++++ internal/flagutil/metadata.go | 2 +- internal/flagutil/stdin.go | 79 +++++++++++++++++++++++----- internal/flagutil/stdinflags_test.go | 64 +++++++++++++++++++++- 5 files changed, 208 insertions(+), 14 deletions(-) create mode 100644 internal/cli/stdinhint_test.go diff --git a/internal/cli/errors.go b/internal/cli/errors.go index 8018eb9..4a0f027 100644 --- a/internal/cli/errors.go +++ b/internal/cli/errors.go @@ -184,6 +184,11 @@ func explainCLIError(cmd *cobra.Command, err error) output.Explanation { x.Next = []string{"Check your internet connection and run it again", "If it keeps failing, sign in again: `vf auth login`"} return x } + if errors.Is(err, flagutil.ErrStdinEmpty) { + x.Type = "stdin_empty" + x.Next = trimAll(strings.Split(msg, "\n")[1:]) + return x + } if errors.Is(err, flagutil.ErrStdinTimeout) { lines := strings.Split(msg, "\n") x.Type = "stdin_timeout" @@ -317,6 +322,10 @@ func explainMissingFlag(cmd *cobra.Command, flag string) output.Explanation { x.Next = append(x.Next, "`"+list+"` shows the values it takes") } x.Next = append(x.Next, "Pass it: `"+cmd.CommandPath()+" --"+flag+" `") + if body, ok := flagutil.StdinLeftUnread(cmd, flag); ok { + x.Why = append(x.Why, "Body flags were given, so vf didn't read stdin.") + x.Next = append([]string{"If it's in the body on stdin, add --" + body + " - to read it: the flags still win"}, x.Next...) + } if interactive.HasPicker(flag) && !output.IsAgentMode() && !interactive.IsInteractive(cmd) { x.Next = append(x.Next, "At a terminal, without --no-interactive, vf lets you pick it from a list") } diff --git a/internal/cli/stdinhint_test.go b/internal/cli/stdinhint_test.go new file mode 100644 index 0000000..da1fb27 --- /dev/null +++ b/internal/cli/stdinhint_test.go @@ -0,0 +1,68 @@ +// This file is not generated by Speakeasy. It covers what errors.go says +// when body flags left a body on stdin unread, and when `--body -` finds +// stdin empty. + +package cli + +import ( + "bytes" + "os" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// runWithStdin runs args with stdin a pipe holding content, and explains the +// error it ends with. +func runWithStdin(t *testing.T, content string, args ...string) output.Explanation { + t.Helper() + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", "http://127.0.0.1:1") + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + w.WriteString(content) + w.Close() + saved := os.Stdin + os.Stdin = r + t.Cleanup(func() { os.Stdin = saved; r.Close() }) + + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + root.SetOut(&buf) + root.SetErr(&buf) + root.SetArgs(append(args, "--agent-mode=false", "--no-interactive", "--dry-run")) + cmd, err := root.ExecuteC() + if err == nil { + t.Fatalf("no error; output:\n%s", buf.String()) + } + return explainCLIError(cmd, err) +} + +// `echo '{"name":…,"color":…}' | vf variable create -n x` needs --color-param; +// the error says the piped body wasn't read, and how to read it. +func TestAMissingFlagSaysThePipedBodyWasntRead(t *testing.T) { + x := runWithStdin(t, `{"name":"from_stdin","color":"#515A63"}`, + "variable", "create", "-p", "p1", "-e", "main", "-n", "from_flag") + all := explained(x) + for _, want := range []string{"needs --color-param", "Body flags were given, so vf didn't read stdin.", "add --body - to read it"} { + if !strings.Contains(all, want) { + t.Errorf("missing %q in:\n%s", want, all) + } + } +} + +// `vf variable create --body - 1<<20 { - return + return false } rest := make([]byte, stat.Size()-at) if n, err := os.Stdin.ReadAt(rest, at); err != nil && n < len(rest) { - return + return false } - if body := bytes.TrimSpace(rest); len(body) > 0 && body[0] == '{' && json.Valid(body) { - fmt.Fprintf(cmd.ErrOrStderr(), "Note: stdin holds a JSON body, which isn't read when body flags are given. To merge it with the flags, add --%s -\n", bodyFlagName) + body := bytes.TrimSpace(rest) + return len(body) > 0 && body[0] == '{' && json.Valid(body) +} + +// StdinLeftUnread reports whether cmd's body flags left a piped or redirected +// stdin unread when --flag, a part of the body, went missing, and names the +// whole-body flag that reads stdin (`--body -`). +func StdinLeftUnread(cmd *cobra.Command, flag string) (bodyFlag string, ok bool) { + if unread.cmd == nil || unread.cmd != cmd { + return "", false + } + for _, m := range unread.bodyFlags { + if m.FlagName == flag || (m.Kind == FlagKindUnion && strings.HasPrefix(flag, m.FlagName+".")) { + return unread.bodyFlag, true + } } + return "", false } // bodyFlagValue is the whole-body flag's value; `--body -` reads it from stdin. @@ -225,5 +275,10 @@ func bodyFlagValue(cmd *cobra.Command, name string) (string, error) { if err != nil { return "", fmt.Errorf("failed to read stdin for --%s -: %w", name, err) } - return strings.TrimSpace(string(data)), nil + body := strings.TrimSpace(string(data)) + if body == "" { + // Not "needs --name": the body was asked for and never came. + return "", fmt.Errorf("%[1]w, and --%[2]s - reads the body from it\nPipe the body in: echo '{…}' | %[3]s --%[2]s -", ErrStdinEmpty, name, cmd.CommandPath()) + } + return body, nil } diff --git a/internal/flagutil/stdinflags_test.go b/internal/flagutil/stdinflags_test.go index a4ce7e6..85499c3 100644 --- a/internal/flagutil/stdinflags_test.go +++ b/internal/flagutil/stdinflags_test.go @@ -1,10 +1,11 @@ // This file is not generated by Speakeasy. It covers bodyFlagsGiven, -// warnUnreadBody and bodyFlagValue in stdin.go. +// stdinLeftUnread, StdinLeftUnread and bodyFlagValue in stdin.go. package flagutil import ( "bytes" + "errors" "io" "os" "path/filepath" @@ -199,3 +200,64 @@ func TestBodyDashReadsStdinForAWholeBodyCommand(t *testing.T) { t.Errorf("body = %+v", req) } } + +// stdinPipe makes a pipe holding content, closed for writing, vf's own stdin, +// as `echo '{…}' | vf …` leaves it. +func stdinPipe(t *testing.T, content string) { + t.Helper() + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + if _, err := w.WriteString(content); err != nil { + t.Fatal(err) + } + w.Close() + saved := os.Stdin + os.Stdin = r + t.Cleanup(func() { os.Stdin = saved; r.Close(); unread.cmd = nil }) +} + +// `echo '{"name":…}' | vf … --value v` fails for want of --name; vf remembers +// that the pipe went unread, for the error to say so. Only for a body flag. +func TestAnUnreadPipeIsRemembered(t *testing.T) { + stdinPipe(t, `{"name":"from-stdin"}`) + cmd, _ := stdinCommand(t, "--project-id", "p1", "--value", "v") + if _, err := BuildRequest[stdinTestRequest](cmd, stdinTestMeta, "Body", "body"); err == nil || !strings.Contains(err.Error(), "--name") { + t.Fatalf("err = %v", err) + } + if body, ok := StdinLeftUnread(cmd, "name"); !ok || body != "body" { + t.Errorf("--name: %q %v", body, ok) + } + if _, ok := StdinLeftUnread(cmd, "project-id"); ok { + t.Error("a path parameter can't come from the body") + } + if _, ok := StdinLeftUnread(&cobra.Command{}, "name"); ok { + t.Error("remembered for another command") + } +} + +// /dev/null, like a terminal or an agent's socket, isn't stdin anyone piped +// a body into. +func TestDevNullIsntAnUnreadBody(t *testing.T) { + f, err := os.Open(os.DevNull) + if err != nil { + t.Fatal(err) + } + saved := os.Stdin + os.Stdin = f + t.Cleanup(func() { os.Stdin = saved; f.Close(); unread.cmd = nil }) + cmd, _ := stdinCommand(t, "--project-id", "p1", "--value", "v") + _, _ = BuildRequest[stdinTestRequest](cmd, stdinTestMeta, "Body", "body") + if _, ok := StdinLeftUnread(cmd, "name"); ok { + t.Error("/dev/null remembered as an unread body") + } +} + +// `vf … --body - Date: Mon, 30 Nov 2026 00:04:45 -0500 Subject: [PATCH 27/30] fix(output): name the field a request body is missing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A body the SDK couldn't serialize failed with the head of Go's marshal chain, cut at 200 characters, so the cause never showed: Couldn't create turn: error serializing request body: json: error calling MarshalJSON for type *components.StableTestTurnCreateRequest: json: error calling MarshalJSON for type …StableTestTurnCreateRequestUser:… Testers read the SDK's source to learn that `variableStates` was missing. The chain's types name the path to the field, so vf now says "the body has no value for user.payload.variableStates", or "the body is none of its forms" when no variant was given, and gives the SDK's cause in full. Any other serialization failure shows its cause rather than the chain's head. --- internal/output/badbody.go | 100 ++++++++++++++++++++++++++++++++ internal/output/badbody_test.go | 70 ++++++++++++++++++++++ internal/output/explain.go | 3 + test/dry-run.test.ts | 2 +- 4 files changed, 174 insertions(+), 1 deletion(-) create mode 100644 internal/output/badbody.go create mode 100644 internal/output/badbody_test.go diff --git a/internal/output/badbody.go b/internal/output/badbody.go new file mode 100644 index 0000000..e1a44b6 --- /dev/null +++ b/internal/output/badbody.go @@ -0,0 +1,100 @@ +// This file is not generated by Speakeasy. It explains a request body vf +// couldn't build. +// +// A body missing a value the SDK can't do without failed with the head of +// Go's marshal chain, cut at 200 characters: +// +// Couldn't create turn: error serializing request body: json: error calling +// MarshalJSON for type *components.StableTestTurnCreateRequest: json: error +// calling MarshalJSON for type *components.StableTestTurnCreateRequestUser:… +// +// The cause sits at the far end ("could not marshal union type +// StableTestTurnCreateRequestVariableStates1: all fields are null"), so it +// never showed, and the testers who hit it read the SDK's source to learn +// that variableStates was missing. The chain's types name the path to the +// field, each the root type's name plus the field's: Request → User → +// Payload1 → VariableStates1 is user.payload.variableStates. vf now says +// that, and gives the cause in full. + +package output + +import ( + "regexp" + "strings" + "unicode" + + "github.com/spf13/cobra" +) + +var ( + marshalTypeRE = regexp.MustCompile(`error calling MarshalJSON for type \*?(?:\w+\.)?(\w+): `) + nullUnionRE = regexp.MustCompile(`could not marshal union type (\w+): all fields are null`) +) + +// explainBadBody explains a request body the SDK couldn't serialize. The +// request wasn't sent. +func explainBadBody(cmd *cobra.Command, err error) (Explanation, bool) { + msg := strings.TrimSpace(err.Error()) + if !strings.Contains(msg, "error serializing request body") { + return Explanation{}, false + } + var types []string + for _, m := range marshalTypeRE.FindAllStringSubmatch(msg, -1) { + types = append(types, m[1]) + } + cause := msg + if locs := marshalTypeRE.FindAllStringIndex(msg, -1); len(locs) > 0 { + cause = msg[locs[len(locs)-1][1]:] + } else if _, after, ok := strings.Cut(msg, "error serializing request body: "); ok { + cause = after + } + help := "`" + cmd.CommandPath() + " --help` lists the body's fields" + said := "The SDK said: " + strings.TrimSuffix(cause, ".") + "." + x := Explanation{ + Type: "invalid_body", + Title: action(cmd) + ": vf couldn't build the request body", + Why: []string{"The request wasn't sent.", said}, + Next: []string{help}, + } + if m := nullUnionRE.FindStringSubmatch(cause); m != nil { + root := m[1] + if len(types) > 0 { + root = types[0] + } + if path := marshalPath(root, append(types, m[1])); path != "" { + x.Title = action(cmd) + ": the body has no value for " + path + } else { + x.Title = action(cmd) + ": the body is none of its forms" + x.Why = []string{"The body takes one of several forms, and none was given, so the request wasn't sent.", said} + x.Next = []string{"`" + cmd.CommandPath() + " --help` lists the forms and their flags"} + } + } + return x, true +} + +// marshalPath turns a marshal chain's types into the path to the field they +// lead to: under root StableTestTurnCreateRequest, the types …User, +// …Payload1 and …VariableStates1 are user.payload.variableStates. A type +// that isn't named after root ends the path, as nothing more can be told. +func marshalPath(root string, types []string) string { + var path []string + for _, t := range types { + if t == root { + continue + } + seg, ok := strings.CutPrefix(t, root) + if !ok { + break + } + seg = strings.TrimRightFunc(seg, unicode.IsDigit) + if seg == "" { + continue + } + r := []rune(seg) + r[0] = unicode.ToLower(r[0]) + if s := string(r); len(path) == 0 || path[len(path)-1] != s { + path = append(path, s) + } + } + return strings.Join(path, ".") +} diff --git a/internal/output/badbody_test.go b/internal/output/badbody_test.go new file mode 100644 index 0000000..852af74 --- /dev/null +++ b/internal/output/badbody_test.go @@ -0,0 +1,70 @@ +// This file is not generated by Speakeasy. It covers badbody.go. + +package output + +import ( + "errors" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +// The errors the SDK returned for `vf test turn create` with a user turn +// that has no variableStates, and with no body at all. +const ( + missingFieldErr = "error serializing request body: json: error calling MarshalJSON for type *components.StableTestTurnCreateRequest: json: error calling MarshalJSON for type *components.StableTestTurnCreateRequestUser: json: error calling MarshalJSON for type *components.StableTestTurnCreateRequestPayload1: json: error calling MarshalJSON for type *components.StableTestTurnCreateRequestVariableStates1: could not marshal union type StableTestTurnCreateRequestVariableStates1: all fields are null" + noFormErr = "error serializing request body: json: error calling MarshalJSON for type *components.StableTestTurnCreateRequest: could not marshal union type StableTestTurnCreateRequest: all fields are null" +) + +func turnCreate() *cobra.Command { + root := &cobra.Command{Use: "vf"} + test := &cobra.Command{Use: "test"} + turn := &cobra.Command{Use: "turn"} + create := &cobra.Command{Use: "create", Short: "Create a turn"} + root.AddCommand(test) + test.AddCommand(turn) + turn.AddCommand(create) + return create +} + +// The missing field is named by its path, not lost past 200 characters. +func TestAnUnbuildableBodyNamesTheMissingField(t *testing.T) { + x := explainWith(turnCreate(), errors.New(missingFieldErr), 0, "", nil) + if x.Type != "invalid_body" || !strings.HasSuffix(x.Title, ": the body has no value for user.payload.variableStates") { + t.Errorf("title %q (%s)", x.Title, x.Type) + } + if why := strings.Join(x.Why, " "); !strings.Contains(why, "wasn't sent") || !strings.Contains(why, "StableTestTurnCreateRequestVariableStates1: all fields are null") { + t.Errorf("why %q", why) + } + if len(x.Next) == 0 || !strings.Contains(x.Next[0], "vf test turn create --help") { + t.Errorf("next %q", x.Next) + } + + x = explainWith(turnCreate(), errors.New(noFormErr), 0, "", nil) + if !strings.HasSuffix(x.Title, ": the body is none of its forms") { + t.Errorf("no form: %q", x.Title) + } + + other := "error serializing request body: json: error calling MarshalJSON for type *components.Thing: json: unsupported value: NaN" + x = explainWith(turnCreate(), errors.New(other), 0, "", nil) + if !strings.HasSuffix(x.Title, ": vf couldn't build the request body") || !strings.Contains(strings.Join(x.Why, " "), "json: unsupported value: NaN.") { + t.Errorf("other: %+v", x) + } +} + +func TestMarshalPath(t *testing.T) { + for _, c := range []struct { + root string + types []string + want string + }{ + {"R", []string{"R", "RUser", "RPayload1", "RVariableStates1", "RVariableStates1"}, "user.payload.variableStates"}, + {"R", []string{"R", "R"}, ""}, + {"R", []string{"R", "RBody", "Other", "RLater"}, "body"}, + } { + if got := marshalPath(c.root, c.types); got != c.want { + t.Errorf("%v: %q, want %q", c.types, got, c.want) + } + } +} diff --git a/internal/output/explain.go b/internal/output/explain.go index e494dd4..49d46b3 100644 --- a/internal/output/explain.go +++ b/internal/output/explain.go @@ -144,6 +144,9 @@ func explainWith(cmd *cobra.Command, err error, status int, body string, checkAc if x, ok := explainTransport(cmd, err); ok { return x } + if x, ok := explainBadBody(cmd, err); ok { // badbody.go: name the missing field, not the head of the chain + return x + } return Explanation{Type: "error", Title: action(cmd) + ": " + firstLine(err.Error())} } diff --git a/test/dry-run.test.ts b/test/dry-run.test.ts index 697ddf6..9a35591 100644 --- a/test/dry-run.test.ts +++ b/test/dry-run.test.ts @@ -111,7 +111,7 @@ describe('--dry-run', () => { expect(result.exitCode).toBe(1); expect(result.stderr).not.toContain(PREVIEWED); - expect(result.stderr).toContain('error serializing request body'); + expect(result.stderr).toContain("the request wasn't sent"); }); }); From bca9e5e54f59aee7ff3edbbdff64acad337de698 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:07:05 -0500 Subject: [PATCH 28/30] fix(home): keep a secret's value out of the prompt's history MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `secret create --name KEY --default-value hunter2` typed in the home prompt came back whole on ↑, the value in clear on screen and in the terminal's scrollback, though the form that asks for the same value hides it. Lines about secrets were already kept off disk; the line kept for ↑ now also loses each flag that holds a secret (as the form knows them: --value and --default-value on secret commands, --token, --password, --api-key and the like) with its value, and on such a command the whole-body --body. Run again, it asks for the value in the hidden form instead of sending a stand-in. --- internal/cli/historysecret.go | 100 ++++++++++++++++++++++++++++ internal/cli/historysecret_test.go | 53 +++++++++++++++ internal/cli/home.go | 7 +- internal/interactive/secretinput.go | 7 ++ 4 files changed, 164 insertions(+), 3 deletions(-) create mode 100644 internal/cli/historysecret.go create mode 100644 internal/cli/historysecret_test.go diff --git a/internal/cli/historysecret.go b/internal/cli/historysecret.go new file mode 100644 index 0000000..fcbc04c --- /dev/null +++ b/internal/cli/historysecret.go @@ -0,0 +1,100 @@ +// This file is not generated by Speakeasy. It keeps a secret's value out of +// the home prompt's history. +// +// `secret create --name KEY --default-value hunter2` typed in the home prompt +// came back whole on ↑, the value in clear on screen and in the terminal's +// scrollback, though the form that asks for the same value hides it. Lines +// about secrets were already kept off disk (history.go); now the line kept +// for ↑ also loses each flag that holds a secret, and its value, and on +// such a command the whole-body --body. Run again, +// it asks for the value in that hidden form instead of sending a stand-in. + +package cli + +import ( + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/interactive" + "github.com/voiceflow/cli/internal/prompt" +) + +// forHistory is line as the prompt's history keeps it: without the flags +// that hold a secret, as interactive.IsSecretFlag knows them, and their +// values. A line that names no command, or holds no secret, is kept as typed. +func forHistory(root *cobra.Command, line string) string { + args, err := prompt.SplitArgs(line) + if err != nil || len(args) == 0 { + return line + } + words := args + if words[0] == "vf" { + words = words[1:] + } + cmd, _, err := root.Find(words) + if err != nil || cmd == nil { + return line + } + // On a command with a secret flag of its own, the whole body may carry + // the secret too: `secret set-value --body '{"value":"hunter2"}'`. Its + // own: every command inherits vf's --token. + holdsSecret := false + cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + holdsSecret = holdsSecret || interactive.IsSecretFlag(f.Name, f.Usage) + }) + kept := make([]string, 0, len(args)) + dropped := false + for i := 0; i < len(args); i++ { + a := args[i] + f, hasValue := lookupFlag(cmd, a) + if f == nil || !(interactive.IsSecretFlag(f.Name, f.Usage) || (holdsSecret && f.Name == "body")) { + kept = append(kept, a) + continue + } + dropped = true + if !hasValue && f.NoOptDefVal == "" && i+1 < len(args) { + i++ // the value, given as the next word + } + } + if !dropped { + return line + } + for i, a := range kept { + kept[i] = quoteArg(a) + } + return strings.Join(kept, " ") +} + +// lookupFlag is the flag a word such as --value, --value=x or -v names on +// cmd, and whether the word carries its value. +func lookupFlag(cmd *cobra.Command, word string) (*pflag.Flag, bool) { + if len(word) < 2 || word[0] != '-' || word == "--" { + return nil, false + } + name, _, hasValue := strings.Cut(strings.TrimLeft(word, "-"), "=") + if strings.HasPrefix(word, "--") { + if f := cmd.Flags().Lookup(name); f != nil { + return f, hasValue + } + return cmd.InheritedFlags().Lookup(name), hasValue + } + if len(name) != 1 { + return nil, false + } + return cmd.Flags().ShorthandLookup(name), hasValue +} + +// quoteArg writes a as one word the prompt's SplitArgs reads back as a. +func quoteArg(a string) string { + switch { + case a == "": + return "''" + case !strings.ContainsAny(a, " \t'\"\\"): + return a + case !strings.Contains(a, "'"): + return "'" + a + "'" + } + return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(a) + `"` +} diff --git a/internal/cli/historysecret_test.go b/internal/cli/historysecret_test.go new file mode 100644 index 0000000..6935864 --- /dev/null +++ b/internal/cli/historysecret_test.go @@ -0,0 +1,53 @@ +// This file is not generated by Speakeasy. It covers historysecret.go. + +package cli + +import ( + "reflect" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/prompt" +) + +// ↑ in the home prompt never brings back a secret's value. +func TestHistoryKeepsNoSecretValue(t *testing.T) { + root := testRoot(t) + for _, c := range []struct{ line, want string }{ + {"secret create --name KEY -p p1 --default-value hunter2-sweep", "secret create --name KEY -p p1"}, + {"secret set-value -p p1 -s s1 --value=hunter2 -e main --version-variant draft", "secret set-value -p p1 -s s1 -e main --version-variant draft"}, + {"vf secret set-value --value 'two words hunter2' -p p1 -s s1", "vf secret set-value -p p1 -s s1"}, + {`secret set-value -p p1 -s s1 --body '{"value":"hunter2"}'`, "secret set-value -p p1 -s s1"}, + {"secret create --name 'my key' --default-value hunter2", "secret create --name 'my key'"}, + {"project list --token vfp_hunter2", "project list"}, + } { + got := forHistory(root, c.line) + if got != c.want || strings.Contains(got, "hunter2") { + t.Errorf("%s\n kept %q\n want %q", c.line, got, c.want) + } + } + for _, line := range []string{ + "variable create -n x --default-value keep-me", + `variable update -p p1 --body '{"defaultValue":"keep-me"}'`, + "project list", + "not a command --value x", + `unclosed "quote`, + } { + if got := forHistory(root, line); got != line { + t.Errorf("%s: kept %q", line, got) + } + } +} + +// What forHistory quotes, the prompt reads back word for word. +func TestQuoteArgRoundTrips(t *testing.T) { + words := []string{"plain", "", "two words", "it's", `say "hi"`, `back\slash`, "tab\there"} + quoted := make([]string, len(words)) + for i, w := range words { + quoted[i] = quoteArg(w) + } + got, err := prompt.SplitArgs(strings.Join(quoted, " ")) + if err != nil || !reflect.DeepEqual(got, words) { + t.Errorf("%q came back as %q (%v)", words, got, err) + } +} diff --git a/internal/cli/home.go b/internal/cli/home.go index 561f87c..1f99f74 100644 --- a/internal/cli/home.go +++ b/internal/cli/home.go @@ -91,8 +91,9 @@ func runPrompt(cmd *cobra.Command, u *ui.UI, out io.Writer, state signIn) error if line == "" { continue } - if len(history) == 0 || history[len(history)-1] != line { - history = append(history, line) + kept := forHistory(cmd.Root(), line) // historysecret.go: no secret's value on ↑ + if len(history) == 0 || history[len(history)-1] != kept { + history = append(history, kept) } args, err := prompt.SplitArgs(line) @@ -120,7 +121,7 @@ func runPrompt(cmd *cobra.Command, u *ui.UI, out io.Writer, state signIn) error } continue } - saveHistory(histFile, line) + saveHistory(histFile, kept) if args[0] == "use" { use(cmd, u, args[1:]) continue diff --git a/internal/interactive/secretinput.go b/internal/interactive/secretinput.go index 728e5e7..f45df70 100644 --- a/internal/interactive/secretinput.go +++ b/internal/interactive/secretinput.go @@ -43,3 +43,10 @@ func isSecretFlag(m flagutil.FlagMeta) bool { } return false } + +// IsSecretFlag is whether the flag named name, described as description, +// holds a secret, for whatever else must keep its value out of sight: the +// home prompt's history (cli/historysecret.go). +func IsSecretFlag(name, description string) bool { + return isSecretFlag(flagutil.FlagMeta{FlagName: name, Description: description}) +} From ce355483d6ead8de4d667511fe03e233677a7ec2 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:08:18 -0500 Subject: [PATCH 29/30] fix(output): redact credentials in --include-headers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --debug prints `Set-Cookie: [REDACTED]`, but --include-headers printed the header as the server sent it, session cookie and all, into CI logs that are often public. --include-headers now redacts the headers --debug redacts (Set-Cookie, Cookie, Authorization, X-Session-Token, *-token, *-secret …), in JSON, YAML and pretty output alike. A test keeps the two lists the same. --- internal/client/headerredact_test.go | 22 +++++++++++ internal/output/headerredact.go | 56 ++++++++++++++++++++++++++++ internal/output/headerredact_test.go | 39 +++++++++++++++++++ internal/output/output.go | 2 + 4 files changed, 119 insertions(+) create mode 100644 internal/client/headerredact_test.go create mode 100644 internal/output/headerredact.go create mode 100644 internal/output/headerredact_test.go diff --git a/internal/client/headerredact_test.go b/internal/client/headerredact_test.go new file mode 100644 index 0000000..08503ea --- /dev/null +++ b/internal/client/headerredact_test.go @@ -0,0 +1,22 @@ +// This file is not generated by Speakeasy. It keeps output/headerredact.go, +// which --include-headers uses, redacting what --debug redacts. + +package client + +import ( + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +func TestIncludeHeadersRedactsWhatDebugRedacts(t *testing.T) { + keys := append(append([]string{}, sensitiveHeaderKeys...), "X-Refresh-Token", "Client-Secret", "Content-Type", "Retry-After", "Set-Cookie") + for _, s := range sensitiveHeaderSuffixes { + keys = append(keys, "X-Any"+s) + } + for _, k := range keys { + if isSensitiveHeader(k) != output.IsSensitiveHeader(k) { + t.Errorf("%s: --debug redacts it: %v, --include-headers: %v", k, isSensitiveHeader(k), output.IsSensitiveHeader(k)) + } + } +} diff --git a/internal/output/headerredact.go b/internal/output/headerredact.go new file mode 100644 index 0000000..0eab893 --- /dev/null +++ b/internal/output/headerredact.go @@ -0,0 +1,56 @@ +// This file is not generated by Speakeasy. It keeps credentials out of +// --include-headers. +// +// --debug prints `Set-Cookie: [REDACTED]` (client/diagnostics.go), but +// --include-headers printed the header as the server sent it, +// +// "Set-Cookie": "ingress-ws=1796013803.728.22.969687|c78de4de…; Path=/; Secure; HttpOnly" +// +// into CI logs that are often public. Both now redact the same headers. The +// list is diagnostics.go's, which output can't import (client imports +// output); a client test keeps the two the same. + +package output + +import ( + "net/http" + "strings" +) + +var ( + sensitiveHeaders = []string{"authorization", "proxy-authorization", "x-api-key", "api-key", "x-session-token", "cookie", "set-cookie"} + sensitiveHeaderSuffixes = []string{"-secret", "-token"} +) + +// IsSensitiveHeader is whether the header named key carries a credential. +func IsSensitiveHeader(key string) bool { + lower := strings.ToLower(key) + for _, s := range sensitiveHeaders { + if lower == s { + return true + } + } + for _, suffix := range sensitiveHeaderSuffixes { + if strings.HasSuffix(lower, suffix) { + return true + } + } + return false +} + +// redactResponseHeaders is h with each credential's value replaced by +// [REDACTED]; h itself is left as it is. +func redactResponseHeaders(h http.Header) http.Header { + if len(h) == 0 { + return h + } + out := make(http.Header, len(h)) + for k, vals := range h { + if IsSensitiveHeader(k) { + out[k] = []string{"[REDACTED]"} + } else { + out[k] = vals + } + } + return out +} diff --git a/internal/output/headerredact_test.go b/internal/output/headerredact_test.go new file mode 100644 index 0000000..6ed2f68 --- /dev/null +++ b/internal/output/headerredact_test.go @@ -0,0 +1,39 @@ +// This file is not generated by Speakeasy. It covers headerredact.go. + +package output + +import ( + "bytes" + "encoding/json" + "net/http" + "strings" + "testing" +) + +func cookieHeaders() http.Header { + return http.Header{ + "Set-Cookie": {"ingress-ws=1796013803.728|c78de4de; Path=/; Secure; HttpOnly", "other=2"}, + "X-Session-Token": {"tok_live"}, + "Content-Type": {"application/json"}, + } +} + +// --include-headers never prints a cookie or a token, in JSON or pretty +// output, and leaves the response's own headers as they were. +func TestIncludeHeadersRedactsCredentials(t *testing.T) { + h := cookieHeaders() + flat, _ := json.Marshal(injectHeaders(map[string]interface{}{"id": "p1"}, h)) + var pretty bytes.Buffer + printResponseHeadersPretty(&pretty, h, false) + for name, out := range map[string]string{"json": string(flat), "pretty": pretty.String()} { + if strings.Contains(out, "ingress-ws") || strings.Contains(out, "tok_live") || !strings.Contains(out, "[REDACTED]") { + t.Errorf("%s:\n%s", name, out) + } + if !strings.Contains(out, "application/json") { + t.Errorf("%s lost Content-Type:\n%s", name, out) + } + } + if h.Get("Set-Cookie") == "[REDACTED]" { + t.Error("redacted the response's own headers") + } +} diff --git a/internal/output/output.go b/internal/output/output.go index eaf505e..9db7ae5 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -668,6 +668,7 @@ func extractErrorResponseHeaders(err error) http.Header { // remain as arrays. Key order is not guaranteed; callers relying on deterministic output // should sort separately (json.Marshal sorts map keys; printResponseHeadersPretty sorts explicitly). func flattenHeaders(headers http.Header) map[string]interface{} { + headers = redactResponseHeaders(headers) // headerredact.go: no credentials, as --debug if len(headers) == 0 { return nil } @@ -753,6 +754,7 @@ func outputWithHeaders(out io.Writer, content interface{}, headers http.Header, // printResponseHeadersPretty prints HTTP response headers in aligned key-value // format, similar to prettyPrint but as a separate section. func printResponseHeadersPretty(w io.Writer, headers http.Header, colorize bool) { + headers = redactResponseHeaders(headers) // headerredact.go: no credentials, as --debug if len(headers) == 0 { return } From 1e960474df9f1e3450f612d9357542b9e0538cc6 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:11:30 -0500 Subject: [PATCH 30/30] style(output): format two returns the same under every gofmt CI's gofmt (Go 1.25, from go.mod) indents a return of multi-line slice literals one level deeper than Go 1.27's does, so two explanations passed locally and failed CI's formatting check. Each now builds its slices first and returns the names, which both versions format alike. --- internal/output/doctype.go | 8 +++----- internal/output/framework.go | 16 ++++++++-------- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/internal/output/doctype.go b/internal/output/doctype.go index e478a6a..1e0f113 100644 --- a/internal/output/doctype.go +++ b/internal/output/doctype.go @@ -28,9 +28,7 @@ func explainDocumentType(cmd *cobra.Command, status int, message string) (why, n if f := cmd.Flags().Lookup("file"); f != nil && f.Value.String() != "" { file = filepath.Base(f.Value.String()) } - return []string{ - file + " isn't a type the knowledge base takes. vf names a file's type from its extension, and the knowledge base takes " + documentTypes + " files.", - }, []string{ - "Save it as " + documentTypes + ", converting it if need be, then run it again", - }, true + why = []string{file + " isn't a type the knowledge base takes. vf names a file's type from its extension, and the knowledge base takes " + documentTypes + " files."} + next = []string{"Save it as " + documentTypes + ", converting it if need be, then run it again"} + return why, next, true } diff --git a/internal/output/framework.go b/internal/output/framework.go index e45d2e5..d95f803 100644 --- a/internal/output/framework.go +++ b/internal/output/framework.go @@ -36,19 +36,19 @@ func explainProjectKind(cmd *cobra.Command, status int, message string) (why, ne project := projectNamed(cmd) switch { case status == 404 && strings.Contains(message, "does not have any environments"): - return []string{ - capitalize(project) + " is an older Voiceflow project (v3): it still uses the fixed development, staging and production versions, and hasn't moved to environments, which vf's commands work with.", - }, []string{ + why = []string{capitalize(project) + " is an older Voiceflow project (v3): it still uses the fixed development, staging and production versions, and hasn't moved to environments, which vf's commands work with."} + next = []string{ anotherProject(cmd), "Or move it to environments in Voiceflow: Settings → General → Danger zone → Migrate to environments. Update anything that uses the old aliases first", - }, migrateDocsURL, true + } + return why, next, migrateDocsURL, true case status == 400 && strings.Contains(message, "is not an agent project"): - return []string{ - capitalize(project) + " isn't an Agent Framework project: it uses Conversation Flow, and this works only in Agent Framework projects.", - }, []string{ + why = []string{capitalize(project) + " isn't an Agent Framework project: it uses Conversation Flow, and this works only in Agent Framework projects."} + next = []string{ anotherProject(cmd), "Or switch it to the Agentic framework in Voiceflow: Settings → General. The switch can't be undone", - }, frameworkDocsURL, true + } + return why, next, frameworkDocsURL, true } return nil, nil, "", false }