diff --git a/README.md b/README.md index 690a16b..92a3ecb 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,7 @@ Worth knowing before you script against the CLI: - **`--version-param draft` runs what you are editing; `published` runs the live version.** A new project is created with a first release already in place, so either works immediately — you do not have to publish anything first. - **`--action '{"type":"launch"}'` is optional.** Sending a `text` action straight away works; the runtime starts the conversation itself. The launch step is shown because it makes the first turn explicit. +- **A conversation with the draft runs your latest edits.** The draft runs as last compiled, so vf compiles it before `conversation run-script` and before a `send` with a `launch` action. If a later turn still ran an older build (you edited mid-conversation, or started with a `text` action), vf compiles right after it and warns, so the next turn runs the edits. `--no-compile` talks to the last build as it is; the published version is never compiled. - **Pass `--output-format json` explicitly when piping.** Inside AI coding agents (`CLAUDECODE`, `CURSOR_AGENT`, …) the default output is TOON, not JSON. - **Capture values with `--output-format json | jq -r`** — the built-in `--jq` flag emits JSON, so strings keep their quotes. - **`vf whoami` is offline** — it shows which credential source is configured but does not validate the token. `vf workspace list` is the real check. diff --git a/internal/cli/autocompile_test.go b/internal/cli/autocompile_test.go new file mode 100644 index 0000000..4cd3c6e --- /dev/null +++ b/internal/cli/autocompile_test.go @@ -0,0 +1,126 @@ +// This file is not generated by Speakeasy. It covers +// conversation/autocompile.go: a conversation with the draft runs the latest +// edits. + +package cli + +import ( + "bytes" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// conversationServer answers compile with compileStatus, and a conversation +// with answer. It records each request as "compile" or "conversation". +func conversationServer(t *testing.T, compileStatus int, answer string) (url string, requests func() []string) { + t.Helper() + var mu sync.Mutex + var seen []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + mu.Lock() + defer mu.Unlock() + w.Header().Set("Content-Type", "application/json") + if strings.HasSuffix(r.URL.Path, "/compile") { + seen = append(seen, "compile") + w.WriteHeader(compileStatus) + io.WriteString(w, `{"message":"Environment compiled","durationMs":5}`) + return + } + seen = append(seen, "conversation") + io.WriteString(w, answer) + })) + t.Cleanup(srv.Close) + return srv.URL, func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), seen...) + } +} + +func runConversation(t *testing.T, url string, args ...string) (string, error) { + t.Helper() + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", url) + t.Setenv("HOME", t.TempDir()) + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + root.SetOut(&buf) + root.SetErr(&buf) + root.SetIn(strings.NewReader("")) + root.SetArgs(append(append([]string{"conversation"}, args...), "--agent-mode=false", "--no-interactive")) + _, err = root.ExecuteC() + return buf.String(), err +} + +const ( + freshTurn = `{"traces":[],"needsRecompile":false}` + staleTurn = `{"traces":[],"needsRecompile":true}` + script = `{"userID":"u1","transcriptID":null,"needsRecompile":false,"turns":[],"notSent":[]}` +) + +func TestAConversationWithTheDraftCompilesItFirst(t *testing.T) { + scope := []string{"-p", "p1", "-e", "main"} + send := append([]string{"send", "-u", "u1", "-v", "draft"}, scope...) + cases := []struct { + name string + answer string + args []string + want string + }{ + {"run-script compiles first", script, append([]string{"run-script", "-m", `["hi"]`}, scope...), "compile conversation"}, + {"run-script --no-compile", script, append([]string{"run-script", "-m", `["hi"]`, "--no-compile"}, scope...), "conversation"}, + {"run-script on published", script, append([]string{"run-script", "-m", `["hi"]`, "--version-param", "published"}, scope...), "conversation"}, + {"a launch compiles first", freshTurn, append(send, "-a", `{"type":"launch"}`), "compile conversation"}, + {"a later turn doesn't", freshTurn, append(send, "-a", `{"type":"text","payload":"hi"}`), "conversation"}, + {"a stale turn compiles after", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`), "conversation compile"}, + {"a stale turn compiles after, -o json", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`, "-o", "json"), "conversation compile"}, + {"a stale turn with --no-compile", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`, "--no-compile"), "conversation"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + url, requests := conversationServer(t, 200, c.answer) + out, err := runConversation(t, url, c.args...) + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + if got := strings.Join(requests(), " "); got != c.want { + t.Errorf("requests = %q, want %q", got, c.want) + } + compiled := strings.Contains(c.want, "compile") + if says := strings.Contains(out, "Compiled the draft") || strings.Contains(out, "vf has compiled it"); says != compiled { + t.Errorf("compiled %v, but saying so is %v:\n%s", compiled, says, out) + } + if strings.Contains(c.name, "-o json") && !strings.Contains(out, `"needsRecompile":true`) { + t.Errorf("the answer wasn't printed as it came:\n%s", out) + } + }) + } +} + +// A draft that won't compile stops the script before it spends credits, and +// says how to run the last build anyway. +func TestADraftThatWontCompileStopsTheScript(t *testing.T) { + url, requests := conversationServer(t, 500, script) + out, err := runConversation(t, url, "run-script", "-m", `["hi"]`, "-p", "p1", "-e", "main") + if err == nil { + t.Fatal("no error") + } + if !strings.Contains(out, "Couldn't compile the draft") || !strings.Contains(out, "--no-compile") { + t.Errorf("the error doesn't say the compile failed, or how to skip it:\n%s", out) + } + if got := strings.Join(requests(), " "); got != "compile" { + t.Errorf("requests = %q, want only the compile", got) + } +} diff --git a/internal/cli/conversation/autocompile.go b/internal/cli/conversation/autocompile.go new file mode 100644 index 0000000..b2951c4 --- /dev/null +++ b/internal/cli/conversation/autocompile.go @@ -0,0 +1,153 @@ +// This file is not generated by Speakeasy. It has a conversation with the +// draft run the latest edits, by compiling the draft first. +// +// A conversation runs the environment's last compiled build, and nothing +// compiled it after an edit. So `agent update` then `conversation run-script` +// talked to the old agent: the usability sweep's agents and newcomers alike +// read the old replies as "my prompt and tool don't work", and spent credits +// on it. The only sign was `needsRecompile: true` atop hundreds of lines. +// +// Nothing says the draft is stale before a run, so vf compiles it whenever a +// conversation with the draft starts: before every run-script, and before a +// send that launches. A send later in a conversation keeps its build, but if +// its turn still ran a stale one, vf compiles right after and says so, so the +// next turn runs the edits. --no-compile runs whatever was last compiled. +// The published version is a release, and is never compiled. + +package conversation + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk" + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/ui" +) + +const noCompileFlag = "no-compile" + +// addNoCompileFlag lets cmd run the draft as last compiled. +func addNoCompileFlag(cmd *cobra.Command) { + cmd.Flags().Bool(noCompileFlag, false, "Run the draft as last compiled. Without it, vf compiles the draft first when a conversation starts, so it runs your latest edits.") +} + +// compileBeforeScript compiles the draft before run-script, which always +// starts a new conversation. +func compileBeforeScript(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableConversationControllerRunScriptRequest) error { + if req.Body.Version != nil && string(*req.Body.Version) != "draft" { + return nil + } + return compileDraft(cmd, s, req.ProjectID, req.EnvironmentAlias) +} + +// compileBeforeSend compiles the draft before a send that launches a +// conversation. +func compileBeforeSend(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableConversationControllerSendRequest) error { + if string(req.Body.Version) != "draft" || actionType(req.Body.Action) != "launch" { + return nil + } + return compileDraft(cmd, s, req.ProjectID, req.EnvironmentAlias) +} + +// compileAfterStaleSend reads a send's answer before it is printed. When the +// turn ran a stale build of the draft, the function it returns compiles the +// draft once the answer is printed, and says so. +func compileAfterStaleSend(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableConversationControllerSendRequest, res *operations.StableConversationControllerSendResponse) func() error { + none := func() error { return nil } + if res == nil || client.IsDryRun(cmd) || string(req.Body.Version) != "draft" || skipCompile(cmd) { + return none + } + answer := res.StableConversationSendResponse + if answer == nil { + answer = &components.StableConversationSendResponse{} + if !output.PeekJSON(res.HTTPMeta.Response, answer) { + return none + } + } + if !answer.NeedsRecompile { + return none + } + return func() error { + if err := compile(cmd, s, req.ProjectID, req.EnvironmentAlias); err != nil { + return err + } + warn(cmd, "This turn ran an older build of the draft. vf has compiled it, so the next turn runs your latest edits.") + return nil + } +} + +// compileDraft compiles the draft of alias in projectID, and says it did. +func compileDraft(cmd *cobra.Command, s *sdk.VoiceflowSDK, projectID, alias string) error { + if skipCompile(cmd) { + return nil + } + start := time.Now() + if err := compile(cmd, s, projectID, alias); err != nil { + return err + } + if !client.IsDryRun(cmd) && !output.IsAgentMode() { + w := cmd.ErrOrStderr() + fmt.Fprintln(w, output.UI(cmd, w).Status(ui.StatusDone, fmt.Sprintf("Compiled the draft of %s (%.1fs), so this runs your latest edits", alias, time.Since(start).Seconds()))) + } + return nil +} + +func compile(cmd *cobra.Command, s *sdk.VoiceflowSDK, projectID, alias string) error { + ctx := client.WithSpinnerMessage(cmd.Context(), "Compiling the draft…") + _, err := s.Environment.Compile(ctx, operations.StableEnvironmentControllerCompileRequest{ProjectID: projectID, EnvironmentAlias: alias}, operations.WithSkipDeserialization()) + if err != nil { + return compileFailed(cmd, err) + } + return nil +} + +// compileFailed explains a compile that failed: the conversation didn't +// start, and --no-compile runs the last build instead. +func compileFailed(cmd *cobra.Command, err error) error { + x := output.ExplainError(cmd, err) + title := "Couldn't compile the draft, so the conversation didn't run" + if _, status, ok := strings.Cut(x.Title, " · "); ok { + title += " · " + status + } + x.Title = title + if status := output.StatusCode(err); status >= 400 && status < 500 && status != 401 && status != 403 && status != 404 { + // The agent, not the command's flags, is what didn't compile. + x.Why = []string{"Something in the agent's draft keeps it from compiling."} + x.Next = []string{"Fix what the message names in the agent, then run it again"} + } + x.Next = append(x.Next, "Add `--no-compile` to talk to the last build instead") + return output.Report(cmd, x, err) +} + +func skipCompile(cmd *cobra.Command) bool { + skip, _ := cmd.Flags().GetBool(noCompileFlag) + return skip +} + +// actionType is a send's action type: "launch", "text", "end"... +func actionType(action components.AnyRequest) string { + raw, err := json.Marshal(action) + if err != nil { + return "" + } + var a struct { + Type string `json:"type"` + } + _ = json.Unmarshal(raw, &a) + return a.Type +} + +// warn says msg on stderr, in every mode: a stale turn matters to an agent +// as much as to a person. +func warn(cmd *cobra.Command, msg string) { + w := cmd.ErrOrStderr() + fmt.Fprintln(w, output.UI(cmd, w).Status(ui.StatusWarn, msg)) +} diff --git a/internal/cli/conversation/runscript.go b/internal/cli/conversation/runscript.go index 743e821..cf5dcfb 100644 --- a/internal/cli/conversation/runscript.go +++ b/internal/cli/conversation/runscript.go @@ -36,6 +36,7 @@ func initRunScriptCmd(parent *cobra.Command) error { Aliases: []string{"rs"}, } flagutil.RegisterFlags(cmd, runScriptCmdMeta) + addNoCompileFlag(cmd) // autocompile.go: --no-compile if err := flagutil.ValidateMeta[operations.StableConversationControllerRunScriptRequest](runScriptCmdMeta); err != nil { return fmt.Errorf("invalid metadata for run-script: %w", err) } @@ -77,6 +78,9 @@ func runRunScriptCmd(cmd *cobra.Command, args []string) error { if output.WantsRawJSON(cmd) { sdkOpts = append(sdkOpts, operations.WithSkipDeserialization()) } + if err := compileBeforeScript(cmd, s, req); err != nil { // autocompile.go: the script runs the latest edits + return err + } res, err := s.Conversation.RunScript(cmd.Context(), *req, sdkOpts...) if err != nil { return output.Error(cmd, err) diff --git a/internal/cli/conversation/send.go b/internal/cli/conversation/send.go index c544497..8b79044 100644 --- a/internal/cli/conversation/send.go +++ b/internal/cli/conversation/send.go @@ -35,6 +35,7 @@ func initSendCmd(parent *cobra.Command) error { RunE: runSendCmd, } flagutil.RegisterFlags(cmd, sendCmdMeta) + addNoCompileFlag(cmd) // autocompile.go: --no-compile if err := flagutil.ValidateMeta[operations.StableConversationControllerSendRequest](sendCmdMeta); err != nil { return fmt.Errorf("invalid metadata for send: %w", err) } @@ -76,13 +77,17 @@ func runSendCmd(cmd *cobra.Command, args []string) error { if output.WantsRawJSON(cmd) { sdkOpts = append(sdkOpts, operations.WithSkipDeserialization()) } + if err := compileBeforeSend(cmd, s, req); err != nil { // autocompile.go: a new conversation runs the latest edits + return err + } res, err := s.Conversation.Send(cmd.Context(), *req, sdkOpts...) if err != nil { return output.Error(cmd, err) } + compiled := compileAfterStaleSend(cmd, s, req, res) // autocompile.go: a stale turn compiles the draft for the next if err := output.Result(cmd, res); err != nil { return err } - return nil + return compiled() } diff --git a/internal/cli/errors.go b/internal/cli/errors.go index 4a0f027..c5e19a2 100644 --- a/internal/cli/errors.go +++ b/internal/cli/errors.go @@ -219,7 +219,11 @@ func explainCLIError(cmd *cobra.Command, err error) output.Explanation { name = "-" + m[1] } x.Title = cmd.CommandPath() + " has no flag " + name - for _, s := range similarFlags(cmd, strings.TrimLeft(name, "-")) { + near := similarFlags(cmd, strings.TrimLeft(name, "-")) + if m[1] != "" { + near = shorthandElsewhere(cmd, m[1]) + } + for _, s := range near { x.Next = append(x.Next, "Did you mean `--"+s+"`?") } x.Next = append(x.Next, help+" lists its flags") @@ -404,7 +408,9 @@ func similarFlags(cmd *cobra.Command, name string) []string { } seen[f.Name] = true d := levenshtein(name, f.Name) - if d <= 2 || (len(name) >= 3 && strings.HasPrefix(f.Name, name)) { + // A typo changes at most half of a name: two edits turn any short + // name, like "pi", into "jq". + if (d <= 2 && 2*d <= len(name)) || (len(name) >= 3 && strings.HasPrefix(f.Name, name)) { found = append(found, scored{f.Name, d}) } } @@ -418,6 +424,43 @@ func similarFlags(cmd *cobra.Command, name string) []string { return out } +// shorthandElsewhere is what - stands for on vf's other commands, +// among the flags cmd has: `agent update -p` → project-id. Edit distance +// can't judge a one-letter name, since every short flag is within two edits +// of "jq". Nothing is suggested when cmd has no such flag. +func shorthandElsewhere(cmd *cobra.Command, letter string) []string { + counts := map[string]int{} + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + c.Flags().VisitAll(func(f *pflag.Flag) { + if f.Shorthand == letter && !f.Hidden { + counts[f.Name]++ + } + }) + for _, sub := range c.Commands() { + walk(sub) + } + } + walk(cmd.Root()) + var names []string + for n := range counts { + f := cmd.Flags().Lookup(n) + if f == nil { + f = cmd.InheritedFlags().Lookup(n) + } + if f != nil && !f.Hidden { + names = append(names, n) + } + } + sort.Slice(names, func(i, j int) bool { + if counts[names[i]] != counts[names[j]] { + return counts[names[i]] > counts[names[j]] + } + return names[i] < names[j] + }) + return names[:min(len(names), 2)] +} + func levenshtein(a, b string) int { prev := make([]int, len(b)+1) for j := range prev { diff --git a/internal/cli/errors_test.go b/internal/cli/errors_test.go index 3a0185a..90b584b 100644 --- a/internal/cli/errors_test.go +++ b/internal/cli/errors_test.go @@ -74,6 +74,9 @@ func TestUnknownCommandsAndFlagsSuggestTheNearest(t *testing.T) { 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)) } + if strings.Contains(explained(x), "Did you mean") { + t.Errorf("-z stands for nothing, so nothing is near it:\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) @@ -222,6 +225,23 @@ func TestCheckAccessFindsTheTargetAmongYourWorkspaces(t *testing.T) { } } +// Every unknown short flag used to get "Did you mean `--jq`?": a one-letter +// name is within two edits of any short flag name. +func TestAnUnknownShortFlagSuggestsWhatItMeansElsewhere(t *testing.T) { + root := testRoot(t) + update := find(t, root, "agent", "update") + if update.Flags().ShorthandLookup("p") != nil || update.Flags().Lookup("project-id") == nil { + t.Fatal("the test needs a command with --project-id and no -p") + } + x := explainCLIError(update, errors.New("unknown shorthand flag: 'p' in -p")) + if got := explained(x); !strings.Contains(got, "Did you mean `--project-id`?") || strings.Contains(got, "--jq") { + t.Errorf("-p on vf agent update:\n%s", got) + } + if got := similarFlags(update, "pi"); len(got) != 0 { + t.Errorf("--pi is near nothing, got %q", got) + } +} + func TestSimilarFlags(t *testing.T) { root := testRoot(t) create := find(t, root, "workspace", "create") diff --git a/internal/cli/examplehelp.go b/internal/cli/examplehelp.go new file mode 100644 index 0000000..388b867 --- /dev/null +++ b/internal/cli/examplehelp.go @@ -0,0 +1,220 @@ +// This file is not generated by Speakeasy. It makes every generated help +// example run as written. +// +// The generator builds an example from the SDK's resource name, not from the +// command's place in the tree. So the 78 commands three levels down showed +// `vf query project-transcript-count`, `vf run wait`, `vf function-variable +// create`: commands that don't exist. Some examples also left out a required +// flag, and one ran a multi-word value into the next words unquoted. Agents +// copy examples word for word, so each of these failed on first use. +// +// fixExamples rewrites them once, at startup, from what the command really +// is: its own path, every required flag, and quoted values. Fixing it here +// rather than in ~80 generated files covers the next command the spec adds. + +package cli + +import ( + "slices" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/flagutil" +) + +// fixExamples gives every command under root an example that runs as written. +func fixExamples(root *cobra.Command) { + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + if c.Example != "" && c != root { + c.Example = fixExample(c, c.Example) + } + for _, sub := range c.Commands() { + walk(sub) + } + } + walk(root) +} + +// fixExample rewrites each line of example that runs vf: the command words +// become c's full path, a multi-word value is quoted, and the first such line +// gains any required flag it left out. Lines that run another command, or +// name no command c answers to, are left alone. +func fixExample(c *cobra.Command, example string) string { + lines := strings.Split(example, "\n") + first := true + for i, line := range lines { + body := strings.TrimLeft(line, " \t") + indent := line[:len(line)-len(body)] + body = strings.TrimRight(body, " \t") + fields := strings.Split(body, " ") + if len(fields) < 2 || fields[0] != "vf" { + continue + } + end := 1 + for end < len(fields) && isCommandWord(fields[end]) { + end++ + } + name := -1 + for k := end - 1; k >= 1; k-- { + if fields[k] == c.Name() || slices.Contains(c.Aliases, fields[k]) { + name = k + break + } + } + if name < 0 { + continue + } + rest := quoteValues(c, fields[name+1:]) + if first { + rest = append(rest, missingRequired(c, rest)...) + first = false + } + lines[i] = indent + strings.Join(append([]string{c.CommandPath()}, rest...), " ") + } + return strings.Join(lines, "\n") +} + +// isCommandWord reports whether word could name a command: lower case, +// digits and dashes. A flag, a placeholder, a path or a quoted value can't. +func isCommandWord(word string) bool { + if word == "" || word[0] < 'a' || word[0] > 'z' { + return false + } + for _, r := range word { + if (r < 'a' || r > 'z') && (r < '0' || r > '9') && r != '-' { + return false + } + } + return true +} + +// quoteValues single-quotes a flag value the example spread over several +// words, so the shell passes it as one: `--description provided quietly +// carpool` becomes `--description 'provided quietly carpool'`. A flag left +// with no value gets a placeholder. +func quoteValues(c *cobra.Command, words []string) []string { + out := make([]string, 0, len(words)) + for i := 0; i < len(words); i++ { + out = append(out, words[i]) + if !strings.HasPrefix(words[i], "--") || strings.Contains(words[i], "=") { + continue + } + f := c.Flags().Lookup(strings.TrimPrefix(words[i], "--")) + if f == nil || f.Value.Type() == "bool" { + continue + } + j := i + 1 + for j < len(words) && !strings.HasPrefix(words[j], "-") { + j++ + } + switch { + case j == i+1: + out = append(out, placeholder(f)) + case j-i > 2 && !strings.ContainsAny(words[i+1][:1], `'"`): + out = append(out, shellQuote(strings.Join(words[i+1:j], " "))) + i = j - 1 + } + } + return out +} + +// missingRequired is " --flag " for each required flag of c that +// words don't set, in the order help lists them. A union's variants are each +// marked required but are alternatives: when words set none of the union, +// only the first variant's flags are added. A union that isn't optional, like +// a body that is one as a whole, gets its first form when words set none. +func missingRequired(c *cobra.Command, words []string) []string { + var add []string + variant := "" + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if f.Hidden || !isRequired(f) || setIn(words, f) { + return + } + if dot := strings.LastIndexByte(f.Name, '.'); dot > 0 { + if unionSetIn(words, f.Name[:strings.IndexByte(f.Name, '.')]) { + return + } + if variant == "" { + variant = f.Name[:dot] + } + if f.Name[:dot] != variant { + return + } + } + add = append(add, "--"+f.Name) + if f.Value.Type() != "bool" { + add = append(add, placeholder(f)) + } + }) + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + form := f.Annotations[flagutil.UnionNeedsAForm] + if f.Hidden || len(form) == 0 || unionSetIn(slices.Concat(words, add), f.Name) { + return + } + add = append(add, aForm(c, form[0])...) + }) + return add +} + +// aForm is the flag and value that give a union the form variant, its first: +// the variant's first field, so the example takes a plain value where it +// can, or else the variant as JSON. +func aForm(c *cobra.Command, variant string) []string { + use := c.Flags().Lookup(variant) + if use == nil { + return nil + } + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if use.Name == variant && !f.Hidden && strings.HasPrefix(f.Name, variant+".") && f.Value.Type() != "bool" { + use = f + } + }) + return []string{"--" + use.Name, placeholder(use)} +} + +// unionSetIn reports whether words set the union flag base, as JSON +// (--base) or through one of its variants (--base.variant.field). +func unionSetIn(words []string, base string) bool { + for _, w := range words { + if w == "--"+base || strings.HasPrefix(w, "--"+base+"=") || strings.HasPrefix(w, "--"+base+".") { + return true + } + } + return false +} + +func isRequired(f *pflag.Flag) bool { + v := f.Annotations["speakeasy:required"] + return len(v) > 0 && v[0] == "true" +} + +func setIn(words []string, f *pflag.Flag) bool { + for _, w := range words { + if w == "--"+f.Name || strings.HasPrefix(w, "--"+f.Name+"=") || (f.Shorthand != "" && w == "-"+f.Shorthand) { + return true + } + } + return false +} + +// placeholder is the value an example shows for f, in the generator's style. +func placeholder(f *pflag.Flag) string { + switch { + case strings.HasPrefix(f.Usage, "Path to file"): + return "" + case strings.HasSuffix(f.Name, "-id"), strings.HasSuffix(f.Name, "-ids"), + f.Value.Type() == "stringArray" && strings.Contains(f.Usage, "IDs"): + return "" + case strings.HasPrefix(f.Value.Type(), "int"), strings.HasPrefix(f.Value.Type(), "float"): + return "1" + } + return "" +} + +// shellQuote quotes s for a POSIX shell. +func shellQuote(s string) string { + return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" +} diff --git a/internal/cli/examplehelp_test.go b/internal/cli/examplehelp_test.go new file mode 100644 index 0000000..0bbb5c6 --- /dev/null +++ b/internal/cli/examplehelp_test.go @@ -0,0 +1,187 @@ +// This file is not generated by Speakeasy. It covers examplehelp.go: every +// example in help names its own command, sets every required flag, and +// parses. + +package cli + +import ( + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/flagutil" +) + +// shellWords splits line as a POSIX shell would, for the quoting examples use. +func shellWords(t *testing.T, line string) []string { + t.Helper() + var words []string + var cur strings.Builder + inWord := false + for i := 0; i < len(line); i++ { + switch ch := line[i]; { + case ch == ' ' || ch == '\t': + if inWord { + words = append(words, cur.String()) + cur.Reset() + inWord = false + } + case ch == '\'': + end := strings.IndexByte(line[i+1:], '\'') + if end < 0 { + t.Fatalf("unclosed ' in %s", line) + } + cur.WriteString(line[i+1 : i+1+end]) + i += end + 1 + inWord = true + case ch == '"': + i++ + for ; i < len(line) && line[i] != '"'; i++ { + if line[i] == '\\' && i+1 < len(line) { + i++ + } + cur.WriteByte(line[i]) + } + if i >= len(line) { + t.Fatalf("unclosed \" in %s", line) + } + inWord = true + case ch == '\\' && i+1 < len(line): + i++ + cur.WriteByte(line[i]) + inWord = true + default: + cur.WriteByte(ch) + inWord = true + } + } + if inWord { + words = append(words, cur.String()) + } + return words +} + +func TestEveryExampleRunsAsWritten(t *testing.T) { + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + checked := 0 + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + if c == root || c.Example == "" { + return + } + for i, line := range strings.Split(c.Example, "\n") { + line = strings.TrimSpace(line) + if !strings.HasPrefix(line, "vf ") || strings.Contains(line, "|") { + continue + } + words := shellWords(t, line) + found, args, err := root.Find(words[1:]) + if err != nil || found != c { + t.Errorf("%s: example %q runs %v", c.CommandPath(), line, found.CommandPath()) + continue + } + if err := found.ParseFlags(args); err != nil { + t.Errorf("%s: example %q: %v", c.CommandPath(), line, err) + continue + } + if i == 0 { + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if !isRequired(f) || f.Hidden || f.Changed { + return + } + // A union's variants are alternatives: one of them, or + // the union's JSON, is enough. + if base, _, ok := strings.Cut(f.Name, "."); ok && unionSetIn(args, base) { + return + } + t.Errorf("%s: example %q leaves out required --%s", c.CommandPath(), line, f.Name) + }) + // A union that isn't optional, like a body that is one as a + // whole, needs one of its forms. + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if len(f.Annotations[flagutil.UnionNeedsAForm]) > 0 && !f.Hidden && !unionSetIn(args, f.Name) { + t.Errorf("%s: example %q gives --%s none of its forms", c.CommandPath(), line, f.Name) + } + }) + } + checked++ + } + } + walk(root) + if checked < 250 { + t.Errorf("checked only %d examples", checked) + } +} + +func TestFixExample(t *testing.T) { + root := &cobra.Command{Use: "vf"} + function := &cobra.Command{Use: "function"} + variable := &cobra.Command{Use: "variable"} + create := &cobra.Command{Use: "create", Aliases: []string{"c"}} + root.AddCommand(function) + function.AddCommand(variable) + variable.AddCommand(create) + create.Flags().StringP("project-id", "p", "", "") + create.Flags().String("function-id", "", "") + create.Flags().String("description", "", "") + create.Flags().String("file", "", "Path to file to upload [required]") + create.Flags().Bool("can-edit", false, "") + for _, name := range []string{"project-id", "function-id", "file"} { + _ = create.Flags().SetAnnotation(name, "speakeasy:required", []string{"true"}) + } + + cases := map[string]string{ + " vf function-variable create --project-id --description a quiet carpool --can-edit --function-id ": " vf function variable create --project-id --description 'a quiet carpool' --can-edit --function-id --file ", + " vf variable c -p --file x.txt --function-id=": " vf function variable create -p --file x.txt --function-id=", + " vf other thing --project-id ": " vf other thing --project-id ", + } + for in, want := range cases { + if got := fixExample(create, in); got != want { + t.Errorf("fixExample(%q)\n got %q\nwant %q", in, got, want) + } + } +} + +// A body that is a union as a whole isn't marked required, but sent empty it +// is "none of its forms". The example gives it its first form: a field of the +// variant where there is one, or else the variant as JSON. +func TestFixExampleGivesAWholeBodyUnionAForm(t *testing.T) { + root := &cobra.Command{Use: "vf"} + branch := &cobra.Command{Use: "update-branch"} + check := &cobra.Command{Use: "create"} + root.AddCommand(branch, check) + for _, c := range []*cobra.Command{branch, check} { + c.Flags().String("project-id", "", "") + _ = c.Flags().SetAnnotation("project-id", "speakeasy:required", []string{"true"}) + c.Flags().String("body-param", "", "") + } + for _, name := range []string{"buttons", "buttons.label", "buttons.url", "card"} { + branch.Flags().String("body-param."+name, "", "") + } + _ = branch.Flags().SetAnnotation("body-param", flagutil.UnionNeedsAForm, []string{"body-param.buttons"}) + check.Flags().String("body-param.response", "", "") + _ = check.Flags().SetAnnotation("body-param", flagutil.UnionNeedsAForm, []string{"body-param.response"}) + + cases := []struct { + c *cobra.Command + in, want string + }{ + {branch, " vf update-branch --project-id ", " vf update-branch --project-id --body-param.buttons.label "}, + {check, " vf create", " vf create --project-id --body-param.response "}, + {check, " vf create --body-param '{}'", " vf create --body-param '{}' --project-id "}, + {branch, " vf update-branch --body-param.card.label x", " vf update-branch --body-param.card.label x --project-id "}, + } + for _, tc := range cases { + if got := fixExample(tc.c, tc.in); got != tc.want { + t.Errorf("fixExample(%q)\n got %q\nwant %q", tc.in, got, tc.want) + } + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index 9ba0105..788bc29 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -240,6 +240,7 @@ func NewRootCommand() (*cobra.Command, error) { } describeBodyFlags(rootCmd) // bodyhelp.go: --body says how stdin is read + fixExamples(rootCmd) // examplehelp.go: every example runs as written rootCmd.SetUsageTemplate(groupedUsageTemplate()) return rootCmd, nil diff --git a/internal/cli/tableview_test.go b/internal/cli/tableview_test.go new file mode 100644 index 0000000..fd6650e --- /dev/null +++ b/internal/cli/tableview_test.go @@ -0,0 +1,22 @@ +// This file is not generated by Speakeasy. It covers output/tableview.go +// end to end: `-o table` on the responses that wrap their data. + +package cli + +import ( + "strings" + "testing" +) + +func TestOutputTableShowsWhatAResponseWraps(t *testing.T) { + out, err := runAgainst(t, `{"environments":[{"alias":"main","name":"Main"},{"alias":"staging","name":"Staging"}]}`, + "environment", "list", "-p", "p1", "-o", "table") + if err != nil || !strings.Contains(out, "staging") { + t.Errorf("environment list -o table: %v\n%s", err, out) + } + out, err = runAgainst(t, `{"transcripts":[{"id":"6b0c-transcript"}],"returned":1,"hasMore":false}`, + "transcript", "search", "-p", "p1", "-o", "table") + if err != nil || !strings.Contains(out, "6b0c-transcript") { + t.Errorf("transcript search -o table dropped the transcripts: %v\n%s", err, out) + } +} diff --git a/internal/cli/test/run/wait.go b/internal/cli/test/run/wait.go index d2d44d8..312d307 100644 --- a/internal/cli/test/run/wait.go +++ b/internal/cli/test/run/wait.go @@ -78,8 +78,9 @@ func runWaitCmd(cmd *cobra.Command, args []string) error { return output.Error(cmd, err) } + verdict := waitVerdict(cmd, res) // wait_exit.go: exit non-zero unless every run passed if err := output.Result(cmd, res); err != nil { return err } - return nil + return verdict() } diff --git a/internal/cli/test/run/wait_exit.go b/internal/cli/test/run/wait_exit.go new file mode 100644 index 0000000..8539a9c --- /dev/null +++ b/internal/cli/test/run/wait_exit.go @@ -0,0 +1,118 @@ +// This file is not generated by Speakeasy. It makes `vf test run wait` and +// `vf test run wait-suite` exit non-zero unless every run passed. +// +// Both printed the runs' results and exited 0 whatever they were, while +// `create-suite --wait` exits 1 when a run fails. So a pipeline that started +// runs and then waited for them went green on failing tests. Now the three +// agree: once the result is printed, a run that failed or was canceled, a run +// still going when the wait stopped, or a run ID that wasn't found makes the +// command exit 1, and the error says which. -o json and --jq skip decoding +// the response, so the verdict reads the raw body and puts it back to be +// printed as before. + +package run + +import ( + "fmt" + "strings" + "time" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" +) + +func noVerdict() error { return nil } + +// waitVerdict reads what `vf test run wait` got back, before it is printed, +// and returns how the command exits once it has been: nil only when every +// run passed. +func waitVerdict(cmd *cobra.Command, res *operations.StableTestRunControllerWaitResponse) func() error { + if res == nil || client.IsDryRun(cmd) { + return noVerdict + } + w := res.StableTestRunWaitResponse + if w == nil { + w = &components.StableTestRunWaitResponse{} + if !output.PeekJSON(res.HTTPMeta.Response, w) { + return noVerdict + } + } + return func() error { return runsOutcome(cmd, w) } +} + +// waitSuiteVerdict is waitVerdict for `vf test run wait-suite`, judged as +// `create-suite --wait` judges the same answer. +func waitSuiteVerdict(cmd *cobra.Command, res *operations.StableTestRunControllerWaitSuiteResponse) func() error { + if res == nil || client.IsDryRun(cmd) { + return noVerdict + } + w := res.StableTestRunSuiteWaitResponse + if w == nil { + w = &components.StableTestRunSuiteWaitResponse{} + if !output.PeekJSON(res.HTTPMeta.Response, w) { + return noVerdict + } + } + target := suiteTarget{bulkID: w.BulkID} + target.projectID, _ = flagutil.GetStringFlag(cmd, "project-id") + target.environmentAlias, _ = flagutil.GetStringFlag(cmd, "environment-alias") + if serverURL, changed := flagutil.GetStringFlag(cmd, "server-url"); changed { + target.serverURL = serverURL + } + if target.bulkID == "" { + target.bulkID, _ = flagutil.GetStringFlag(cmd, "bulk-id") + } + return func() error { + return suiteOutcome(cmd, target, w, time.Duration(w.WaitedSeconds)*time.Second) + } +} + +// runsOutcome is nil only when every run waited for passed. +func runsOutcome(cmd *cobra.Command, w *components.StableTestRunWaitResponse) error { + var failed, canceled, going []string + for _, r := range w.Runs { + switch r.Status { + case components.StableTestRunWaitResponseStatusPassed: + case components.StableTestRunWaitResponseStatusFailed: + failed = append(failed, r.RunID) + case components.StableTestRunWaitResponseStatusCanceled: + canceled = append(canceled, r.RunID) + default: + going = append(going, r.RunID) + } + } + project, _ := flagutil.GetStringFlag(cmd, "project-id") + env, _ := flagutil.GetStringFlag(cmd, "environment-alias") + flags := fmt.Sprintf("--project-id %s --environment-alias %s", shellQuote(project), shellQuote(env)) + switch { + case len(failed)+len(canceled) > 0: + return suiteError(cmd, "test_runs_failed", + fmt.Sprintf("%d of %d runs did not pass (%d failed, %d canceled)", len(failed)+len(canceled), len(w.Runs), len(failed), len(canceled)), + []string{"Read a run's logs: vf test run get " + flags + " --run-id " + shellQuote(append(failed, canceled...)[0])}) + case len(going) > 0 || !w.Done: + hints := []string{} + if len(going) > 0 { + hints = append(hints, "Keep waiting: vf test run wait "+flags+" --run-ids "+strings.Join(quoteAll(going), " --run-ids ")) + } + return suiteError(cmd, "test_runs_unfinished", + fmt.Sprintf("%d of %d runs were still going when the wait stopped after %ds", len(going), len(w.Runs), w.WaitedSeconds), hints) + case len(w.NotFoundRunIDs) > 0: + return suiteError(cmd, "test_runs_not_found", + fmt.Sprintf("%d of the runs asked for weren't found: %s", len(w.NotFoundRunIDs), strings.Join(w.NotFoundRunIDs, ", ")), + []string{"Pass each run's id from 'vf test run create', not its testID"}) + } + return nil +} + +func quoteAll(values []string) []string { + out := make([]string, len(values)) + for i, v := range values { + out[i] = shellQuote(v) + } + return out +} diff --git a/internal/cli/test/run/waitsuite.go b/internal/cli/test/run/waitsuite.go index fc37236..de18b9b 100644 --- a/internal/cli/test/run/waitsuite.go +++ b/internal/cli/test/run/waitsuite.go @@ -79,8 +79,9 @@ func runWaitSuiteCmd(cmd *cobra.Command, args []string) error { return output.Error(cmd, err) } + verdict := waitSuiteVerdict(cmd, res) // wait_exit.go: exit non-zero unless every run passed if err := output.Result(cmd, res); err != nil { return err } - return nil + return verdict() } diff --git a/internal/cli/waitexit_test.go b/internal/cli/waitexit_test.go new file mode 100644 index 0000000..a3a2412 --- /dev/null +++ b/internal/cli/waitexit_test.go @@ -0,0 +1,122 @@ +// This file is not generated by Speakeasy. It covers wait_exit.go: `vf test +// run wait` and `wait-suite` print the result, then exit non-zero unless +// every run passed, in every output format. + +package cli + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// runAgainst runs args against a server that answers every request with body, +// and returns what was printed and the error the command ended with. +func runAgainst(t *testing.T, body string, args ...string) (string, error) { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, body) + })) + t.Cleanup(srv.Close) + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", srv.URL) + t.Setenv("HOME", t.TempDir()) + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + root.SetOut(&buf) + root.SetErr(&buf) + root.SetIn(strings.NewReader("")) + root.SetArgs(append(args, "--agent-mode=false", "--no-interactive")) + _, err = root.ExecuteC() + return buf.String(), err +} + +func waitBody(statuses ...string) string { + type run struct { + RunID string `json:"runID"` + TestID string `json:"testID"` + Status string `json:"status"` + TotalChecks float64 `json:"totalChecks"` + } + runs := []run{} + done := true + for i, s := range statuses { + runs = append(runs, run{RunID: "run" + string(rune('a'+i)), TestID: "t", Status: s, TotalChecks: 1}) + if s == "running" || s == "pending" || s == "idle" { + done = false + } + } + b, _ := json.Marshal(map[string]any{"done": done, "stoppedBy": "finished", "waitedSeconds": 3, "runs": runs}) + return string(b) +} + +func TestTestRunWaitExitsNonZeroUnlessEveryRunPassed(t *testing.T) { + waitArgs := []string{"test", "run", "wait", "-p", "p1", "-e", "main", "-r", "runa", "-r", "runb"} + for _, format := range [][]string{nil, {"-o", "json"}, {"--jq", ".runs[].status"}} { + name := "pretty" + if format != nil { + name = strings.Join(format, " ") + } + t.Run(name, func(t *testing.T) { + out, err := runAgainst(t, waitBody("passed", "passed"), append(waitArgs, format...)...) + if err != nil { + t.Errorf("all passed, but got error %v; output:\n%s", err, out) + } + + out, err = runAgainst(t, waitBody("passed", "failed"), append(waitArgs, format...)...) + if err == nil || !strings.Contains(err.Error(), "1 of 2 runs did not pass") { + t.Errorf("a run failed, but got error %v; output:\n%s", err, out) + } + if !strings.Contains(out, "failed") { + t.Errorf("the result wasn't printed before the error:\n%s", out) + } + + out, err = runAgainst(t, waitBody("passed", "running"), append(waitArgs, format...)...) + if err == nil || !strings.Contains(err.Error(), "still going") { + t.Errorf("a run was still going, but got error %v; output:\n%s", err, out) + } + }) + } +} + +func TestTestRunWaitSaysWhichRunsWerentFound(t *testing.T) { + body := `{"done":true,"stoppedBy":"finished","waitedSeconds":0,"runs":[],"notFoundRunIDs":["nope"]}` + _, err := runAgainst(t, body, "test", "run", "wait", "-p", "p1", "-e", "main", "-r", "nope") + if err == nil || !strings.Contains(err.Error(), "weren't found: nope") { + t.Errorf("got %v", err) + } +} + +func TestTestRunWaitSuiteExitsNonZeroWhenARunFailed(t *testing.T) { + suite := func(passed, failed int) string { + b, _ := json.Marshal(map[string]any{ + "bulkID": "bulk1", "done": true, "stoppedBy": "finished", "waitedSeconds": 3, + "counts": map[string]int{"passed": passed, "failed": failed, "canceled": 0, "unfinished": 0, "total": passed + failed}, + "runs": []any{}, + }) + return string(b) + } + args := []string{"test", "run", "wait-suite", "-p", "p1", "-e", "main", "-b", "bulk1"} + for _, format := range [][]string{nil, {"-o", "json"}} { + if out, err := runAgainst(t, suite(2, 0), append(args, format...)...); err != nil { + t.Errorf("%v: all passed, but got error %v; output:\n%s", format, err, out) + } + if out, err := runAgainst(t, suite(1, 1), append(args, format...)...); err == nil { + t.Errorf("%v: a run failed, but it exited 0; output:\n%s", format, out) + } + } +} diff --git a/internal/flagutil/listflags.go b/internal/flagutil/listflags.go new file mode 100644 index 0000000..6d7f941 --- /dev/null +++ b/internal/flagutil/listflags.go @@ -0,0 +1,84 @@ +// This file is not generated by Speakeasy. It lets every list flag take the +// list the way its help example writes it. +// +// A list flag (pflag's stringArray) took one value per flag, as is. But the +// generated examples write lists as JSON (`--run-ids '["a","b"]'`), some help +// says "Send [] when it has none", and `test run create-suite --test-ids` +// splits commas. So `--run-ids '["a"]'` sent the one ID `["a"]`, and +// `--run-ids a,b` the one ID `a,b`. The server then said none of them existed, +// and the error blamed the project ID. +// +// Now a value that starts with [ is read as a JSON array of strings, `[]` +// included, and a list of IDs or names also splits on commas. Lists of free +// text, such as URL patterns or words, keep their commas. + +package flagutil + +import ( + "encoding/json" + "fmt" + "strings" +) + +// describeList adds how to pass several values to a list flag's help. +func describeList(m FlagMeta) string { + if m.Kind != FlagKindStringArray { + return m.Description + } + how := "Repeat the flag or pass a JSON array." + if splitsOnCommas(m.FlagName) { + how = "Separate values with commas, repeat the flag, or pass a JSON array." + } + desc := strings.TrimSpace(m.Description) + if desc == "" || desc == "list of values" { + return how + } + if strings.Contains(desc, "repeat the flag") { + return desc + } + // After the whole description, [required] included: help keeps the + // spec's text word for word (test/flag-errors.test.ts checks it). + return desc + " " + how +} + +// ListValues turns what was passed to the list flag name into its values. A +// value that starts with [ is a JSON array of strings, so `["a","b"]` is two +// values and `[]` none. Lists of IDs and names also split on commas. explicit +// is true when a JSON array was given, so an empty list was asked for. +func ListValues(name string, given []string) (values []string, explicit bool, err error) { + values = []string{} + for _, v := range given { + t := strings.TrimSpace(v) + if strings.HasPrefix(t, "[") { + var list []string + if err := json.Unmarshal([]byte(t), &list); err != nil { + return nil, false, fmt.Errorf("--%s got %s, which isn't a JSON array of strings. Pass a list as --%s a --%s b, or as --%s '[\"a\",\"b\"]'", name, v, name, name, name) + } + values = append(values, list...) + explicit = true + continue + } + if !splitsOnCommas(name) { + values = append(values, v) + continue + } + for _, part := range strings.Split(v, ",") { + if part = strings.TrimSpace(part); part != "" { + values = append(values, part) + } + } + } + return values, explicit, nil +} + +// splitsOnCommas reports whether the list flag name holds IDs or names, +// which never contain a comma: --run-ids, --exclude-id, --turn-order, +// --expected-steps, --kinds, --levels, --interfaces, --resource-types. +func splitsOnCommas(name string) bool { + for _, suffix := range []string{"ids", "-id", "order", "-steps", "-actions", "kinds", "levels", "interfaces", "types"} { + if strings.HasSuffix(name, suffix) { + return true + } + } + return false +} diff --git a/internal/flagutil/listflags_test.go b/internal/flagutil/listflags_test.go new file mode 100644 index 0000000..af84b25 --- /dev/null +++ b/internal/flagutil/listflags_test.go @@ -0,0 +1,92 @@ +// This file is not generated by Speakeasy. It covers listflags.go. + +package flagutil + +import ( + "encoding/json" + "slices" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +func TestListValues(t *testing.T) { + cases := []struct { + name string + given []string + want []string + }{ + {"run-ids", []string{`["a","b"]`}, []string{"a", "b"}}, + {"run-ids", []string{"a,b", " c "}, []string{"a", "b", "c"}}, + {"run-ids", []string{`["a"]`, "b"}, []string{"a", "b"}}, + {"expected-actions", []string{"[]"}, []string{}}, + {"exclude-id", []string{"x, y"}, []string{"x", "y"}}, + {"levels", []string{"fatal,error"}, []string{"fatal", "error"}}, + // URL patterns and written words keep their commas. + {"exclude", []string{"/a,b/*"}, []string{"/a,b/*"}}, + {"remove", []string{"Smith, Jr."}, []string{"Smith, Jr."}}, + {"remove", []string{`["Smith, Jr.","Dr."]`}, []string{"Smith, Jr.", "Dr."}}, + } + for _, c := range cases { + got, _, err := ListValues(c.name, c.given) + if err != nil || !slices.Equal(got, c.want) { + t.Errorf("ListValues(%s, %q) = %q, %v; want %q", c.name, c.given, got, err, c.want) + } + } + if _, _, err := ListValues("run-ids", []string{`["a",`}); err == nil { + t.Error("a broken JSON array was taken as an ID") + } else if !strings.Contains(err.Error(), "--run-ids a --run-ids b") { + t.Errorf("the error doesn't say how to pass a list: %v", err) + } +} + +type listTestRequest struct { + Body struct { + RunIDs []string `json:"runIDs"` + ExpectedActions []string `json:"expectedActions"` + } +} + +var listTestMeta = []FlagMeta{ + {FlagName: "run-ids", FieldPath: "Body.RunIDs", Kind: FlagKindStringArray, Optional: true, Description: "The runs."}, + {FlagName: "expected-actions", FieldPath: "Body.ExpectedActions", Kind: FlagKindStringArray, Required: true, Description: "Send [] when it has none. [required]"}, +} + +func buildList(t *testing.T, args ...string) (string, error) { + t.Helper() + cmd := &cobra.Command{Use: "wait"} + RegisterFlags(cmd, listTestMeta) + if err := cmd.ParseFlags(args); err != nil { + t.Fatal(err) + } + req, err := BuildRequest[listTestRequest](cmd, listTestMeta, "Body", "body") + if err != nil { + return "", err + } + b, _ := json.Marshal(req.Body) + return string(b), nil +} + +// The generated examples' `--run-ids '["a","b"]'` sends two IDs, and the +// help's "Send [] when it has none" sends an empty list. +func TestAListFlagTakesItsExamplesJSON(t *testing.T) { + got, err := buildList(t, "--run-ids", `["a","b"]`, "--expected-actions", "[]") + if want := `{"runIDs":["a","b"],"expectedActions":[]}`; err != nil || got != want { + t.Errorf("got %s, %v; want %s", got, err, want) + } + if _, err := buildList(t, "--run-ids", "a"); err == nil || !strings.Contains(err.Error(), "--expected-actions") { + t.Errorf("a required list that wasn't given passed: %v", err) + } +} + +func TestAListFlagSaysHowToPassSeveralValues(t *testing.T) { + cmd := &cobra.Command{Use: "wait"} + RegisterFlags(cmd, listTestMeta) + if got := cmd.Flags().Lookup("run-ids").Usage; got != "The runs. Separate values with commas, repeat the flag, or pass a JSON array." { + t.Errorf("--run-ids help = %q", got) + } + if got := cmd.Flags().Lookup("expected-actions").Usage; got != "Send [] when it has none. [required] Separate values with commas, repeat the flag, or pass a JSON array." { + t.Errorf("--expected-actions help = %q", got) + } +} diff --git a/internal/flagutil/metadata.go b/internal/flagutil/metadata.go index 1aa4ded..4d55dea 100644 --- a/internal/flagutil/metadata.go +++ b/internal/flagutil/metadata.go @@ -106,6 +106,7 @@ type FlagMeta struct { func RegisterFlags(cmd *cobra.Command, meta []FlagMeta) { for _, m := range meta { m.Description = flagDescription(m.Description) // see description.go + m.Description = describeList(m) // listflags.go: how to pass several values // Skip if a flag with this name already exists — either inherited from // a parent command (persistent globals/security) or already registered // locally (e.g., operation security flags like username/password). @@ -117,6 +118,7 @@ func RegisterFlags(cmd *cobra.Command, meta []FlagMeta) { case FlagKindUnion: if m.Union != nil { registerUnionFlags(cmd, m) + markUnionNeedsAForm(cmd, m) // unionform.go: help examples give it a form } case FlagKindFile, FlagKindFileArray, FlagKindBytes: registerStringFlag(cmd, m) @@ -602,8 +604,12 @@ func buildFloat64Field(cmd *cobra.Command, v reflect.Value, m FlagMeta) error { func buildStringArrayField(cmd *cobra.Command, v reflect.Value, m FlagMeta) error { val, changed := GetStringArrayFlag(cmd, m.FlagName) + val, explicit, err := ListValues(m.FlagName, val) // listflags.go: JSON arrays and commas + if err != nil { + return err + } - if m.Required && len(val) == 0 { + if m.Required && len(val) == 0 && !explicit { return fmt.Errorf("missing required flag: --%s", m.FlagName) } diff --git a/internal/flagutil/stdin.go b/internal/flagutil/stdin.go index 4f02394..9195da0 100644 --- a/internal/flagutil/stdin.go +++ b/internal/flagutil/stdin.go @@ -179,10 +179,12 @@ func (f *firstReadSignal) Read(p []byte) (int, error) { // 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. +// given. Path and query parameters aren't part of the body. A body that is a +// union as a whole (`test turn create`'s --body-param.user.…) is filled by a +// flag whose field is the body itself. func bodyFlagsGiven(cmd *cobra.Command, meta []FlagMeta, bodyFieldPath string) bool { for _, m := range meta { - if bodyFieldPath != "" && !strings.HasPrefix(m.FieldPath, bodyFieldPath+".") { + if bodyFieldPath != "" && m.FieldPath != bodyFieldPath && !strings.HasPrefix(m.FieldPath, bodyFieldPath+".") { continue } if FlagChanged(cmd, m.FlagName) || (m.Kind == FlagKindUnion && HasAnyFlagWithPrefix(cmd, m.FlagName+".")) { diff --git a/internal/flagutil/stdinflags_test.go b/internal/flagutil/stdinflags_test.go index 85499c3..80837e3 100644 --- a/internal/flagutil/stdinflags_test.go +++ b/internal/flagutil/stdinflags_test.go @@ -261,3 +261,37 @@ func TestBodyDashOnAnEmptyStdinSaysSo(t *testing.T) { t.Errorf("err = %v", err) } } + +// `sleep 15 | vf test turn create --body-param.user.…` waited 10s on the pipe, +// and a `while read` loop ran once: a body that is a union as a whole is +// filled by a flag whose field is the body itself, which the check skipped. +func TestAWholeBodyUnionsFlagsTurnStdinOff(t *testing.T) { + meta := []FlagMeta{ + {FlagName: "project-id", FieldPath: "ProjectID", Kind: FlagKindString}, + {FlagName: "body-param", FieldPath: "Body", Kind: FlagKindUnion}, + } + for _, args := range [][]string{ + {"--project-id", "p1", "--body-param.user.text", "hi"}, + {"--project-id", "p1", "--body-param", `{"type":"user"}`}, + } { + cmd := &cobra.Command{Use: "create"} + cmd.Flags().String("project-id", "", "") + cmd.Flags().String("body-param", "", "") + cmd.Flags().String("body-param.user.text", "", "") + if err := cmd.ParseFlags(args); err != nil { + t.Fatal(err) + } + if !bodyFlagsGiven(cmd, meta, "Body") { + t.Errorf("%q: the body's own flag wasn't counted, so stdin would be read", args) + } + } + cmd := &cobra.Command{Use: "create"} + cmd.Flags().String("project-id", "", "") + cmd.Flags().String("body-param", "", "") + if err := cmd.ParseFlags([]string{"--project-id", "p1"}); err != nil { + t.Fatal(err) + } + if bodyFlagsGiven(cmd, meta, "Body") { + t.Error("a path parameter alone isn't a body flag") + } +} diff --git a/internal/flagutil/unionform.go b/internal/flagutil/unionform.go new file mode 100644 index 0000000..419ba28 --- /dev/null +++ b/internal/flagutil/unionform.go @@ -0,0 +1,30 @@ +// This file is not generated by Speakeasy. It marks the union flags that must +// be given one of their forms, so that a help example can give one. +// +// A union that isn't a pointer can't be left out: a whole body that is a +// union (`test check create`'s --body-param) sent empty fails with "the body +// is none of its forms". Its flag isn't marked required, though, because the +// value comes from any one of several flags: --body-param, or a variant's +// --body-param.response, or that variant's field flags. So nothing told the +// help examples to set it, and 7 of them failed as written. + +package flagutil + +import "github.com/spf13/cobra" + +// UnionNeedsAForm annotates a union flag that must be given one of its forms. +// Its value is the first variant's flag, or the union's own flag when its +// variants have no flags of their own. +const UnionNeedsAForm = "vf:union-needs-a-form" + +// markUnionNeedsAForm annotates m's flag when the union isn't optional. +func markUnionNeedsAForm(cmd *cobra.Command, m FlagMeta) { + if m.Union == nil || m.Union.Optional || cmd.Flags().Lookup(m.FlagName) == nil { + return + } + form := m.FlagName + if len(m.Union.Variants) > 0 { + form = m.Union.Variants[0].FlagName + } + _ = cmd.Flags().SetAnnotation(m.FlagName, UnionNeedsAForm, []string{form}) +} diff --git a/internal/flagutil/unionform_test.go b/internal/flagutil/unionform_test.go new file mode 100644 index 0000000..dfdb395 --- /dev/null +++ b/internal/flagutil/unionform_test.go @@ -0,0 +1,25 @@ +// This file is not generated by Speakeasy. It covers unionform.go. + +package flagutil + +import ( + "testing" + + "github.com/spf13/cobra" +) + +func TestAUnionThatIsntOptionalNeedsAForm(t *testing.T) { + variants := []UnionVariantMeta{{DiscriminatorValue: "response", FlagName: "body-param.response"}, {DiscriminatorValue: "tool", FlagName: "body-param.tool"}} + cmd := &cobra.Command{Use: "create"} + RegisterFlags(cmd, []FlagMeta{ + {FlagName: "body-param", FieldPath: "Body", Kind: FlagKindUnion, Union: &UnionMeta{Discriminated: true, DiscriminatorKey: "Type", Variants: variants}}, + {FlagName: "action", FieldPath: "Body.Action", Kind: FlagKindUnion, Union: &UnionMeta{}}, + {FlagName: "settings", FieldPath: "Body.Settings", Kind: FlagKindUnion, Union: &UnionMeta{Optional: true, Variants: []UnionVariantMeta{{FlagName: "settings.a"}}}}, + }) + for flag, want := range map[string]string{"body-param": "body-param.response", "action": "action", "settings": ""} { + got := cmd.Flags().Lookup(flag).Annotations[UnionNeedsAForm] + if (want == "" && len(got) != 0) || (want != "" && (len(got) != 1 || got[0] != want)) { + t.Errorf("--%s: got %q, want %q", flag, got, want) + } + } +} diff --git a/internal/interactive/formwrap.go b/internal/interactive/formwrap.go new file mode 100644 index 0000000..94349f9 --- /dev/null +++ b/internal/interactive/formwrap.go @@ -0,0 +1,47 @@ +// This file is not generated by Speakeasy. It keeps a form field's input in +// view when its description is longer than a line. +// +// huh v0.6 doesn't wrap a field's description. The form's viewport does, +// after the field's ┃ border is drawn, so the wrapped lines lost the border, +// and the form, which had sized itself by the unwrapped lines, cut off the +// bottom of the field: the input line or the options. At 72 columns most +// required fields hid their input. Keys still reached it, so people typed +// blind, and a hidden select submitted its first option. +// +// The theme now wraps descriptions to the width a field has inside its +// border, so every line the form counts is a line on screen. And a select's +// height, which huh counts from the top of its title, now includes the title +// and description, so the options a select was sized for all show. + +package interactive + +import ( + "github.com/charmbracelet/huh" + "github.com/charmbracelet/lipgloss" +) + +// fieldTextWidth is how wide a field's text can be in a form formWidth() +// wide: the width less the field's border and padding. +func fieldTextWidth(t *huh.Theme) int { + return max(20, formWidth()-t.Focused.Base.GetHorizontalFrameSize()) +} + +// wrapDescriptions has t wrap every field description to the field's width. +func wrapDescriptions(t *huh.Theme) { + w := fieldTextWidth(t) + t.Focused.Description = t.Focused.Description.Width(w) + t.Blurred.Description = t.Blurred.Description.Width(w) +} + +// selectHeight is the height to give a select that should show options rows +// under title and desc. huh's height counts the title and description lines +// too, so a height of len(options) showed fewer options than there were, and +// none at all under a long description. +func selectHeight(options int, title, desc string) int { + t := formTheme() + lines := lipgloss.Height(t.Focused.Title.Render(title)) + if desc != "" { + lines += lipgloss.Height(t.Focused.Description.Render(desc)) + } + return options + lines +} diff --git a/internal/interactive/formwrap_test.go b/internal/interactive/formwrap_test.go new file mode 100644 index 0000000..96e2685 --- /dev/null +++ b/internal/interactive/formwrap_test.go @@ -0,0 +1,66 @@ +// This file is not generated by Speakeasy. It covers formwrap.go. + +package interactive + +import ( + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/huh" + "github.com/charmbracelet/x/ansi" + + "github.com/voiceflow/cli/internal/flagutil" +) + +// goesTo is event create's --goes-to, as generated: a description that +// wraps to several lines over a three-option select. +var goesTo = flagutil.FlagMeta{FlagName: "goes-to", Kind: flagutil.FlagKindEnum, Required: true, + EnumValues: []string{"flow", "global_agent", "continue"}, + Description: "What the agent does when the event arrives. `flow` runs the workflow named by workflowID. " + + "`global_agent` hands the conversation back to the agent to decide what to do next, and is only valid " + + "in an agent project. `continue` carries on the conversation where it was, for an event that only updates user info. [required]"} + +// screen is what a form holding field shows, the way PromptAndSetFlags runs it. +func screen(t *testing.T, field huh.Field) string { + t.Helper() + form := huh.NewForm(huh.NewGroup(field)).WithWidth(formWidth()).WithTheme(formTheme()).WithShowHelp(false) + form.Init() + model, _ := form.Update(tea.WindowSizeMsg{Width: formWidth(), Height: 40}) + return ansi.Strip(model.View()) +} + +// A description longer than a line keeps the field's border on every line, +// fits the width, and leaves every option of a select on screen. +func TestALongDescriptionLeavesTheFieldInView(t *testing.T) { + field, _ := buildFormField(goesTo) + view := screen(t, field) + for _, option := range goesTo.EnumValues { + if !strings.Contains(view, " "+option) && !strings.Contains(view, "> "+option) { + t.Errorf("option %q isn't on screen:\n%s", option, view) + } + } + for _, line := range strings.Split(strings.TrimRight(view, "\n"), "\n") { + if strings.TrimSpace(line) == "" { + continue + } + if !strings.HasPrefix(line, "┃") { + t.Errorf("a line lost the field's border:\n%q\nin:\n%s", line, view) + } + if w := ansi.StringWidth(line); w > formWidth() { + t.Errorf("a line is %d wide, wider than the form's %d: %q", w, formWidth(), line) + } + } +} + +// The same for a text input: its input line shows under the description. +func TestALongDescriptionLeavesTheInputInView(t *testing.T) { + m := flagutil.FlagMeta{FlagName: "name", Kind: flagutil.FlagKindString, Required: true, + Description: strings.Repeat("The name of the secret, which a {token} in a default-value field binds to. ", 3) + "[required]"} + field, _ := buildFormField(m) + view := screen(t, field) + lines := strings.Split(strings.TrimSpace(view), "\n") + if last := strings.TrimSpace(lines[len(lines)-1]); last != "┃ >" { + t.Errorf("the input line isn't the field's last line:\n%s", view) + } +} diff --git a/internal/interactive/interactive.go b/internal/interactive/interactive.go index b058668..7df9c7b 100644 --- a/internal/interactive/interactive.go +++ b/internal/interactive/interactive.go @@ -146,6 +146,7 @@ func formTheme() *huh.Theme { t.Blurred.SelectSelector = t.Blurred.SelectSelector.Foreground(dimmed) t.Blurred.SelectedPrefix = lipgloss.NewStyle().Foreground(dimmed).SetString("✓ ") t.Blurred.UnselectedPrefix = lipgloss.NewStyle().SetString(" ") + wrapDescriptions(&t) // formwrap.go: a long description doesn't hide the input return &t } @@ -412,6 +413,7 @@ func buildFormField(m flagutil.FlagMeta) (huh.Field, flagBinding) { if height > 10 { height = 10 } + height = selectHeight(height, title, desc) // formwrap.go: show the options under the title and description field := huh.NewSelect[string](). Title(title). Description(desc). diff --git a/internal/interactive/pickers.go b/internal/interactive/pickers.go index 227605f..71d82ea 100644 --- a/internal/interactive/pickers.go +++ b/internal/interactive/pickers.go @@ -336,7 +336,7 @@ var chooseInForm = func(title, desc string, options []huh.Option[string], value Title(title). Description(desc). Options(options...). - Height(min(len(options), 10)). + Height(selectHeight(min(len(options), 10), title, desc)). Value(value)) } diff --git a/internal/output/created.go b/internal/output/created.go index 7341897..71a299f 100644 --- a/internal/output/created.go +++ b/internal/output/created.go @@ -190,9 +190,9 @@ func nextSteps(cmd *cobra.Command, group, id string) []ui.Tip { 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"}) + tips = append(tips, ui.Tip{Command: withScope(cmd, sibling.CommandPath()+" --"+idFlag+" "+id), Does: "see it"}) // hintfit.go: with -p and -e case sibling.Name() == "list": - tips = append(tips, ui.Tip{Command: sibling.CommandPath(), Does: "list them"}) + tips = append(tips, ui.Tip{Command: withScope(cmd, sibling.CommandPath()), Does: "list them"}) } } return tips diff --git a/internal/output/explain.go b/internal/output/explain.go index 49d46b3..e18ffbc 100644 --- a/internal/output/explain.go +++ b/internal/output/explain.go @@ -178,7 +178,7 @@ func explainAPI(cmd *cobra.Command, err error, status int, body string, headers x := Explanation{ Type: classifyErrorType(status), Title: action(cmd) + " · HTTP " + strconv.Itoa(status) + " " + http.StatusText(status), - Message: serverMessage(status, fields, body), + Message: vfCommandNames(cmd, serverMessage(status, fields, body)), // hintfit.go Details: fieldErrors(cmd, fields), Docs: docsFor(cmd), } @@ -218,6 +218,11 @@ func explainAPI(cmd *cobra.Command, err error, status int, body string, headers x.Next = []string{"Add credits or upgrade the workspace's plan in Voiceflow"} } + case status == 403 && !refusalIsAboutAccess(x.Message): + // hintfit.go: a rule of the resource's own, which the message states. + x.Why = []string{"Voiceflow refused this, for the reason above. Your access isn't the problem."} + x.Next = []string{"`" + cmd.CommandPath() + " --help` says what it can and can't do"} + 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."} x.Next = []string{"`vf workspace list` shows the workspaces you can reach", "Ask an admin of that workspace or organization for access"} @@ -231,19 +236,24 @@ func explainAPI(cmd *cobra.Command, err error, status int, body string, headers } 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 why, next, ok := explainMissingRoute(cmd, x.Message); ok { // hintfit.go + x.Type, x.Why, x.Next = "unsupported_command", why, next + break } + x.Why = notFoundWhy(cmd) // hintfit.go: the ID of what was looked up first if list := listCommand(cmd); list != "" { - x.Next = []string{"`" + list + "` lists the IDs you can use"} + x.Next = []string{"`" + withScope(cmd, 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 !conflictIsAboutAName(x.Message) { // hintfit.go: the message says what conflicts + x.Why = []string{"It conflicts with the current state, as the message says. Nothing was changed."} + x.Next = nil + } if list := listCommand(cmd); list != "" { - x.Next = append(x.Next, "`"+list+"` shows what's there") + x.Next = append(x.Next, "`"+withScope(cmd, list)+"` shows what's there") } case status == 429: @@ -256,6 +266,11 @@ func explainAPI(cmd *cobra.Command, err error, status int, body string, headers 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)} + if status == 500 && x.Message != "" && !soundsTransient(x.Message) { + // hintfit.go: a 500 that says what's wrong fails the same way again. + x.Why = []string{"Voiceflow failed on this request, and said why above. With the same values it will likely fail the same way."} + x.Next = []string{"Fix what the message names, then run it again", supportStep(headers)} + } default: x.Why = []string{"Voiceflow rejected the request."} @@ -593,25 +608,6 @@ func listCommand(cmd *cobra.Command) string { 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 { diff --git a/internal/output/hintfit.go b/internal/output/hintfit.go new file mode 100644 index 0000000..b61005c --- /dev/null +++ b/internal/output/hintfit.go @@ -0,0 +1,196 @@ +// This file is not generated by Speakeasy. It keeps vf's explanation of an +// API error from pointing away from the real cause. +// +// explainAPI starts from what each status usually means. The usability sweep +// found where that sent people the wrong way: +// +// - A 404 blamed the project and environment flags, never the ID of the +// thing looked up: `event get --event-id ` said to check +// --project-id. +// - A 404 whose body is "Cannot PATCH /v1/…" is a route the server doesn't +// have, not a wrong ID. `function patch-code` failed that way every time +// and the hint said to recheck three correct IDs. +// - A 500 that said what was wrong with the input ("Could not resolve +// 'nope' environment alias") still said "It's usually temporary. Run it +// again in a minute". +// - A 409 or 403 with its own reason ("oldString was not found in the +// current text", "Main environment cannot be deleted") got the stock +// "a name that's already taken" or "your account isn't allowed". +// - The commands in hints left out the scope flags they need, so pasting +// `vf event list` asked for a project. +// - A server message naming an MCP tool (search_instructions) named no vf +// command. + +package output + +import ( + "regexp" + "slices" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/session" +) + +// scopeFlags hold where a resource lives, as opposed to which one it is. +var scopeFlags = []string{"organization-id", "workspace-id", "project-id", "environment-alias", "environment-id"} + +// notFoundWhy says which IDs to check after a 404: the ones that name what +// was looked up first, then where it was looked for. +func notFoundWhy(cmd *cobra.Command) []string { + own, scope := givenIDFlags(cmd) + switch { + case len(own) > 0 && len(scope) > 0: + return []string{"Check " + strings.Join(own, ", ") + ": it may be wrong, or not be in " + strings.Join(scope, ", ") + "."} + case len(own) > 0: + return []string{"Check " + strings.Join(own, ", ") + ": it may be wrong, or belong to another workspace."} + case len(scope) > 0: + return []string{"Check " + strings.Join(scope, ", ") + ": it may be wrong, or belong to another workspace or environment."} + } + return []string{"The ID may be wrong, or belong to another workspace or environment."} +} + +// givenIDFlags lists the ID flags cmd was given, as typed: own names the +// thing acted on (--event-id, --run-ids, --id), scope where it lives. +func givenIDFlags(cmd *cobra.Command) (own, scope []string) { + if cmd == nil { + return nil, nil + } + cmd.Flags().Visit(func(f *pflag.Flag) { + given := "--" + f.Name + " " + flagValue(f) + switch { + case slices.Contains(scopeFlags, f.Name): + scope = append(scope, given) + case f.Name == "id" || strings.HasSuffix(f.Name, "-id") || strings.HasSuffix(f.Name, "-ids"): + own = append(own, given) + } + }) + slices.SortStableFunc(scope, func(a, b string) int { return scopeRank(a) - scopeRank(b) }) + return own, scope +} + +func scopeRank(given string) int { + name, _, _ := strings.Cut(strings.TrimPrefix(given, "--"), " ") + return slices.Index(scopeFlags, name) +} + +// flagValue is f's value as typed: a list's values joined by commas. +func flagValue(f *pflag.Flag) string { + if s, ok := f.Value.(pflag.SliceValue); ok { + return strings.Join(s.GetSlice(), ",") + } + return f.Value.String() +} + +// missingRoute is "Cannot PATCH /v1/stable/function/…": the reply of a server +// with no route for the request, whatever its IDs. +var missingRoute = regexp.MustCompile(`^Cannot (GET|POST|PUT|PATCH|DELETE) (/\S*)`) + +// explainMissingRoute explains a 404 for a route the server doesn't have. +func explainMissingRoute(cmd *cobra.Command, message string) (why, next []string, ok bool) { + m := missingRoute.FindStringSubmatch(message) + if m == nil { + return nil, nil, false + } + path, _, _ := strings.Cut(m[2], "?") + why = []string{"This Voiceflow server has no " + m[1] + " " + path + " route, so it can't run this command. The IDs weren't checked."} + if source := serverURLSource(cmd); source != "" { + why = append(why, "The server URL comes from "+source+"; that server may be older than this vf.") + } + next = []string{"`" + groupPath(cmd) + " --help` lists other commands that may do the same"} + return why, next, true +} + +func groupPath(cmd *cobra.Command) string { + if cmd.HasParent() && cmd.Parent().HasParent() { + return cmd.Parent().CommandPath() + } + return cmd.CommandPath() +} + +// conflictIsAboutAName reports whether a 409's message is the usual one, +// something that already exists, which the stock hint is about. +func conflictIsAboutAName(message string) bool { + if message == "" { + return true + } + lower := strings.ToLower(message) + for _, word := range []string{"exist", "already", "taken", "duplicate", "unique", "in use"} { + if strings.Contains(lower, word) { + return true + } + } + return false +} + +// refusalIsAboutAccess reports whether a 403's message is about who may do +// this, which the stock hint is about, rather than a rule of the resource's +// own ("Main environment cannot be deleted"). +func refusalIsAboutAccess(message string) bool { + if message == "" { + return true + } + lower := strings.ToLower(message) + for _, word := range []string{"permission", "access", "allowed", "forbidden", "authori", "role", "scope", "plan", "workspace", "organization"} { + if strings.Contains(lower, word) { + return true + } + } + return false +} + +// soundsTransient reports whether a 500's message describes a passing +// failure, which running it again may get past. +func soundsTransient(message string) bool { + lower := strings.ToLower(message) + for _, word := range []string{"timeout", "timed out", "temporar", "unavailable", "try again", "retry", "overload", "econn", "socket", "connection"} { + if strings.Contains(lower, word) { + return true + } + } + return false +} + +// withScope is next, a command in the same tree as cmd, with the scope flags +// cmd was given that next also takes, so it runs when pasted. In the home +// prompt, where the context fills them in, it is next as is. +func withScope(cmd *cobra.Command, next string) string { + if session.Active() || cmd == nil { + return next + } + target, _, err := cmd.Root().Find(strings.Fields(next)[1:]) + if err != nil || target == nil { + return next + } + for _, name := range scopeFlags { + f := cmd.Flags().Lookup(name) + if f == nil || !f.Changed || target.Flags().Lookup(name) == nil || strings.Contains(next, "--"+name) { + continue + } + next += " --" + name + " " + quoteArg(f.Value.String()) + } + return next +} + +// snakeName is an MCP tool's name in a server message: search_instructions. +var snakeName = regexp.MustCompile("`?\\b[a-z]+(?:_[a-z]+)+\\b`?") + +// vfCommandNames rewrites the MCP tool names in a server message as the vf +// commands beside cmd that do the same: "Use search_instructions" becomes +// "Use `vf agent search-instructions`". Names with no such command stay. +func vfCommandNames(cmd *cobra.Command, message string) string { + if cmd == nil || !cmd.HasParent() { + return message + } + return snakeName.ReplaceAllStringFunc(message, func(name string) string { + kebab := strings.ReplaceAll(strings.Trim(name, "`"), "_", "-") + for _, sibling := range cmd.Parent().Commands() { + if sibling.Name() == kebab { + return "`" + sibling.CommandPath() + "`" + } + } + return name + }) +} diff --git a/internal/output/hintfit_test.go b/internal/output/hintfit_test.go new file mode 100644 index 0000000..9908645 --- /dev/null +++ b/internal/output/hintfit_test.go @@ -0,0 +1,124 @@ +// This file is not generated by Speakeasy. It covers hintfit.go: an API +// error's explanation points at the real cause. + +package output + +import ( + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/session" +) + +// scoped is 'vf ' with create, get, list and verbs, each taking -p, -e +// and ---id, with flags set on the command returned. +func scoped(t *testing.T, name, verb string, set map[string]string, more ...string) *cobra.Command { + t.Helper() + session.Stop() + root := &cobra.Command{Use: "vf"} + g := &cobra.Command{Use: name} + root.AddCommand(g) + var picked *cobra.Command + for _, v := range append([]string{"create", "get", "list"}, more...) { + c := &cobra.Command{Use: v, Short: strings.ToUpper(v[:1]) + v[1:] + " " + name, RunE: func(*cobra.Command, []string) error { return nil }} + c.Flags().StringP("project-id", "p", "", "") + c.Flags().StringP("environment-alias", "e", "", "") + c.Flags().String(name+"-id", "", "") + c.Flags().String("server-url", "", "") + c.Flags().String("timeout", "", "") + g.AddCommand(c) + if v == verb { + picked = c + } + } + for flag, value := range set { + if err := picked.Flags().Set(flag, value); err != nil { + t.Fatal(err) + } + } + return picked +} + +// `event get --event-id ` says to check --event-id, and the list it +// points to runs when pasted. +func TestANotFoundNamesTheIDOfWhatWasLookedUp(t *testing.T) { + cmd := scoped(t, "event", "get", map[string]string{"event-id": "ev1", "project-id": "p1", "environment-alias": "main"}) + x := ExplainError(cmd, apiError(404, `{"message":"No event exists with ID ev1"}`, nil)) + if want := "Check --event-id ev1: it may be wrong, or not be in --project-id p1, --environment-alias main."; strings.Join(x.Why, " ") != want { + t.Errorf("why = %q\nwant %q", x.Why, want) + } + if want := "`vf event list --project-id p1 --environment-alias main` lists the IDs you can use"; strings.Join(x.Next, "\n") != want { + t.Errorf("next = %q\nwant %q", x.Next, want) + } +} + +// "Cannot PATCH /…" is a route the server doesn't have: no ID is blamed. +func TestAMissingRouteIsNotAWrongID(t *testing.T) { + cmd := scoped(t, "function", "patch-code", map[string]string{"function-id": "f1", "project-id": "p1"}, "patch-code") + x := ExplainError(cmd, apiError(404, `{"message":"Cannot PATCH /v1/stable/function/f1/code?projectID=p1","error":"Not Found","statusCode":404}`, nil)) + all := joined(x) + if x.Type != "unsupported_command" || !strings.Contains(all, "no PATCH /v1/stable/function/f1/code route") || strings.Contains(all, "Check --") { + t.Errorf("type %q:\n%s", x.Type, all) + } +} + +// A 500 that says what's wrong with the input doesn't say to retry; one +// that says nothing, or something passing, still does. +func TestAServerErrorThatNamesTheInputIsntRetried(t *testing.T) { + cmd := scoped(t, "secret", "create", nil) + cases := map[string]bool{ + `{"message":"Could not resolve 'nope' environment alias. There is no environment or version under that alias."}`: false, + `{"message":"Internal server error"}`: true, + `{"message":"Upstream request timed out"}`: true, + } + for body, retry := range cases { + x := ExplainError(cmd, apiError(500, body, nil)) + if got := strings.Contains(strings.Join(x.Next, "\n"), "Run it again in a minute"); got != retry { + t.Errorf("%s: retry = %v, want %v\n%s", body, got, retry, joined(x)) + } + } +} + +// A 409 or 403 with a reason of its own isn't explained as a taken name or +// missing access, and an MCP tool it names becomes the vf command. +func TestAReasonOfTheServersOwnIsntContradicted(t *testing.T) { + cmd := scoped(t, "agent", "patch-instructions", nil, "patch-instructions", "search-instructions") + x := ExplainError(cmd, apiError(409, `{"message":"oldString was not found in the current text. Nothing was written. Use search_instructions to find the exact wording."}`, nil)) + all := joined(x) + if strings.Contains(all, "already taken") || strings.Contains(all, "different name") { + t.Errorf("409 says a name is taken:\n%s", all) + } + if !strings.Contains(x.Message, "Use `vf agent search-instructions` to find") { + t.Errorf("message = %q", x.Message) + } + + x = ExplainError(scoped(t, "environment", "delete", nil, "delete"), apiError(403, `{"message":"Main environment cannot be deleted."}`, nil)) + if all := joined(x); strings.Contains(all, "isn't allowed") || strings.Contains(all, "vf workspace list") { + t.Errorf("403 blames access:\n%s", all) + } + + // The usual 409 keeps its hint. + x = ExplainError(cmd, apiError(409, `{"message":"A variable with this name already exists"}`, nil)) + if !strings.Contains(joined(x), "different name") { + t.Errorf("usual 409 lost its hint:\n%s", joined(x)) + } +} + +// After `event create -p p1 -e main`, `vf event get --event-id ev1` would +// ask for a project: the tips carry -p and -e. +func TestNextStepsCarryTheScopeFlags(t *testing.T) { + cmd := scoped(t, "event", "create", map[string]string{"project-id": "p1", "environment-alias": "main"}) + var got []string + for _, tip := range nextSteps(cmd, "event", "ev1") { + got = append(got, tip.Command) + } + want := []string{ + "vf event get --event-id ev1 --project-id p1 --environment-alias main", + "vf event list --project-id p1 --environment-alias main", + } + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Errorf("tips = %q\nwant %q", got, want) + } +} diff --git a/internal/output/output.go b/internal/output/output.go index 9db7ae5..ee185f7 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -264,7 +264,7 @@ func Result(cmd *cobra.Command, res interface{}) error { } fmt.Fprint(out, string(data)) case "table": - if err := printTable(out, content); err != nil { + if err := printTableOf(out, content); err != nil { // tableview.go: the rows a response wraps, or why not return err } case "toon": diff --git a/internal/output/peekbody.go b/internal/output/peekbody.go new file mode 100644 index 0000000..e246233 --- /dev/null +++ b/internal/output/peekbody.go @@ -0,0 +1,33 @@ +// This file is not generated by Speakeasy. It lets a command read a response +// before Result prints it. + +package output + +import ( + "bytes" + "encoding/json" + "io" + "net/http" +) + +// PeekJSON decodes a response body the SDK left unread (with -o json or +// --jq) into v, and puts the body back so Result prints it as it would have. +// A read that failed is put back failing the same way, for Result to report. +// It reports whether v was decoded. +func PeekJSON(res *http.Response, v any) bool { + if res == nil || res.Body == nil { + return false + } + raw, err := io.ReadAll(res.Body) + res.Body.Close() + if err != nil { + res.Body = io.NopCloser(io.MultiReader(bytes.NewReader(raw), errReader{err})) + return false + } + res.Body = io.NopCloser(bytes.NewReader(raw)) + return json.Unmarshal(raw, v) == nil +} + +type errReader struct{ err error } + +func (r errReader) Read([]byte) (int, error) { return 0, r.err } diff --git a/internal/output/tableview.go b/internal/output/tableview.go new file mode 100644 index 0000000..94314c9 --- /dev/null +++ b/internal/output/tableview.go @@ -0,0 +1,104 @@ +// This file is not generated by Speakeasy. It has -o table show the rows a +// response holds, and fail when it can't, rather than print part of it. +// +// The generated table printer only knew three shapes: a list, a record and a +// map. But almost every response wraps its data in an object: +// {"environments": [...]}, {"project": {...}}, {"transcripts": [...], +// "returned": 1, "hasMore": false}. So `environment list -o table` and +// `project get -o table` failed with "no displayable fields found", and +// `transcript search -o table` printed `returned` and `hasMore` and exited 0 +// without a single transcript. +// +// printTableOf looks through the wrapper. One list is printed as rows, with +// the response's other plain fields under it. A wrapper around one record is +// printed as that record. A response that holds more than one list fails, and +// says which lists and what to use instead, so no rows are dropped unseen. + +package output + +import ( + "fmt" + "io" + "reflect" + "strings" +) + +// printTableOf prints content as a table, looking through the object a +// response wraps its data in. +func printTableOf(out io.Writer, content any) error { + v := reflect.ValueOf(content) + for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface { + if v.IsNil() { + return printTable(out, content) + } + v = v.Elem() + } + if v.Kind() != reflect.Struct { + return tableError(printTable(out, content)) + } + + var lists, records []int + for i := 0; i < v.NumField(); i++ { + f := v.Type().Field(i) + if !f.IsExported() { + continue + } + switch t := derefType(f.Type); { + case (t.Kind() == reflect.Slice || t.Kind() == reflect.Array) && isRowType(t.Elem()): + lists = append(lists, i) + case t.Kind() == reflect.Struct || t.Kind() == reflect.Map: + records = append(records, i) + } + } + plain := collectTableColumns(v.Type()) + + switch { + case len(lists) > 1: + names := make([]string, len(lists)) + for i, field := range lists { + names[i] = jsonName(v.Type().Field(field)) + } + return fmt.Errorf("-o table shows one list, and this response holds %d: %s. Use -o json or -o yaml to see them all", len(lists), strings.Join(names, ", ")) + case len(lists) == 1: + if err := tableError(printTableRows(out, v.Field(lists[0]))); err != nil { + return err + } + if len(plain) == 0 { + return nil + } + fmt.Fprintln(out) + return printTableSingle(out, v) + case len(records) == 1 && len(plain) == 0: + return printTableOf(out, v.Field(records[0]).Interface()) + } + return tableError(printTable(out, content)) +} + +// isRowType reports whether a list of t prints as rows: a list of objects. +func isRowType(t reflect.Type) bool { + t = derefType(t) + return t.Kind() == reflect.Struct || t.Kind() == reflect.Map || t.Kind() == reflect.Interface +} + +func derefType(t reflect.Type) reflect.Type { + for t.Kind() == reflect.Ptr { + t = t.Elem() + } + return t +} + +func jsonName(f reflect.StructField) string { + if name, _, _ := strings.Cut(f.Tag.Get("json"), ","); name != "" && name != "-" { + return name + } + return f.Name +} + +// tableError says what to use instead when content has nothing a table can +// show. +func tableError(err error) error { + if err == nil { + return nil + } + return fmt.Errorf("-o table can't show this response: %w. Use -o json or -o yaml", err) +} diff --git a/internal/output/tableview_test.go b/internal/output/tableview_test.go new file mode 100644 index 0000000..ee0807b --- /dev/null +++ b/internal/output/tableview_test.go @@ -0,0 +1,67 @@ +// This file is not generated by Speakeasy. It covers tableview.go. + +package output + +import ( + "bytes" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/sdk/models/components" +) + +func table(t *testing.T, content any) (string, error) { + t.Helper() + var out bytes.Buffer + err := printTableOf(&out, content) + return out.String(), err +} + +// {"environments": [...]} prints its environments as rows. +func TestATableShowsTheListAResponseWraps(t *testing.T) { + out, err := table(t, &components.StableEnvironmentListResponse{Environments: []components.StableEnvironment{ + {Alias: "main", Name: "Main"}, {Alias: "staging", Name: "Staging"}, + }}) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(out, "ALIAS") || !strings.Contains(out, "staging") { + t.Errorf("no rows:\n%s", out) + } +} + +// {"transcripts": [...], "returned": 1, "hasMore": false} prints the +// transcripts, and returned and hasMore under them: before, only those two. +func TestATableShowsTheRowsAndThePlainFieldsUnderThem(t *testing.T) { + out, err := table(t, &components.StableTranscriptSearchResponseV2{ + Transcripts: []components.StableTranscriptSummary{{ID: "6b0c-transcript"}}, + Returned: 1, + }) + if err != nil { + t.Fatal(err) + } + rows, footer, ok := strings.Cut(out, "\n\n") + if !ok || !strings.Contains(rows, "6b0c-transcript") || !strings.Contains(footer, "HASMORE") { + t.Errorf("want the rows, a blank line, then returned and hasMore; got:\n%s", out) + } +} + +// {"project": {...}} prints the project. +func TestATableShowsTheRecordAResponseWraps(t *testing.T) { + out, err := table(t, &components.StableProjectResponse{Project: components.StableProject{ID: "6b0c-project", Name: "Coffee"}}) + if err != nil || !strings.Contains(out, "6b0c-project") || !strings.Contains(out, "Coffee") { + t.Errorf("got %v:\n%s", err, out) + } +} + +// A response with two lists fails and names them, rather than print one. +func TestATableOfTwoListsFailsAndSaysWhatToUse(t *testing.T) { + type twoLists struct { + Tests []components.StableEnvironment `json:"tests"` + Runs []components.StableEnvironment `json:"runs"` + } + _, err := table(t, twoLists{}) + if err == nil || !strings.Contains(err.Error(), "tests, runs") || !strings.Contains(err.Error(), "-o json") { + t.Errorf("got %v", err) + } +}