From c6eb2a7e8b5520aa98979a3bc9a5ca6c9c10283c Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:53:23 -0500 Subject: [PATCH 01/31] fix(function): --code and a secret's --value read @file and - Round 5 taught @file to --prompt, --instructions and --content only, so `function create --code @lookup_order.js` saved the words "@lookup_order.js" as the function's code, exit 0, and the function only failed later, in a conversation. `secret set-value --value -` stored a dash, and `--value @secret.txt` the path, and neither help said so. Found by the round-5 sweep's agent-builder, agent-migrator and agent-ci testers. --code (function create and update), the patch commands' --old-string and --new-string (function patch-code, agent patch-prompt and patch-instructions, playbook patch-instructions), a prompt's --system and function check's --cases now take @file for a file's text and - for stdin's, and --body takes @file as it took -. Their help says so, ahead of [required]. A secret's --value and --default-value read them too, which keeps the value off the command line, where ps and a shell's history see it. The line break that ends a file or `echo`'s output is dropped, and an empty value is refused. No error repeats the value: a --value @hunter2 that names no file says "invalid value for --value" without it, and a --body that isn't valid JSON on a command holding a secret no longer prints "You passed: ...". --- internal/cli/agent/patchinstructions.go | 1 + internal/cli/agent/patchprompt.go | 1 + internal/cli/barehelp.go | 2 +- internal/cli/bodyhelp.go | 5 +- internal/cli/errors.go | 6 + internal/cli/function/check.go | 1 + internal/cli/function/create.go | 1 + internal/cli/function/patchcode.go | 1 + internal/cli/function/update.go | 1 + internal/cli/historysecret.go | 30 ++- internal/cli/playbook/patchinstructions.go | 1 + internal/cli/prompt/create.go | 1 + internal/cli/prompt/update.go | 1 + internal/cli/secret/create.go | 1 + internal/cli/secret/setvalue.go | 1 + internal/cli/textflags_test.go | 213 +++++++++++++++++++++ internal/flagutil/stdin.go | 14 +- internal/flagutil/textfile.go | 101 +++++++++- 18 files changed, 364 insertions(+), 18 deletions(-) create mode 100644 internal/cli/textflags_test.go diff --git a/internal/cli/agent/patchinstructions.go b/internal/cli/agent/patchinstructions.go index 61cbfab5..ea29b1cc 100644 --- a/internal/cli/agent/patchinstructions.go +++ b/internal/cli/agent/patchinstructions.go @@ -34,6 +34,7 @@ func initPatchInstructionsCmd(parent *cobra.Command) error { Aliases: []string{"pi"}, } flagutil.RegisterFlags(cmd, patchInstructionsCmdMeta) + flagutil.ReadsText(cmd, "old-string", "new-string") // flagutil/textfile.go: @file and - read the text if err := flagutil.ValidateMeta[operations.StableAgentControllerPatchInstructionsV2Request](patchInstructionsCmdMeta); err != nil { return fmt.Errorf("invalid metadata for patch-instructions: %w", err) } diff --git a/internal/cli/agent/patchprompt.go b/internal/cli/agent/patchprompt.go index 9677c1eb..d88fad01 100644 --- a/internal/cli/agent/patchprompt.go +++ b/internal/cli/agent/patchprompt.go @@ -34,6 +34,7 @@ func initPatchPromptCmd(parent *cobra.Command) error { Aliases: []string{"pp"}, } flagutil.RegisterFlags(cmd, patchPromptCmdMeta) + flagutil.ReadsText(cmd, "old-string", "new-string") // flagutil/textfile.go: @file and - read the text if err := flagutil.ValidateMeta[operations.StableAgentControllerPatchPromptV2Request](patchPromptCmdMeta); err != nil { return fmt.Errorf("invalid metadata for patch-prompt: %w", err) } diff --git a/internal/cli/barehelp.go b/internal/cli/barehelp.go index 7f5a73d9..11b2d062 100644 --- a/internal/cli/barehelp.go +++ b/internal/cli/barehelp.go @@ -65,7 +65,7 @@ func bare(help string) bool { // core is help usage without "[required]", how to pass a list, and how to // give text from a file (flagutil/textfile.go). func core(help string) string { - help = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(help), flagutil.TextHelp)) + help = strings.Join(strings.Fields(strings.NewReplacer(flagutil.TextHelp, "", flagutil.SecretHelp, "").Replace(help)), " ") // ahead of [required], too for _, how := range listHow { help = strings.TrimSpace(strings.TrimSuffix(help, how)) } diff --git a/internal/cli/bodyhelp.go b/internal/cli/bodyhelp.go index 1a307c88..44414552 100644 --- a/internal/cli/bodyhelp.go +++ b/internal/cli/bodyhelp.go @@ -3,7 +3,8 @@ // // 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. +// stdin off and `--body -` reads it (flagutil/stdin.go), and the help says so, +// and that `--body @body.json` reads a file. package cli @@ -14,7 +15,7 @@ import ( ) // 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." +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. --body @file reads it from a file." // describeBodyFlags gives every generated --body flag bodyFlagHelp. func describeBodyFlags(root *cobra.Command) { diff --git a/internal/cli/errors.go b/internal/cli/errors.go index 0435aa6a..1e2bd107 100644 --- a/internal/cli/errors.go +++ b/internal/cli/errors.go @@ -197,6 +197,9 @@ func explainCLIError(cmd *cobra.Command, err error) output.Explanation { if errors.As(err, &body) { x.Type = "invalid_body" x.Why = []string{"The request wasn't sent.", "You passed: " + body.DisplayValue()} + if bodyHoldsSecret(cmd) && !strings.HasPrefix(strings.TrimSpace(body.Value), "@") { // historysecret.go: an error never repeats a secret + x.Why = x.Why[:1] + } takes := "The body" if !body.Stdin && body.Flag != "" { takes = "--" + body.Flag @@ -265,6 +268,9 @@ func explainCLIError(cmd *cobra.Command, err error) output.Explanation { if m := badArgumentRE.FindStringSubmatch(msg); m != nil { x.Type = "invalid_flag_value" x.Title = "invalid value for --" + m[2] + ": \"" + m[1] + "\"" + if secretFlag(cmd, m[2]) { // historysecret.go: an error never repeats a secret + x.Title = "invalid value for --" + m[2] + } x.Why = []string{lastCause(m[3]) + "."} x.Next = []string{help + " shows what each flag takes"} return x diff --git a/internal/cli/function/check.go b/internal/cli/function/check.go index dc6c0739..33a5dc07 100644 --- a/internal/cli/function/check.go +++ b/internal/cli/function/check.go @@ -35,6 +35,7 @@ func initCheckCmd(parent *cobra.Command) error { if err := flagutil.ValidateMeta[operations.StableFunctionControllerCheckRequest](checkCmdMeta); err != nil { return fmt.Errorf("invalid metadata for check: %w", err) } + flagutil.ReadsText(cmd, "cases") // flagutil/textfile.go: @file and - read the cases; after their JSON shape is described cmd.Flags().String("body", "", "Request body as JSON (alternative to individual flags). Can also be provided via stdin.") parent.AddCommand(cmd) return nil diff --git a/internal/cli/function/create.go b/internal/cli/function/create.go index 1c50a4e6..960d5ac8 100644 --- a/internal/cli/function/create.go +++ b/internal/cli/function/create.go @@ -34,6 +34,7 @@ func initCreateCmd(parent *cobra.Command) error { RunE: runCreateCmd, } flagutil.RegisterFlags(cmd, createCmdMeta) + flagutil.ReadsText(cmd, "code") // flagutil/textfile.go: @file and - read the text if err := flagutil.ValidateMeta[operations.StableFunctionControllerCreateRequest](createCmdMeta); err != nil { return fmt.Errorf("invalid metadata for create: %w", err) } diff --git a/internal/cli/function/patchcode.go b/internal/cli/function/patchcode.go index e8cfc517..80faa421 100644 --- a/internal/cli/function/patchcode.go +++ b/internal/cli/function/patchcode.go @@ -35,6 +35,7 @@ func initPatchCodeCmd(parent *cobra.Command) error { Aliases: []string{"pc"}, } flagutil.RegisterFlags(cmd, patchCodeCmdMeta) + flagutil.ReadsText(cmd, "old-string", "new-string") // flagutil/textfile.go: @file and - read the text if err := flagutil.ValidateMeta[operations.StableFunctionControllerPatchCodeRequest](patchCodeCmdMeta); err != nil { return fmt.Errorf("invalid metadata for patch-code: %w", err) } diff --git a/internal/cli/function/update.go b/internal/cli/function/update.go index afe50488..d67c3366 100644 --- a/internal/cli/function/update.go +++ b/internal/cli/function/update.go @@ -36,6 +36,7 @@ func initUpdateCmd(parent *cobra.Command) error { RunE: runUpdateCmd, } flagutil.RegisterFlags(cmd, updateCmdMeta) + flagutil.ReadsText(cmd, "code") // flagutil/textfile.go: @file and - read the text if err := flagutil.ValidateMeta[operations.StableFunctionControllerUpdateRequest](updateCmdMeta); err != nil { return fmt.Errorf("invalid metadata for update: %w", err) } diff --git a/internal/cli/historysecret.go b/internal/cli/historysecret.go index fcbc04cf..54d541ae 100644 --- a/internal/cli/historysecret.go +++ b/internal/cli/historysecret.go @@ -1,5 +1,6 @@ // This file is not generated by Speakeasy. It keeps a secret's value out of -// the home prompt's history. +// the home prompt's history, and out of the error for a value vf couldn't +// use. // // `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 @@ -37,13 +38,7 @@ func forHistory(root *cobra.Command, line string) string { 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) - }) + holdsSecret := bodyHoldsSecret(cmd) kept := make([]string, 0, len(args)) dropped := false for i := 0; i < len(args); i++ { @@ -86,6 +81,25 @@ func lookupFlag(cmd *cobra.Command, word string) (*pflag.Flag, bool) { return cmd.Flags().ShorthandLookup(name), hasValue } +// secretFlag is whether cmd's flag name holds a secret, so that no error +// repeats its value: `secret set-value --value @hunter2`, with no file +// named hunter2, fails without saying "@hunter2" (flagutil/textfile.go). +func secretFlag(cmd *cobra.Command, name string) bool { + f := cmd.Flags().Lookup(name) + return f != nil && interactive.IsSecretFlag(f.Name, f.Usage) +} + +// bodyHoldsSecret is whether cmd's whole body may carry a secret, as on a +// command with a secret flag of its own: `secret set-value --body +// '{"value":"hunter2"}'`. Its own: every command inherits vf's --token. +func bodyHoldsSecret(cmd *cobra.Command) bool { + holds := false + cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + holds = holds || interactive.IsSecretFlag(f.Name, f.Usage) + }) + return holds +} + // quoteArg writes a as one word the prompt's SplitArgs reads back as a. func quoteArg(a string) string { switch { diff --git a/internal/cli/playbook/patchinstructions.go b/internal/cli/playbook/patchinstructions.go index e9772ec1..a75240e8 100644 --- a/internal/cli/playbook/patchinstructions.go +++ b/internal/cli/playbook/patchinstructions.go @@ -35,6 +35,7 @@ func initPatchInstructionsCmd(parent *cobra.Command) error { Aliases: []string{"pi"}, } flagutil.RegisterFlags(cmd, patchInstructionsCmdMeta) + flagutil.ReadsText(cmd, "old-string", "new-string") // flagutil/textfile.go: @file and - read the text if err := flagutil.ValidateMeta[operations.StablePlaybookControllerPatchInstructionsV2Request](patchInstructionsCmdMeta); err != nil { return fmt.Errorf("invalid metadata for patch-instructions: %w", err) } diff --git a/internal/cli/prompt/create.go b/internal/cli/prompt/create.go index 2f26c6f1..3c90cd62 100644 --- a/internal/cli/prompt/create.go +++ b/internal/cli/prompt/create.go @@ -33,6 +33,7 @@ func initCreateCmd(parent *cobra.Command) error { RunE: runCreateCmd, } flagutil.RegisterFlags(cmd, createCmdMeta) + flagutil.ReadsText(cmd, "system") // flagutil/textfile.go: @file and - read the text if err := flagutil.ValidateMeta[operations.StablePromptControllerCreateRequest](createCmdMeta); err != nil { return fmt.Errorf("invalid metadata for create: %w", err) } diff --git a/internal/cli/prompt/update.go b/internal/cli/prompt/update.go index 624ea17b..14f73735 100644 --- a/internal/cli/prompt/update.go +++ b/internal/cli/prompt/update.go @@ -34,6 +34,7 @@ func initUpdateCmd(parent *cobra.Command) error { RunE: runUpdateCmd, } flagutil.RegisterFlags(cmd, updateCmdMeta) + flagutil.ReadsText(cmd, "system") // flagutil/textfile.go: @file and - read the text if err := flagutil.ValidateMeta[operations.StablePromptControllerUpdateRequest](updateCmdMeta); err != nil { return fmt.Errorf("invalid metadata for update: %w", err) } diff --git a/internal/cli/secret/create.go b/internal/cli/secret/create.go index 1d5a9511..02466d4d 100644 --- a/internal/cli/secret/create.go +++ b/internal/cli/secret/create.go @@ -32,6 +32,7 @@ func initCreateCmd(parent *cobra.Command) error { RunE: runCreateCmd, } flagutil.RegisterFlags(cmd, createCmdMeta) + flagutil.ReadsSecret(cmd, "default-value") // flagutil/textfile.go: @file and - read the value, off the command line if err := flagutil.ValidateMeta[operations.StableSecretControllerCreateV2Request](createCmdMeta); err != nil { return fmt.Errorf("invalid metadata for create: %w", err) } diff --git a/internal/cli/secret/setvalue.go b/internal/cli/secret/setvalue.go index 198a3307..54bb0cec 100644 --- a/internal/cli/secret/setvalue.go +++ b/internal/cli/secret/setvalue.go @@ -34,6 +34,7 @@ func initSetValueCmd(parent *cobra.Command) error { Aliases: []string{"sv"}, } flagutil.RegisterFlags(cmd, setValueCmdMeta) + flagutil.ReadsSecret(cmd, "value") // flagutil/textfile.go: @file and - read the value, off the command line if err := flagutil.ValidateMeta[operations.StableSecretControllerSetValueRequest](setValueCmdMeta); err != nil { return fmt.Errorf("invalid metadata for set-value: %w", err) } diff --git a/internal/cli/textflags_test.go b/internal/cli/textflags_test.go new file mode 100644 index 00000000..83fcca13 --- /dev/null +++ b/internal/cli/textflags_test.go @@ -0,0 +1,213 @@ +// This file is not generated by Speakeasy. It covers the flags that read +// text with flagutil/textfile.go beyond a prompt's: a function's code, the +// patch commands' strings, a prompt's system text, function check's cases, +// a whole --body, and a secret's value, which no error repeats. + +package cli + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// withFiles makes a folder holding files the working directory. +func withFiles(t *testing.T, files map[string]string) { + t.Helper() + dir := t.TempDir() + for name, text := range files { + if err := os.WriteFile(filepath.Join(dir, name), []byte(text), 0o600); err != nil { + t.Fatal(err) + } + } + t.Chdir(dir) +} + +// runLineIn runs vf args with stdin and returns everything it wrote and the +// error it ended with, reported as main reports it. +func runLineIn(t *testing.T, stdin string, args ...string) (string, error) { + t.Helper() + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var out bytes.Buffer + root.SetOut(&out) + root.SetErr(&out) + root.SetIn(strings.NewReader(stdin)) + root.SetArgs(args) + cmd, err := root.ExecuteC() + if err != nil { + err = renderError(cmd, err) + } + return out.String(), err +} + +const lookupOrderJS = "export default async function main(args) {\n return { next: { path: \"success\" } };\n}\n" + +// round-5 agent-builder:F1, agent-migrator:F1: `function create --code +// @lookup_order.js` saved "@lookup_order.js" as the code, exit 0. The code, +// the patch commands' strings, a prompt's system text, function check's +// cases and a whole --body now come from @file or -. +func TestCodeAndOtherLongTextComeFromAFileOrStdin(t *testing.T) { + withFiles(t, map[string]string{ + "lookup_order.js": lookupOrderJS, + "old.txt": "Be brief.\n", + "system.md": "You sort tickets.\n", + "cases.json": `[{"name":"shipped","inputs":{"order":"1"}}]`, + "body.json": `{"name":"from_body","code":"x"}`, + }) + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + ids := []string{"-p", "p1", "-e", "main"} + cases := []struct { + args []string + stdin string + want []string + }{ + {[]string{"function", "create", "--name", "lookup_order", "--code", "@lookup_order.js"}, "", + []string{`"code": "export default async function main(args) {\n return { next: { path: \"success\" } };\n}\n"`}}, + {[]string{"function", "update", "-f", "f1", "--code", "-"}, lookupOrderJS, + []string{`"code": "export default async function main(args) {\n`}}, + {[]string{"function", "patch-code", "-f", "f1", "--old-string", "@old.txt", "--new-string", "-"}, "Be thorough.", + []string{`"oldString": "Be brief.\n"`, `"newString": "Be thorough."`}}, + {[]string{"agent", "patch-prompt", "--old-string", "@old.txt", "--new-string", "Be kind."}, "", + []string{`"oldString": "Be brief.\n"`}}, + {[]string{"agent", "patch-instructions", "--old-string", "@old.txt", "--new-string", "Be kind."}, "", + []string{`"oldString": "Be brief.\n"`}}, + {[]string{"playbook", "patch-instructions", "--playbook-id", "pb1", "--old-string", "@old.txt", "--new-string", "Be kind."}, "", + []string{`"oldString": "Be brief.\n"`}}, + {[]string{"prompt", "create", "--system", "@system.md"}, "", []string{`"system": "You sort tickets.\n"`}}, + {[]string{"prompt", "update", "--prompt-id", "pr1", "--system", "-"}, "You route calls.", []string{`"system": "You route calls."`}}, + {[]string{"function", "check", "-f", "f1", "--cases", "@cases.json"}, "", []string{`"name": "shipped"`}}, + {[]string{"function", "create", "--body", "@body.json"}, "", []string{`"name": "from_body"`}}, + } + for _, c := range cases { + args := append(append(append([]string{}, c.args...), ids...), "--dry-run", "--agent-mode=false", "--no-interactive") + if c.args[0] == "function" && c.args[1] == "update" { + args = append(append([]string{}, c.args...), "--project-id", "p1", "-e", "main", "--dry-run", "--agent-mode=false", "--no-interactive") + } + out, err := runLineIn(t, c.stdin, args...) + if err != nil { + t.Errorf("%v: %v\n%s", c.args, err, out) + continue + } + for _, want := range c.want { + if !strings.Contains(out, want) { + t.Errorf("%v: want %s in:\n%s", c.args, want, out) + } + } + } +} + +// Help says which flags read a file, ahead of [required]. +func TestCodeHelpSaysItReadsAFile(t *testing.T) { + root := testRoot(t) + for _, c := range []struct{ path, flag string }{ + {"function create", "code"}, {"function update", "code"}, {"function patch-code", "new-string"}, + {"prompt create", "system"}, {"prompt update", "system"}, {"function check", "cases"}, + {"secret set-value", "value"}, {"secret create", "default-value"}, + } { + f := find(t, root, strings.Fields(c.path)...).Flags().Lookup(c.flag) + if !strings.Contains(f.Usage, "@file reads the") || strings.Contains(f.Usage, "[required] @file") { + t.Errorf("%s --%s: %q", c.path, c.flag, f.Usage) + } + } + if got := find(t, root, "function", "check").Flags().Lookup("cases").Usage; !strings.HasPrefix(got, "JSON: [{ name: string") { + t.Errorf("--cases should keep its JSON shape: %q", got) + } +} + +// secretServer answers every request with {} and keeps each body it got. +func secretServer(t *testing.T) (url string, bodies func() []string) { + t.Helper() + var mu sync.Mutex + var got []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + data, _ := io.ReadAll(r.Body) + mu.Lock() + got = append(got, string(data)) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + if r.Method == http.MethodPost { + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"secret":{"id":"s1","name":"KEY","visibility":"masked","createdAt":"2026-01-01T00:00:00Z","updatedAt":"2026-01-01T00:00:00Z"}}`)) + return + } + _, _ = w.Write([]byte(`{"message":"Secret value set."}`)) + })) + t.Cleanup(srv.Close) + return srv.URL, func() []string { mu.Lock(); defer mu.Unlock(); return append([]string(nil), got...) } +} + +// round-5 agent-ci:F7: `secret set-value --value -` and `--value @file` +// stored the dash and the path. Both read the value now, without the line +// break `echo` and an editor end it with, so it stays off the command line. +func TestASecretValueComesFromAFileOrStdin(t *testing.T) { + withFiles(t, map[string]string{"secret.txt": "sk-file\n"}) + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + cases := []struct { + args []string + stdin string + key string + want string + }{ + {[]string{"secret", "set-value", "-s", "s1", "--value", "-"}, "sk-piped\n", "value", "sk-piped"}, + {[]string{"secret", "set-value", "-s", "s1", "--value", "@secret.txt"}, "", "value", "sk-file"}, + {[]string{"secret", "set-value", "-s", "s1", "--value", "@@sk-at"}, "", "value", "@sk-at"}, + {[]string{"secret", "create", "--name", "KEY", "--default-value", "@secret.txt"}, "", "defaultValue", "sk-file"}, + } + for _, c := range cases { + url, bodies := secretServer(t) + out, err := runLineIn(t, c.stdin, append(c.args, "-p", "p1", "--server-url", url, "--agent-mode=false", "--no-interactive")...) + if err != nil { + t.Errorf("%v: %v\n%s", c.args, err, out) + continue + } + sent := bodies() + var body map[string]any + if len(sent) != 1 || json.Unmarshal([]byte(sent[0]), &body) != nil || body[c.key] != c.want { + t.Errorf("%v: sent %v, want %s %q", c.args, sent, c.key, c.want) + } + } +} + +// A value that starts with @ may be the secret itself, so no error says it: +// not when no file has that name, nor when a whole --body is bad JSON. +func TestNoErrorRepeatsASecret(t *testing.T) { + withFiles(t, map[string]string{"blank.txt": "\n"}) + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + for _, agent := range []string{"--agent-mode=false", "--agent-mode=true"} { + for _, args := range [][]string{ + {"secret", "set-value", "-s", "s1", "--value", "@hunter2"}, + {"secret", "create", "--name", "KEY", "--default-value", "@hunter2"}, + {"secret", "set-value", "-s", "s1", "--body", `{"value":"hunter2"`}, + {"secret", "set-value", "-s", "s1", "--value", "@blank.txt"}, + } { + url, bodies := secretServer(t) + out, err := runLineIn(t, "", append(args, "-p", "p1", "--server-url", url, agent, "--no-interactive")...) + if code := output.ExitCode(err); code != output.ExitUsage { + t.Errorf("%s %v: exit %d, want %d\n%s", agent, args, code, output.ExitUsage, out) + } + if strings.Contains(out, "hunter2") { + t.Errorf("%s %v: the error repeats the secret:\n%s", agent, args, out) + } + if len(bodies()) != 0 { + t.Errorf("%s %v: nothing should be sent", agent, args) + } + } + } +} diff --git a/internal/flagutil/stdin.go b/internal/flagutil/stdin.go index 9195da0c..f3f324b4 100644 --- a/internal/flagutil/stdin.go +++ b/internal/flagutil/stdin.go @@ -267,9 +267,21 @@ func StdinLeftUnread(cmd *cobra.Command, flag string) (bodyFlag string, ok bool) return "", false } -// bodyFlagValue is the whole-body flag's value; `--body -` reads it from stdin. +// bodyFlagValue is the whole-body flag's value; `--body -` reads it from +// stdin, and `--body @body.json` from the file, as --code and --prompt read +// theirs (textfile.go). JSON never starts with @, so nothing else is meant. func bodyFlagValue(cmd *cobra.Command, name string) (string, error) { v, _ := GetStringFlag(cmd, name) + if path, ok := strings.CutPrefix(strings.TrimSpace(v), "@"); ok && path != "" { + text, err := ReadTextFile(path, "the body") + if err == nil && strings.TrimSpace(text) == "" { + err = fmt.Errorf("%s is empty", path) + } + if err != nil { + return "", &BodyError{Flag: name, Value: v, Problem: err.Error(), Cause: err} + } + return strings.TrimSpace(text), nil + } if strings.TrimSpace(v) != "-" { return v, nil } diff --git a/internal/flagutil/textfile.go b/internal/flagutil/textfile.go index e2bfdf07..3dbfa548 100644 --- a/internal/flagutil/textfile.go +++ b/internal/flagutil/textfile.go @@ -11,12 +11,23 @@ // - for stdin's, as curl and gh do. The value is read when the flag is set, // on the command line or from a form, so everything after it sees the text. // @@ starts text that itself starts with @. +// +// Round 5 opted in only --prompt, --instructions and --content, so +// `function create --code @lookup_order.js` saved the words +// "@lookup_order.js" as the function's code, exit 0, and `secret set-value +// --value -` stored a dash. Now --code, the patch commands' --old-string and +// --new-string, a prompt's --system and function check's --cases take them +// too. A secret's --value and --default-value take them through ReadsSecret: +// reading the value keeps it off the command line, where ps and a shell's +// history see it, and no error repeats what was typed, which may be the +// secret itself. package flagutil import ( "errors" "fmt" + "io/fs" "os" "path/filepath" "strings" @@ -29,15 +40,23 @@ import ( // undescribed says only this until internal/cli/barehelp.go describes it. const TextHelp = "@file reads the text from a file, and - from stdin." +// SecretHelp is what a flag that holds a secret says about reading it. +const SecretHelp = "@file reads the value from a file, and - from stdin, which keeps it off the command line." + // textValue is a flag's value that reads @path and - before it is set. type textValue struct { pflag.Value - cmd *cobra.Command - name string + cmd *cobra.Command + name string + secret bool // a secret: see ReadsSecret } func (v *textValue) Set(s string) error { - text, err := readText(v.cmd, v.name, s) + read := readText + if v.secret { + read = readSecret + } + text, err := read(v.cmd, v.name, s) if err != nil { return err } @@ -47,6 +66,18 @@ func (v *textValue) Set(s string) error { // ReadsText makes each named flag of cmd take @path and -, and says so in its // help. A flag cmd doesn't have is left out. func ReadsText(cmd *cobra.Command, names ...string) { + readsFrom(cmd, false, TextHelp, names) +} + +// ReadsSecret is ReadsText for a flag that holds a secret. A file's or +// stdin's text loses the line break that ends it, as `echo $KEY |` and an +// editor add one, an empty one is refused, and its errors never repeat the +// value given. +func ReadsSecret(cmd *cobra.Command, names ...string) { + readsFrom(cmd, true, SecretHelp, names) +} + +func readsFrom(cmd *cobra.Command, secret bool, help string, names []string) { for _, name := range names { f := cmd.Flags().Lookup(name) if f == nil { @@ -55,8 +86,13 @@ func ReadsText(cmd *cobra.Command, names ...string) { if _, done := f.Value.(*textValue); done { continue } - f.Value = &textValue{Value: f.Value, cmd: cmd, name: name} - f.Usage = strings.TrimSpace(strings.TrimSpace(f.Usage) + " " + TextHelp) + f.Value = &textValue{Value: f.Value, cmd: cmd, name: name, secret: secret} + // Ahead of "[required]", which help shows last. + text, required := strings.CutSuffix(strings.TrimSpace(f.Usage), "[required]") + f.Usage = strings.TrimSpace(strings.TrimSpace(text) + " " + help) + if required { + f.Usage += " [required]" + } } } @@ -96,6 +132,46 @@ func readText(cmd *cobra.Command, name, value string) (string, error) { return value, nil } +// readSecret is readText for a secret: the file's or stdin's text without +// its last line break, and errors that say what was wrong without the value, +// since a value that starts with @ may be the secret and not a path. +func readSecret(cmd *cobra.Command, name, value string) (string, error) { + var text string + switch { + case value == "-": + data, err := textFromStdin(cmd, name) + if err != nil { + return "", err + } + text = data + case strings.HasPrefix(value, "@@"): + return value[1:], nil + case strings.HasPrefix(value, "@") && len(value) > 1: + data, err := ReadTextFile(value[1:], "--"+name) + var pathErr *fs.PathError + switch { + case errors.Is(err, os.ErrNotExist): + return "", fmt.Errorf("--%s starts with @, so it reads a file, and there is no such file; to give a value that starts with @, write @@", name) + case errors.As(err, &pathErr): + return "", fmt.Errorf("can't read the file named for --%s: %w", name, pathErr.Err) + case err != nil: + return "", fmt.Errorf("can't read the file named for --%s", name) + } + text = data + default: + return value, nil + } + text = strings.TrimRight(text, "\r\n") + if text == "" { + from := "the file named for --" + name + if value == "-" { + from = "stdin, read for --" + name + " -," + } + return "", fmt.Errorf("%s holds no value, only a line break or nothing; a secret's value can't be empty", from) + } + return text, nil +} + // ReadTextFile reads the file at path, ~/ for the home directory, for the // flag named by what. Its error says which file and why. func ReadTextFile(path, what string) (string, error) { @@ -126,10 +202,23 @@ type noFile string func (e noFile) Error() string { return string(e) } func (e noFile) Is(target error) bool { return target == os.ErrNotExist } +// exampleFiles name a file each flag might read, for its errors. Any other +// flag reads prompt.md. +var exampleFiles = map[string]string{ + "code": "function.js", + "cases": "cases.json", + "value": "secret.txt", + "default-value": "secret.txt", +} + // textFromStdin reads the text piped in for --name -. func textFromStdin(cmd *cobra.Command, name string) (string, error) { if !HasStdinInput(cmd) { - return "", fmt.Errorf("--%[1]s - reads the text from stdin, and nothing is piped in; pipe it in (cat prompt.md | vf … --%[1]s -), or read a file with --%[1]s @prompt.md", name) + file := exampleFiles[name] + if file == "" { + file = "prompt.md" + } + return "", fmt.Errorf("--%[1]s - reads the text from stdin, and nothing is piped in; pipe it in (cat %[2]s | vf … --%[1]s -), or read a file with --%[1]s @%[2]s", name, file) } data, err := readStdinBounded(cmd.InOrStdin(), 0) if err != nil { From 17a6d7b79e50894177a5055f9f768cc89ee7c546 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:57:10 -0500 Subject: [PATCH 02/31] fix(function): function check exits 6 when a case didn't pass MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `function check` printed its cases and exited 0 whatever they were. The round-5 sweep's agent-builder tester gave a case an expectOutputs it didn't meet and got `matched: false`, "0 failed; 2 of 3 matched what you expected." and EXIT=0, so a CI step or a coding agent that gates on the exit code passed a broken function. The API's "0 failed" counts only the cases that threw. Once the result is printed, a case that didn't run, threw, or didn't match its expectPath or expectOutputs now makes check exit 6, as `test run wait` does, with a line that names each such case and why: Error: 1 of 3 cases didn't pass - "deliberately wrong" didn't match what you expected: order_status was "processing", expected "shipped" A check that refused to run (checked: false) exits 6 with its reason, since nothing was verified. In agent mode and with -o json the error is the usual JSON, error_type function_check_failed. When every case passed, a person at a terminal gets a ✓ line. `vf --help` and the README list function check under exit code 6. --- README.md | 2 +- internal/cli/function/check.go | 3 +- internal/cli/function/checkexit.go | 108 +++++++++++++++++++++++++ internal/cli/functioncheck_test.go | 124 +++++++++++++++++++++++++++++ internal/output/exitcode.go | 8 +- 5 files changed, 240 insertions(+), 5 deletions(-) create mode 100644 internal/cli/function/checkexit.go create mode 100644 internal/cli/functioncheck_test.go diff --git a/README.md b/README.md index 37e5eb3a..388982e1 100644 --- a/README.md +++ b/README.md @@ -896,7 +896,7 @@ Each kind of failure has its own exit code, so a script can tell them apart with | `3` | Authentication: not signed in, no token, HTTP 401, an expired session | | `4` | Not found: HTTP 404 | | `5` | Timed out: `--timeout`, or a wait's `--max-wait` ran out with runs still going | -| `6` | A test run didn't pass: `test run wait`, `test run wait-suite`, `test run create-suite --wait` | +| `6` | A test run didn't pass: `test run wait`, `test run wait-suite`, `test run create-suite --wait`; or a case of `function check` didn't | `vf --help` lists them too. diff --git a/internal/cli/function/check.go b/internal/cli/function/check.go index 33a5dc07..3cec18c4 100644 --- a/internal/cli/function/check.go +++ b/internal/cli/function/check.go @@ -79,8 +79,9 @@ func runCheckCmd(cmd *cobra.Command, args []string) error { return output.Error(cmd, err) } + verdict := checkVerdict(cmd, res) // checkexit.go: exit 6 unless every case ran and passed if err := output.Result(cmd, res); err != nil { return err } - return nil + return verdict() } diff --git a/internal/cli/function/checkexit.go b/internal/cli/function/checkexit.go new file mode 100644 index 00000000..dc705dfe --- /dev/null +++ b/internal/cli/function/checkexit.go @@ -0,0 +1,108 @@ +// This file is not generated by Speakeasy. It makes `vf function check` +// exit 6 unless every case ran and did what it was expected to. +// +// check printed its cases and exited 0 whatever they were. The round-5 +// agent-builder tester gave a case an expectOutputs it didn't meet and got +// `matched: false`, "0 failed; 2 of 3 matched what you expected." and +// EXIT=0, so a CI step or a coding agent gating on the exit code passed a +// broken function. "0 failed" counts only the cases that threw. +// +// Now, once the result is printed, a case that wasn't run, threw, or didn't +// match its expectPath or expectOutputs makes check exit 6, "a test didn't +// pass" (internal/output/exitcode.go), as `test run wait` does, with a ✗ +// line that names each such case and why. So does a check that refused to +// run at all (checked: false), since nothing was verified. When every case +// passed, a person at a terminal gets a ✓ line. -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 function + +import ( + "errors" + "fmt" + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk/models/operations" +) + +// checkAnswer is what check's verdict reads of its answer. +type checkAnswer struct { + Checked bool `json:"checked"` + Reason string `json:"reason"` + Cases []struct { + Name string `json:"name"` + Ran bool `json:"ran"` + Success bool `json:"success"` + Error *string `json:"error"` + Matched *bool `json:"matched"` + Mismatches []string `json:"mismatches"` + } `json:"cases"` +} + +func noVerdict() error { return nil } + +// checkVerdict reads what `vf function check` got back, before it is +// printed, and returns how the command exits once it has been: nil only +// when every case ran and passed. +func checkVerdict(cmd *cobra.Command, res *operations.StableFunctionControllerCheckResponse) func() error { + if res == nil || client.IsDryRun(cmd) { + return noVerdict + } + var a checkAnswer + if !output.PeekJSON(res.HTTPMeta.Response, &a) { + return noVerdict + } + return func() error { return checkOutcome(cmd, a) } +} + +// checkOutcome is nil only when every case ran and passed. +func checkOutcome(cmd *cobra.Command, a checkAnswer) error { + if !a.Checked { + why := []string{"No case ran, so nothing was checked."} + if a.Reason != "" { + why = append([]string{a.Reason}, why...) + } + return failedCheck(cmd, "The check didn't run", why) + } + var why []string + expected := false + for _, c := range a.Cases { + expected = expected || c.Matched != nil + switch { + case !c.Ran: + why = append(why, fmt.Sprintf("%q didn't run", c.Name)) + case !c.Success: + reason := "threw" + if c.Error != nil && *c.Error != "" { + reason = "failed: " + *c.Error + } + why = append(why, fmt.Sprintf("%q %s", c.Name, reason)) + case c.Matched != nil && !*c.Matched: + line := fmt.Sprintf("%q didn't match what you expected", c.Name) + if len(c.Mismatches) > 0 { + line += ": " + strings.Join(c.Mismatches, "; ") + } + why = append(why, line) + } + } + if len(why) > 0 { + return failedCheck(cmd, fmt.Sprintf("%d of %d cases didn't pass", len(why), len(a.Cases)), why) + } + done := fmt.Sprintf("%d of %d cases ran", len(a.Cases), len(a.Cases)) + if expected { + done += " and did what you expected" + } + output.Done(cmd, done) + return nil +} + +// failedCheck reports a check that didn't pass, which exits 6. +func failedCheck(cmd *cobra.Command, title string, why []string) error { + err := output.WithExitCode(errors.New(title), output.ExitNotPassed) + return output.Report(cmd, output.Explanation{Type: "function_check_failed", Title: title, Why: why}, err) +} diff --git a/internal/cli/functioncheck_test.go b/internal/cli/functioncheck_test.go new file mode 100644 index 00000000..bbc8172b --- /dev/null +++ b/internal/cli/functioncheck_test.go @@ -0,0 +1,124 @@ +// This file is not generated by Speakeasy. It covers +// function/checkexit.go: `vf function check` exits 6 unless every case ran +// and passed. + +package cli + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// checkServer answers function check with answer. +func checkServer(t *testing.T, answer string) string { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.HasSuffix(r.URL.Path, "/check") { + t.Errorf("unexpected request %s %s", r.Method, r.URL) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(answer)) + })) + t.Cleanup(srv.Close) + return srv.URL +} + +// checkCase is one case of check's answer. +func checkCase(name string, ran, success bool, matched string, extra string) string { + c := `{"name":"` + name + `","ran":` + boolText(ran) + `,"success":` + boolText(success) + `,"path":"success","outputs":{},"error":null` + if matched != "" { + c += `,"matched":` + matched + } + return c + extra + `}` +} + +func boolText(b bool) string { + if b { + return "true" + } + return "false" +} + +func checkAnswer(cases ...string) string { + return `{"checked":true,"functionID":"f1","summary":"…","cases":[` + strings.Join(cases, ",") + `]}` +} + +// round-5 agent-builder:F3: a case that didn't match its expectOutputs got +// "0 failed; 2 of 3 matched what you expected." and EXIT=0. A case that +// didn't match, didn't run or threw now exits 6 and is named; a check +// that refused to run exits 6 with its reason. +func TestAFunctionCheckThatDidntPassExits6(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + ok := checkCase("shipped", true, true, "true", "") + cases := []struct { + name string + answer string + want []string + }{ + {"a mismatch", checkAnswer(ok, ok, checkCase("deliberately wrong", true, true, "false", `,"mismatches":["order_status was \"processing\", expected \"shipped\""]`)), + []string{"1 of 3 cases didn't pass", `"deliberately wrong" didn't match what you expected: order_status was "processing", expected "shipped"`}}, + {"a case that didn't run", checkAnswer(ok, checkCase("late", false, false, "", "")), + []string{"1 of 2 cases didn't pass", `"late" didn't run`}}, + {"a case that threw", checkAnswer(checkCase("boom", true, false, "", "")), + []string{"1 of 1 cases didn't pass", `"boom" threw`}}, + {"a refused check", `{"checked":false,"reason":"The code mentions fetch."}`, + []string{"The check didn't run", "The code mentions fetch."}}, + } + for _, c := range cases { + for _, mode := range [][]string{{"--agent-mode=false"}, {"--agent-mode=true"}, {"--agent-mode=false", "-o", "json"}} { + url := checkServer(t, c.answer) + out, err := runLineIn(t, "", append([]string{"function", "check", "-p", "p1", "-e", "main", "-f", "f1", + "--cases", `[{"name":"x","inputs":{}}]`, "--server-url", url, "--no-interactive"}, mode...)...) + if code := output.ExitCode(err); code != output.ExitNotPassed { + t.Errorf("%s %v: exit %d, want %d\n%s", c.name, mode, code, output.ExitNotPassed, out) + } + said := out + if mode[0] == "--agent-mode=true" || len(mode) > 1 { + i := strings.LastIndex(out, "{\n") + var envelope map[string]any + if i < 0 || json.Unmarshal([]byte(out[i:]), &envelope) != nil { + t.Fatalf("%s %v: want the JSON envelope last:\n%s", c.name, mode, out) + } + if envelope["error_type"] != "function_check_failed" || envelope["exit_code"] != float64(6) { + t.Errorf("%s %v: envelope %v", c.name, mode, envelope) + } + said = envelope["error"].(string) + "\n" + envelope["explanation"].(string) + } + for _, want := range c.want { + if !strings.Contains(said, want) { + t.Errorf("%s %v: want %s in:\n%s", c.name, mode, want, said) + } + } + } + } +} + +// Every case that ran and matched, or ran with nothing expected, exits 0. +func TestAFunctionCheckThatPassedExits0(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + for _, answer := range []string{ + checkAnswer(checkCase("shipped", true, true, "true", ""), checkCase("plain", true, true, "", "")), + checkAnswer(checkCase("plain", true, true, "", "")), + } { + url := checkServer(t, answer) + out, err := runLineIn(t, "", "function", "check", "-p", "p1", "-e", "main", "-f", "f1", + "--cases", `[{"name":"x","inputs":{}}]`, "--server-url", url, "--no-interactive", "--agent-mode=false") + if err != nil { + t.Errorf("%s: %v\n%s", answer, err, out) + } + } +} + +// vf --help lists function check under exit code 6. +func TestExitCode6NamesFunctionCheck(t *testing.T) { + if !strings.Contains(output.ExitCodesHelp, "function check") || output.ExitCodeFor("function_check_failed", 0) != output.ExitNotPassed { + t.Errorf("exit code 6 should name function check:\n%s", output.ExitCodesHelp) + } +} diff --git a/internal/output/exitcode.go b/internal/output/exitcode.go index 44ba2551..b1b86016 100644 --- a/internal/output/exitcode.go +++ b/internal/output/exitcode.go @@ -15,7 +15,8 @@ // 3 authentication: not signed in, no token, a 401, an expired session // 4 not found: a 404 // 5 timed out: --timeout, or a wait's --max-wait ran out with runs still going -// 6 a test run didn't pass: test run wait, wait-suite, create-suite --wait +// 6 a test run didn't pass: test run wait, wait-suite, create-suite --wait; +// or a function check case didn't (cli/function/checkexit.go) package output @@ -43,7 +44,8 @@ var ExitCodesHelp = strings.Join([]string{ " 3 Authentication: not signed in, no token, HTTP 401, an expired session", " 4 Not found: HTTP 404", " 5 Timed out: --timeout, or a wait's --max-wait ran out with runs still going", - " 6 A test run didn't pass: test run wait, wait-suite, create-suite --wait", + " 6 A test run didn't pass: test run wait, wait-suite, create-suite --wait;", + " or a function check case didn't", }, "\n") // ExitCodeFor is the exit code for an error of errorType, the error_type the @@ -62,7 +64,7 @@ func ExitCodeFor(errorType string, status int) int { return ExitNotFound case "timeout", "test_runs_unfinished", "test_suite_unfinished": return ExitTimeout - case "test_runs_failed", "test_suite_failed": + case "test_runs_failed", "test_suite_failed", "function_check_failed": return ExitNotPassed } switch status { From 1126bbe67dc79501ead66dbc1e1fbd30d4f6c7e0 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:01:00 -0500 Subject: [PATCH 03/31] fix(cli): a flag given two different values is refused, not cut to the last MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit pflag keeps the last value of a flag that takes one and drops the rest without a word. The round-5 sweep's human-kb tester ran `document create-text --file faq/refunds.md --file faq/accounts.md --wait` at the home prompt and got "✓ Added accounts.md"; refunds.md was never added, and only a later `document list` showed it. The same silence picks the wrong project for `-p A … -p B` or the wrong environment for `-e main … -e staging`. Before anything is asked or sent, vf and the home prompt now refuse such a flag with exit 2, naming it and both values: Error: --file was given twice, as faq/refunds.md and as faq/accounts.md - --file takes one value, and vf would have used only the last. Nothing was sent. Next: 'vf document create-text' takes one file: run it once for each file This holds for every flag that takes one value, not only --file: none can use two, and which one wins shouldn't depend on the order of words. The same value twice still runs, as do flags that collect values (--header, list flags such as --run-ids). A secret's values, and a --body that may hold one, are not repeated. Forms and pickers set flags after the check and are unaffected. --- internal/cli/home.go | 4 + internal/cli/repeatedflags.go | 142 +++++++++++++++++++++++++++++ internal/cli/repeatedflags_test.go | 129 ++++++++++++++++++++++++++ internal/cli/root.go | 3 + 4 files changed, 278 insertions(+) create mode 100644 internal/cli/repeatedflags.go create mode 100644 internal/cli/repeatedflags_test.go diff --git a/internal/cli/home.go b/internal/cli/home.go index 3efcf0db..d89cdfe9 100644 --- a/internal/cli/home.go +++ b/internal/cli/home.go @@ -173,6 +173,10 @@ func runLine(ctx context.Context, u *ui.UI, args []string) { _ = renderError(cmd, err) return } + if cmd, err := repeatedFlag(root, args); err != nil { // repeatedflags.go: --file a --file b fails rather than dropping a + _ = renderError(cmd, err) + return + } cmd, err := root.ExecuteContextC(ctx) switch { case err == nil: diff --git a/internal/cli/repeatedflags.go b/internal/cli/repeatedflags.go new file mode 100644 index 00000000..a04a764f --- /dev/null +++ b/internal/cli/repeatedflags.go @@ -0,0 +1,142 @@ +// This file is not generated by Speakeasy. It refuses a flag that takes one +// value when the command line gives it two different ones. +// +// pflag keeps the last value of such a flag and drops the others without a +// word. The round-5 human-kb tester ran `document create-text --file +// faq/refunds.md --file faq/accounts.md --wait` and got "✓ Added +// accounts.md"; refunds.md was never added, and only `document list` showed +// it. The same silence picks the wrong project for `-p A … -p B`, the wrong +// environment for `-e main … -e staging`, or sends half of a --body. +// +// So before anything is asked or sent, a flag that takes one value and was +// given two different ones is a usage error, exit 2, that names the flag and +// both values (a secret's are not repeated). This holds for every such flag, +// not only --file: none of them can use two values, and which one wins is +// not something to leave to the order of words. The same value twice is +// harmless and still runs, and so does a flag that takes several values, +// such as --header or a list flag. The home prompt runs each line through +// the same check (home.go); forms and pickers set flags after it. + +package cli + +import ( + "fmt" + "strconv" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/output" +) + +// repeatedFlag finds, among the flags of the command args name, one that +// takes a single value and was given two different ones. When it does, it +// reports the error and returns it, with the command, as unknownSubcommand +// does. +func repeatedFlag(root *cobra.Command, args []string) (*cobra.Command, error) { + cmd, rest, err := root.Find(args) + if err != nil || cmd == 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, "") + } + first := map[string]string{} + var twice *repeatedFlagError + // ParseAll hands each flag and value to the function instead of setting + // it, so nothing is read or changed: a --code @file is not read twice. + _ = flags.ParseAll(rest, func(f *pflag.Flag, value string) error { + if takesSeveral(f) { + return nil + } + was, given := first[f.Name] + switch { + case !given: + first[f.Name] = value + case twice == nil && !sameValue(f, was, value): + twice = &repeatedFlagError{flag: f.Name, first: was, second: value, + secret: secretFlag(cmd, f.Name) || (f.Name == "body" && bodyHoldsSecret(cmd)) || f.Name == "token"} + } + return nil + }) + if twice == nil { + return nil, nil + } + reportIn(cmd, rest) + return cmd, output.Report(cmd, twice.explain(cmd), output.WithExitCode(twice, output.ExitUsage)) +} + +// repeatedFlagError is a flag that takes one value, given two. +type repeatedFlagError struct { + flag, first, second string + secret bool // its values are not repeated +} + +func (e *repeatedFlagError) Error() string { + if e.secret { + return fmt.Sprintf("--%s was given twice, with different values", e.flag) + } + return fmt.Sprintf("--%s was given twice, as %s and as %s", e.flag, shellWord(e.first), shellWord(e.second)) +} + +// explain says what happened and what to do instead. +func (e *repeatedFlagError) explain(cmd *cobra.Command) output.Explanation { + x := output.Explanation{ + Type: "usage_error", + Title: e.Error(), + Why: []string{"--" + e.flag + " takes one value, and vf would have used only the last. Nothing was sent."}, + Next: []string{"Give --" + e.flag + " once, with the value you mean"}, + } + if e.flag == "file" { + x.Next = []string{"`" + cmd.CommandPath() + "` takes one file: run it once for each file"} + } + return x +} + +// takesSeveral is whether f is a flag that collects each value given, such +// as --header or a list flag, rather than keeping one. +func takesSeveral(f *pflag.Flag) bool { + if _, ok := f.Value.(pflag.SliceValue); ok { + return true + } + t := f.Value.Type() + return t == "count" || strings.HasPrefix(t, "stringTo") || strings.HasSuffix(t, "Slice") || strings.HasSuffix(t, "Array") +} + +// sameValue is whether a and b are one value for f: true and 1 are one +// value for a switch. +func sameValue(f *pflag.Flag, a, b string) bool { + if a == b { + return true + } + if f.Value.Type() == "bool" { + x, errA := strconv.ParseBool(a) + y, errB := strconv.ParseBool(b) + return errA == nil && errB == nil && x == y + } + return false +} + +// reportIn applies the flags that decide how an error is reported (agent +// mode, -o json, --jq), which cobra never parsed: the error comes out the +// way the command line asked for. No other flag is set. +func reportIn(cmd *cobra.Command, rest []string) { + flags := pflag.NewFlagSet(cmd.Name(), pflag.ContinueOnError) + flags.SetOutput(discard{}) + flags.ParseErrorsAllowlist.UnknownFlags = true + for _, name := range []string{"agent-mode", "output-format", "jq"} { + if f := cmd.Flags().Lookup(name); f != nil { + flags.AddFlag(f) + } else if f := cmd.InheritedFlags().Lookup(name); f != nil { + flags.AddFlag(f) + } + } + _ = flags.Parse(rest) + output.InitAgentMode(cmd) +} diff --git a/internal/cli/repeatedflags_test.go b/internal/cli/repeatedflags_test.go new file mode 100644 index 00000000..b4f1eeed --- /dev/null +++ b/internal/cli/repeatedflags_test.go @@ -0,0 +1,129 @@ +// This file is not generated by Speakeasy. It covers repeatedflags.go: a +// flag that takes one value, given two different ones, is refused before +// anything is sent. + +package cli + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/ui" +) + +func TestAFlagGivenTwoValuesIsRefused(t *testing.T) { + root := testRoot(t) + t.Cleanup(output.ResetAgentMode) + captureStderr(t) // each refusal is reported + refused := []struct { + args []string + want string + }{ + {[]string{"document", "create-text", "-p", "p1", "-e", "main", "--file", "faq/refunds.md", "--file", "faq/accounts.md"}, + "--file was given twice, as faq/refunds.md and as faq/accounts.md"}, + {[]string{"project", "get", "-p", "A", "--project-id=B"}, "--project-id was given twice, as A and as B"}, + {[]string{"variable", "list", "-p", "p1", "-e", "main", "-e", "staging"}, "--environment-alias was given twice, as main and as staging"}, + {[]string{"document", "create-text", "--wait", "--wait=false"}, "--wait was given twice, as true and as false"}, + {[]string{"agent", "update", "--prompt", "@a.md", "--prompt", "two words"}, `--prompt was given twice, as @a.md and as "two words"`}, + {[]string{"project", "list", "-o", "json", "--output-format", "yaml"}, "--output-format was given twice, as json and as yaml"}, + {[]string{"secret", "set-value", "--value", "hunter2", "--value", "hunter3"}, "--value was given twice, with different values"}, + {[]string{"secret", "set-value", "--body", `{"value":"hunter2"}`, "--body", `{"value":"hunter3"}`}, "--body was given twice, with different values"}, + } + for _, c := range refused { + cmd, err := repeatedFlag(root, c.args) + var twice *repeatedFlagError + if !errors.As(err, &twice) || cmd == nil { + t.Errorf("%q: want it refused, got %v", c.args, err) + continue + } + x := twice.explain(cmd) + if x.Title != c.want || x.Type != "usage_error" || output.ExitCode(err) != output.ExitUsage { + t.Errorf("%q: got %q (%s, exit %d), want %q", c.args, x.Title, x.Type, output.ExitCode(err), c.want) + } + if strings.Contains(explained(x), "hunter") { + t.Errorf("%q: a secret is repeated:\n%s", c.args, explained(x)) + } + } + if x := (&repeatedFlagError{flag: "file", first: "a", second: "b"}).explain(find(t, root, "document", "create-text")); !strings.Contains(explained(x), "takes one file: run it once for each file") { + t.Errorf("--file should say one file per call:\n%s", explained(x)) + } + + // The same value twice is harmless, and a flag that collects values + // takes each. + for _, args := range [][]string{ + {"document", "create-text", "--file", "faq/refunds.md", "--file=faq/refunds.md"}, + {"document", "create-text", "--wait", "--wait=true", "--wait=1"}, + {"project", "get", "-p", "A", "-H", "X-A: 1", "-H", "X-B: 2"}, + {"test", "run", "wait", "--run-ids", "r1", "--run-ids", "r2"}, + {"conversation", "send", "--text", "hi", "--", "--text", "there"}, + {"document", "create-text", "--file", "a.md", "--nosuch", "x", "--nosuch", "y"}, + {"project", "get", "--help"}, + {}, + } { + if cmd, err := repeatedFlag(root, args); err != nil { + t.Errorf("%q: %v (%s)", args, err, cmd.CommandPath()) + } + } +} + +// Neither vf nor the home prompt sends anything for a repeated --file: +// round-5 human-kb added only the second of two files, silently. +func TestARepeatedFileSendsNothing(t *testing.T) { + isolate(t) + var requests atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + t.Errorf("unexpected request %s %s", r.Method, r.URL) + })) + t.Cleanup(srv.Close) + t.Setenv("VF_TOKEN", "vfp_fake") + dir := t.TempDir() + for _, name := range []string{"refunds.md", "accounts.md"} { + writeFile(t, filepath.Join(dir, name), "# "+name+"\n") + } + t.Chdir(dir) + line := []string{"document", "create-text", "-p", "p1", "-e", "main", "--file", "refunds.md", "--file", "accounts.md", "--server-url", srv.URL, "--no-interactive", "--agent-mode=false"} + + stderr := captureStderr(t) + saved := os.Args + os.Args = append([]string{"vf"}, line...) + t.Cleanup(func() { os.Args = saved }) + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + err := Execute() + if code := ExitCode(err); code != output.ExitUsage { + t.Errorf("vf: exit %d, want %d", code, output.ExitUsage) + } + runLine(context.Background(), ui.Plain(), line) // the home prompt + if got := stderr(); strings.Count(got, "--file was given twice, as refunds.md and as accounts.md") != 2 { + t.Errorf("vf and the home prompt should each say so:\n%s", got) + } + if requests.Load() != 0 { + t.Errorf("%d requests were sent", requests.Load()) + } +} + +// captureStderr sends os.Stderr to a file until the test ends, and returns +// what has been written to it so far. +func captureStderr(t *testing.T) func() string { + t.Helper() + f, err := os.CreateTemp(t.TempDir(), "stderr") + if err != nil { + t.Fatal(err) + } + saved := os.Stderr + os.Stderr = f + t.Cleanup(func() { os.Stderr = saved; f.Close() }) + return func() string { + data, _ := os.ReadFile(f.Name()) + return string(data) + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index 25381ba2..4f349a4f 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -273,6 +273,9 @@ func Execute() error { if cmd, err := unknownSubcommand(rootCmd, commandLine()); err != nil { // errors.go: 'vf workspace lsit' fails rather than printing help return renderError(cmd, err) } + if cmd, err := repeatedFlag(rootCmd, commandLine()); err != nil { // repeatedflags.go: --file a --file b fails rather than dropping a + return renderError(cmd, err) + } return renderError(rootCmd.ExecuteC()) // errors.go: what went wrong, why, and what to do next } From fe10130de5c0392b6d490c13f3e9ea0b4bd01a34 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:06:09 -0500 Subject: [PATCH 04/31] fix(document): a bare --overwrite means true A knowledge base document's options (--overwrite, --single-chunk, --markdown-conversion and the --llm-* flags, 39 flags on six document commands) are a union of a boolean and the strings "true" and "false" in the spec, so they are string flags. Given bare, as the switch --wait next to them is, `--overwrite --dry-run` took "--dry-run" as the value and failed with "it isn't valid JSON at character 2", and a bare --overwrite last on the line said only that it needed a value. Found by the round-5 sweep's agent-ci, agent-migrator and agent-builder testers. pflag's NoOptDefVal alone would turn the `--overwrite true` that help and hints write into the flag plus a stray word "true". So these flags are marked where their metadata is described, and vf and the home prompt rewrite one given bare, with nothing or another flag after it, as --overwrite=true before cobra or any other check reads the line. `--overwrite true`, `--overwrite false` and `--overwrite=false` work as before, and so does -s for --single-chunk. A value that is neither now says "invalid value for --overwrite: it takes true or false", not that it isn't valid JSON. --- internal/cli/errors.go | 5 +- internal/cli/home.go | 1 + internal/cli/root.go | 1 + internal/cli/truefalse.go | 61 ++++++++++++++++ internal/cli/truefalse_test.go | 121 ++++++++++++++++++++++++++++++++ internal/flagutil/forms.go | 1 + internal/flagutil/inputerror.go | 6 ++ internal/flagutil/truefalse.go | 49 +++++++++++++ 8 files changed, 243 insertions(+), 2 deletions(-) create mode 100644 internal/cli/truefalse.go create mode 100644 internal/cli/truefalse_test.go create mode 100644 internal/flagutil/truefalse.go diff --git a/internal/cli/errors.go b/internal/cli/errors.go index 1e2bd107..3d929430 100644 --- a/internal/cli/errors.go +++ b/internal/cli/errors.go @@ -418,8 +418,9 @@ func parseFlagsAfterError(cmd *cobra.Command) { } } -// commandLine is the arguments Execute runs, which cobra reads from os.Args. -func commandLine() []string { return os.Args[1:] } +// commandLine is the arguments Execute runs, from os.Args, with a bare +// --overwrite written --overwrite=true (truefalse.go). +func commandLine() []string { return bareMeansTrue(rootCmd, os.Args[1:]) } type discard struct{} diff --git a/internal/cli/home.go b/internal/cli/home.go index d89cdfe9..f0909122 100644 --- a/internal/cli/home.go +++ b/internal/cli/home.go @@ -168,6 +168,7 @@ func runLine(ctx context.Context, u *ui.UI, args []string) { return } setPromptHelp(root, u) + args = bareMeansTrue(root, args) // truefalse.go: a bare --overwrite means true root.SetArgs(args) if cmd, err := unknownSubcommand(root, args); err != nil { _ = renderError(cmd, err) diff --git a/internal/cli/root.go b/internal/cli/root.go index 4f349a4f..81f49329 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -266,6 +266,7 @@ func Execute() error { // Early agent mode detection from env vars (flag parsing hasn't happened yet), // so an error from parsing the flags themselves is already in agent form. output.InitAgentMode(rootCmd) + rootCmd.SetArgs(commandLine()) // errors.go: a bare --overwrite means true // 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 diff --git a/internal/cli/truefalse.go b/internal/cli/truefalse.go new file mode 100644 index 00000000..ee2ff422 --- /dev/null +++ b/internal/cli/truefalse.go @@ -0,0 +1,61 @@ +// This file is not generated by Speakeasy. It reads a flag that takes true +// or false as text, given bare, as given true: `document create-text --file +// faq.md --overwrite --dry-run` replaces the document, as `--overwrite true` +// does, rather than taking "--dry-run" as the value and failing with "it +// isn't valid JSON". flagutil/truefalse.go says which flags these are, and +// why pflag can't do this on its own. +// +// The words are rewritten before cobra or any other check reads them: vf's +// command line (commandLine, errors.go) and each line of the home prompt +// (home.go). + +package cli + +import ( + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" +) + +// bareMeansTrue is args with each true-or-false flag that has no value, as +// --overwrite or -s with nothing or another flag after it, written +// --overwrite=true. Anything else is left as it is. +func bareMeansTrue(root *cobra.Command, args []string) []string { + if root == nil { + return args + } + cmd, _, err := root.Find(args) + if err != nil || cmd == nil { + return args + } + var out []string // a copy, once a word changes: args stays as it was + for i := 0; i < len(args); i++ { + word := args[i] + if word == "--" { + break + } + f, hasValue := lookupFlag(cmd, word) // historysecret.go + switch { + case f == nil, hasValue: + case flagutil.TakesTrueOrFalse(f) && (i+1 == len(args) || isFlagWord(args[i+1])): + if out == nil { + out = append([]string{}, args...) + } + out[i] = "--" + f.Name + "=true" + case f.NoOptDefVal == "": + i++ // the next word is its value + } + } + if out == nil { + return args + } + return out +} + +// isFlagWord is whether word is a flag, or the -- that ends them, rather +// than a value: - alone names stdin. +func isFlagWord(word string) bool { + return len(word) > 1 && strings.HasPrefix(word, "-") +} diff --git a/internal/cli/truefalse_test.go b/internal/cli/truefalse_test.go new file mode 100644 index 00000000..f4ffc94c --- /dev/null +++ b/internal/cli/truefalse_test.go @@ -0,0 +1,121 @@ +// This file is not generated by Speakeasy. It covers truefalse.go and +// flagutil/truefalse.go: a flag that takes true or false as text means true +// given bare. + +package cli + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/ui" +) + +// The knowledge base document options are the flags that take true or false +// as text, on every command that has them. +func TestTheTrueOrFalseFlagsAreMarked(t *testing.T) { + root := testRoot(t) + names := map[string]bool{"overwrite": true, "single-chunk": true, "markdown-conversion": true, "llm-based-chunks": true, + "llm-generated-q": true, "llm-content-summarization": true, "llm-prepend-context": true} + marked := 0 + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if flagutil.TakesTrueOrFalse(f) { + marked++ + if !names[f.Name] { + t.Errorf("%s --%s is marked true-or-false", c.CommandPath(), f.Name) + } + } + }) + } + walk(root) + if marked != 39 { + t.Errorf("%d flags are marked true-or-false, want the 39 document options of six commands", marked) + } + if flagutil.TakesTrueOrFalse(find(t, root, "document", "create-text").Flags().Lookup("wait")) { + t.Error("--wait is a plain switch") + } +} + +// round-5 agent-ci:F8, agent-migrator:F7, agent-builder:F12: `--overwrite +// --dry-run` took "--dry-run" as its value. Bare, with nothing or a flag +// after it, it now means true; a value after it is still its value. +func TestABareTrueOrFalseFlagMeansTrue(t *testing.T) { + root := testRoot(t) + base := []string{"document", "create-text", "--file", "faq.md"} + cases := []struct{ in, want string }{ + {"--overwrite --dry-run", "--overwrite=true --dry-run"}, + {"--dry-run --overwrite", "--dry-run --overwrite=true"}, + {"-s --overwrite", "--single-chunk=true --overwrite=true"}, + {"--overwrite -- --x", "--overwrite=true -- --x"}, + {"--overwrite true --dry-run", "--overwrite true --dry-run"}, + {"--overwrite false", "--overwrite false"}, + {"--overwrite=false", "--overwrite=false"}, + {"--overwrite yes", "--overwrite yes"}, + {"-e --overwrite", "-e --overwrite"}, // the value of -e + {"--wait --overwrite", "--wait --overwrite=true"}, + {"-- --overwrite", "-- --overwrite"}, + } + for _, c := range cases { + args := append(append([]string{}, base...), strings.Fields(c.in)...) + saved := append([]string{}, args...) + got := strings.Join(bareMeansTrue(root, args)[len(base):], " ") + if got != c.want { + t.Errorf("%q: got %q, want %q", c.in, got, c.want) + } + if strings.Join(args, " ") != strings.Join(saved, " ") { + t.Errorf("%q: the words given were changed", c.in) + } + } + if got := bareMeansTrue(root, []string{"project", "get", "--overwrite"}); strings.Join(got, " ") != "project get --overwrite" { + t.Errorf("a command without the flag is left alone: %q", got) + } +} + +// Through vf and the home prompt, a bare --overwrite sends overwrite=true, +// and a value that isn't true or false says so rather than "isn't valid +// JSON". +func TestABareOverwriteIsSentAsTrue(t *testing.T) { + isolate(t) + t.Setenv("VF_TOKEN", "vfp_fake") + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "faq.md"), "# FAQ\n") + t.Chdir(dir) + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + line := []string{"document", "create-text", "-p", "p1", "-e", "main", "--file", "faq.md", "--overwrite", "--dry-run", "--agent-mode=false", "--no-interactive", "-s"} + + stderr := captureStderr(t) + saved := os.Args + t.Cleanup(func() { os.Args = saved }) + os.Args = append([]string{"vf"}, line...) + if err := Execute(); err != nil { + t.Fatalf("vf: %v\n%s", err, stderr()) + } + runLine(context.Background(), ui.Plain(), line) // the home prompt + if got := stderr(); strings.Count(got, "overwrite=true&projectID=p1&singleChunk=true") != 2 { + t.Errorf("vf and the home prompt should each send overwrite=true and singleChunk=true:\n%s", got) + } + + os.Args = []string{"vf", "document", "create-text", "-p", "p1", "-e", "main", "--file", "faq.md", "--overwrite", "yes", "--dry-run", "--agent-mode=false", "--no-interactive"} + before := len(stderr()) + err := Execute() + if code := ExitCode(err); code != output.ExitUsage { + t.Errorf("--overwrite yes: exit %d, want %d", code, output.ExitUsage) + } + if got := stderr()[before:]; !strings.Contains(got, "invalid value for --overwrite: it takes true or false") || strings.Contains(got, "JSON") { + t.Errorf("--overwrite yes should say it takes true or false:\n%s", got) + } +} diff --git a/internal/flagutil/forms.go b/internal/flagutil/forms.go index b8bfa465..440f9af8 100644 --- a/internal/flagutil/forms.go +++ b/internal/flagutil/forms.go @@ -48,6 +48,7 @@ func describeForms(t reflect.Type, meta []FlagMeta) { return } markJSONFlags(cmd, t, meta) // jsonexample.go + markTrueOrFalse(cmd, meta) // truefalse.go: a bare --overwrite means true for _, m := range meta { if m.Kind != FlagKindUnion || m.Union == nil || !m.Union.Discriminated || len(m.Union.Variants) == 0 { continue diff --git a/internal/flagutil/inputerror.go b/internal/flagutil/inputerror.go index a55c4c44..7a4afd69 100644 --- a/internal/flagutil/inputerror.go +++ b/internal/flagutil/inputerror.go @@ -69,6 +69,9 @@ func bodyError(flag string, stdin bool, value string, target reflect.Type, cause // takes is what the flag takes, from unionTakes or variantTakes; target is // the type of the one form a variant's flag takes, or nil. func unionError(flag, takes, value string, target reflect.Type, cause error) error { + if takes == takesTrueOrFalse { // truefalse.go: not "it isn't valid JSON" + return &FlagValueError{Flag: flag, Value: value, Expected: "it takes true or false", Cause: cause} + } problem := jsonProblem(cause, target, value) if problem == noFormProblem { problem = "it isn't any of the forms --" + flag + " takes" @@ -401,6 +404,9 @@ func kindOfValue(v interface{}) (kind, literal string) { // unionTakes is what a union flag takes, from its description of its forms: // "JSON value (one of: string | number)" is "JSON, one of: string | number". func unionTakes(desc string) string { + if booleanOrEnum.MatchString(desc) { + return takesTrueOrFalse + } if f := plainForms(desc); f != "" { return "JSON, one of: " + f } diff --git a/internal/flagutil/truefalse.go b/internal/flagutil/truefalse.go new file mode 100644 index 00000000..423f6997 --- /dev/null +++ b/internal/flagutil/truefalse.go @@ -0,0 +1,49 @@ +// This file is not generated by Speakeasy. It marks the flags that take true +// or false as text, so that one given bare means true. +// +// A knowledge base document's options (--overwrite, --single-chunk, +// --markdown-conversion and the --llm-* flags on document create-text, +// create-url, create-table, create-sitemap and the managed sitemap +// commands) are a union of a boolean and the strings "true" and "false" in +// the spec, so they are string flags. Given bare, as the switch --wait next +// to them is, `--overwrite --dry-run` took "--dry-run" as its value and +// failed with "it isn't valid JSON at character 2", and a bare --overwrite +// last on the line said only "needs a value". Three round-5 testers hit it. +// +// pflag's NoOptDefVal can't fix it alone: with it, the `--overwrite true` +// that help and hints write becomes the flag and a stray word "true". So +// these flags keep taking a value, are marked here, and vf reads one given +// bare, with nothing or another flag after it, as given true +// (cli/truefalse.go). `--overwrite true`, `--overwrite=false` and +// `--overwrite false` work as before, and a value that is neither now says +// the flag takes true or false. + +package flagutil + +import ( + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// trueOrFalse annotates a flag that takes true or false as text. +const trueOrFalse = "vf:true-or-false" + +// takesTrueOrFalse is what such a flag takes, as its errors say it +// (inputerror.go). +const takesTrueOrFalse = "true or false" + +// markTrueOrFalse marks each flag in meta, registered on cmd, that is a +// union of a boolean and its string form. +func markTrueOrFalse(cmd *cobra.Command, meta []FlagMeta) { + for _, m := range meta { + if m.Kind == FlagKindUnion && m.Union != nil && !m.Union.Discriminated && booleanOrEnum.MatchString(m.Union.TypeDescription) { + _ = cmd.Flags().SetAnnotation(m.FlagName, trueOrFalse, []string{"true"}) + } + } +} + +// TakesTrueOrFalse is whether f takes true or false as text, and means +// true given bare. +func TakesTrueOrFalse(f *pflag.Flag) bool { + return f != nil && len(f.Annotations[trueOrFalse]) > 0 +} From 14fc4f12b4a8d90c9a5f08f680544905a5208db7 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:18:40 -0500 Subject: [PATCH 05/31] fix(agent): --strict fails a write whose {tokens} didn't bind `vf agent update --instructions @instructions.md`, run before the variables it names existed, kept {customer_name} and {tier} as literal text and exited 0. The answer said "Kept as literal text" and listed unresolvedReferences, but a script under set -e carried on with a prompt that would never fill in, and the round-5 agent-migrator tester had to parse the list by hand. A non-zero exit by default would be wrong: the change is saved by then, and a script that reads a failed exit as "nothing happened" retries, so a create runs twice. So it is a flag. --strict, on the 34 commands whose answer can list unresolvedReferences (agent update and patch-*, playbook, prompt, message, tool, api-tool, mcp-server and workflow writes), prints the answer as before, then exits 1 with error type unresolved_references and a line per {token}: where it was, why it didn't bind, and that the change was saved. A backticked mention that matched no attached tool (unresolvedMentions) fails it too. Without --strict nothing changes. The commands are listed in cli/strict.go; a test reads each command's SDK call and fails when the list and the SDK disagree. --- README.md | 2 + internal/cli/root.go | 1 + internal/cli/strict.go | 46 ++++++++ internal/cli/strict_test.go | 207 ++++++++++++++++++++++++++++++++++++ internal/output/output.go | 2 + internal/output/strict.go | 120 +++++++++++++++++++++ 6 files changed, 378 insertions(+) create mode 100644 internal/cli/strict.go create mode 100644 internal/cli/strict_test.go create mode 100644 internal/output/strict.go diff --git a/README.md b/README.md index 388982e1..3ed62baf 100644 --- a/README.md +++ b/README.md @@ -900,6 +900,8 @@ Each kind of failure has its own exit code, so a script can tell them apart with `vf --help` lists them too. +A write whose `{token}` names no variable or entity, or whose backticked mention names no attached tool, still succeeds: it keeps them as text, exits `0`, and its answer lists them in `unresolvedReferences` and `unresolvedMentions`. `--strict` on `agent update`, `playbook create`, `prompt update` and the other commands that write such text makes it exit `1` instead, with `error_type` `unresolved_references`, after the answer prints. The change is saved either way, so don't run a create again because of it. + In agent mode, and with `-o json` or `--jq`, an error is printed to stderr as one JSON object, with the same keys whether vf found the problem itself or the API answered with it: | Key | When | Meaning | diff --git a/internal/cli/root.go b/internal/cli/root.go index 81f49329..cde93699 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -244,6 +244,7 @@ func NewRootCommand() (*cobra.Command, error) { fixExamples(rootCmd) // examplehelp.go: every example runs as written rejectStrayArgs(rootCmd) // strayargs.go: a command that takes no arguments says so askFirst(rootCmd) // confirm.go: deletes and merges ask before they send, at a terminal + offerStrict(rootCmd) // strict.go: --strict fails a write whose {tokens} didn't bind describeBareFlags(rootCmd) // barehelp.go: a flag the spec left undescribed says what it is nameVFCommandsInHelp(rootCmd) // namehelp.go: vf's commands and flags, not MCP tools and API fields diff --git a/internal/cli/strict.go b/internal/cli/strict.go new file mode 100644 index 00000000..05106c03 --- /dev/null +++ b/internal/cli/strict.go @@ -0,0 +1,46 @@ +// This file is not generated by Speakeasy. It gives --strict to each command +// whose answer can say a {token} in what it wrote didn't bind +// (unresolvedReferences). output/strict.go makes the flag fail the command +// when one didn't; that file says why it is a flag and not the default. +// +// Nothing in a command says what its answer holds, so they are listed here. +// TestStrictIsOfferedWhereATokenCanFailToBind reads each command's SDK call +// and fails when this list and the SDK disagree, so a command the spec adds +// later is caught. + +package cli + +import ( + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/output" +) + +// strictCommands are the commands whose answer lists unresolvedReferences. +var strictCommands = []string{ + "agent update", "agent patch-prompt", "agent patch-instructions", + "agent add-tool-message", "agent update-tool-message", "agent add-workflow", "agent update-workflow", + "playbook create", "playbook update", "playbook patch-instructions", + "playbook add-tool-message", "playbook update-tool-message", "playbook path create", "playbook path update", + "prompt create", "prompt update", + "message create", "message add-variant", "message update-variant", + "tool create", "tool update", + "api-tool create", "api-tool update", + "mcp-server create", "mcp-server update", + "workflow create", "workflow create-block", "workflow add-blocks", "workflow add-actions", + "workflow replace-action", "workflow insert-step", "workflow update-step", + "workflow add-branch", "workflow update-branch", +} + +// offerStrict gives each of strictCommands --strict. +func offerStrict(root *cobra.Command) { + for _, path := range strictCommands { + c, _, err := root.Find(strings.Fields(path)) + if err != nil || c.CommandPath() != root.Name()+" "+path || c.Flags().Lookup(output.StrictFlag) != nil { + continue + } + c.Flags().Bool(output.StrictFlag, false, output.StrictHelp) + } +} diff --git a/internal/cli/strict_test.go b/internal/cli/strict_test.go new file mode 100644 index 00000000..67610b65 --- /dev/null +++ b/internal/cli/strict_test.go @@ -0,0 +1,207 @@ +// This file is not generated by Speakeasy. It covers strict.go and +// output/strict.go: --strict fails a write whose {tokens} or mentions +// didn't bind. + +package cli + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "regexp" + "runtime" + "sort" + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk" +) + +// sdkCall is the SDK method a generated command's run function calls, as +// "Agent.Update". +var sdkCall = regexp.MustCompile(`\bs\.((?:[A-Z]\w*\.)*[A-Z]\w*)\(cmd\.Context\(\)`) + +// answersUnbound is whether the SDK method named call answers with a body +// that can list unresolvedReferences. +func answersUnbound(t *testing.T, call string) bool { + t.Helper() + parts := strings.Split(call, ".") + typ := reflect.TypeOf(&sdk.VoiceflowSDK{}) + for _, field := range parts[:len(parts)-1] { + f, ok := typ.Elem().FieldByName(field) + if !ok { + t.Fatalf("the SDK has no %s in %s", field, call) + } + typ = f.Type + } + m, ok := typ.MethodByName(parts[len(parts)-1]) + if !ok { + t.Fatalf("the SDK has no method %s", call) + } + res := m.Type.Out(0).Elem() + for i := 0; i < res.NumField(); i++ { + body := res.Field(i).Type + for body.Kind() == reflect.Pointer { + body = body.Elem() + } + if body.Kind() != reflect.Struct { + continue + } + for j := 0; j < body.NumField(); j++ { + if strings.HasPrefix(body.Field(j).Tag.Get("json"), "unresolvedReferences,") { + return true + } + } + } + return false +} + +// runSource is the source of c's generated run function, or "" when it +// isn't one. +func runSource(t *testing.T, c *cobra.Command) string { + t.Helper() + if c.RunE == nil { + return "" + } + name := runtime.FuncForPC(reflect.ValueOf(c.RunE).Pointer()).Name() + const module = "github.com/voiceflow/cli/" + dot := strings.LastIndex(name, ".") + if !strings.HasPrefix(name, module) || dot < 0 { + return "" + } + dir, fn := filepath.Join("..", "..", name[len(module):dot]), name[dot+1:] + files, _ := filepath.Glob(filepath.Join(dir, "*.go")) + for _, file := range files { + src, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + if i := strings.Index(string(src), "\nfunc "+fn+"("); i >= 0 { + body := string(src[i:]) + if end := strings.Index(body, "\n}\n"); end >= 0 { + body = body[:end] + } + return body + } + } + return "" +} + +// The commands that take --strict are exactly those whose SDK call answers +// with unresolvedReferences: the list in strict.go can't fall behind the +// spec. +func TestStrictIsOfferedWhereATokenCanFailToBind(t *testing.T) { + root := testRoot(t) + var want, got []string + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + if c.Flags().Lookup(output.StrictFlag) != nil { + got = append(got, c.CommandPath()) + } + if m := sdkCall.FindStringSubmatch(runSource(t, c)); m != nil && answersUnbound(t, m[1]) { + want = append(want, c.CommandPath()) + } + } + walk(root) + sort.Strings(want) + sort.Strings(got) + if len(want) < 30 { + t.Fatalf("found %d commands whose answer lists unresolvedReferences; the SDK calls weren't read: %v", len(want), want) + } + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Errorf("--strict is on:\n %s\nthe commands whose answer lists unresolvedReferences are:\n %s", + strings.Join(got, "\n "), strings.Join(want, "\n ")) + } +} + +// unboundServer answers agent update with answer. +func unboundServer(t *testing.T, answer string) string { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(answer)) + })) + t.Cleanup(srv.Close) + return srv.URL +} + +const unboundAgentAnswer = `{"message":"Agent updated.\nKept as literal text — instructions: {customer_name}, instructions: {tier}: create the variable or entity, or fix the spelling, then write the field again with the same {token}.",` + + `"unresolvedReferences":[{"path":"instructions","token":"customer_name","reason":"unknown"},{"path":"instructions","token":"tier","reason":"unknown"}],` + + `"unresolvedMentions":[{"path":"instructions","mention":"lookup_ordr"}]}` + +// round-5 agent-migrator:F5: `agent update --instructions @instructions.md` +// kept {customer_name} as literal text and exited 0, so a script carried +// on. With --strict it prints the answer as before, then exits 1 and names +// each reference; without it, nothing changes. +func TestStrictFailsAWriteWhoseTokensDidntBind(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + line := []string{"agent", "update", "-p", "p1", "-e", "main", "--instructions", "Greet {customer_name}.", "--no-interactive"} + wants := []string{"3 references didn't bind, and were kept as text", + "{customer_name} in instructions: no variable or entity has that name", + "{tier} in instructions: no variable or entity has that name", + "lookup_ordr", "in instructions: no tool, playbook or workflow attached here has that name", + "The change was saved"} + for _, mode := range [][]string{{"--agent-mode=false"}, {"--agent-mode=true"}, {"--agent-mode=false", "-o", "json"}} { + url := unboundServer(t, unboundAgentAnswer) + out, err := runLineIn(t, "", append(append(append([]string{}, line...), "--strict", "--server-url", url), mode...)...) + if code := output.ExitCode(err); code != output.ExitFailure { + t.Errorf("%v: exit %d, want %d\n%s", mode, code, output.ExitFailure, out) + } + said := out + if mode[0] == "--agent-mode=true" || len(mode) > 1 { + i := strings.LastIndex(out, "{\n") + var envelope map[string]any + if i < 0 || json.Unmarshal([]byte(out[i:]), &envelope) != nil { + t.Fatalf("%v: want the JSON envelope last:\n%s", mode, out) + } + if envelope["error_type"] != "unresolved_references" || envelope["exit_code"] != float64(1) { + t.Errorf("%v: envelope %v", mode, envelope) + } + said = envelope["error"].(string) + "\n" + envelope["explanation"].(string) + } + for _, want := range wants { + if !strings.Contains(said, want) { + t.Errorf("%v: want %s in:\n%s", mode, want, said) + } + } + if answer := strings.Index(out, "Agent updated."); answer < 0 || answer > strings.Index(out, "didn't bind") { + t.Errorf("%v: the answer should print first, as without --strict:\n%s", mode, out) + } + + out, err = runLineIn(t, "", append(append(append([]string{}, line...), "--server-url", url), mode...)...) + if err != nil || !strings.Contains(out, "Agent updated.") || strings.Contains(out, "didn't bind") { + t.Errorf("%v: without --strict, the same answer exits 0 as before: %v\n%s", mode, err, out) + } + } + + url := unboundServer(t, `{"message":"Agent updated."}`) + if out, err := runLineIn(t, "", append(append([]string{}, line...), "--strict", "--server-url", url, "--agent-mode=false")...); err != nil { + t.Errorf("--strict with every token bound exits 0: %v\n%s", err, out) + } + if out, err := runLineIn(t, "", append(append([]string{}, line...), "--strict", "--dry-run", "--agent-mode=false")...); err != nil { + t.Errorf("--strict --dry-run exits 0: %v\n%s", err, out) + } +} + +// One {token}, named in the title. +func TestStrictNamesALoneToken(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + url := unboundServer(t, `{"message":"Prompt updated.","unresolvedReferences":[{"path":"system","token":"API_KEY","reason":"secret-not-allowed"}]}`) + out, err := runLineIn(t, "", "prompt", "update", "-p", "p1", "-e", "main", "--prompt-id", "pr1", "--system", "Use {API_KEY}.", + "--strict", "--server-url", url, "--no-interactive", "--agent-mode=false") + if output.ExitCode(err) != output.ExitFailure || !strings.Contains(out, "{API_KEY} didn't bind, and was kept as text") || + !strings.Contains(out, "{API_KEY} in system: it names a secret, and this field can't use one") { + t.Errorf("exit %d:\n%s", output.ExitCode(err), out) + } +} diff --git a/internal/output/output.go b/internal/output/output.go index 7928c9df..fe89183b 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -148,6 +148,8 @@ 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{}) (err error) { + defer strictVerdict(cmd, res)(&err) // strict.go: --strict fails a write whose {tokens} didn't bind, once it has printed + 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() diff --git a/internal/output/strict.go b/internal/output/strict.go new file mode 100644 index 00000000..a6897d36 --- /dev/null +++ b/internal/output/strict.go @@ -0,0 +1,120 @@ +// This file is not generated by Speakeasy. It makes --strict fail a write +// whose {tokens} or `mentions` didn't bind. cli/strict.go gives the flag to +// the commands whose answer can say so. +// +// `vf agent update --instructions @instructions.md`, run before the +// variables it names existed, saved {customer_name} and {tier} as literal +// text and exited 0. The answer said so, "Kept as literal text — +// instructions: {customer_name}, …", and listed unresolvedReferences, but a +// script under set -e carried on with a prompt that would never fill in. +// The round-5 agent-migrator tester had to parse the list by hand. +// +// Failing by default would be wrong: by then the change is saved, and a +// script that reads a non-zero exit as "nothing happened" retries, and a +// create run twice makes two. So it is asked for. With --strict, once the +// answer has printed as before, a reference that didn't bind makes the +// command exit 1, error type unresolved_references, with a ✗ line that +// names each {token}, where it was and why, and says the change was saved. +// So does a `name` mention that matched no tool, playbook or workflow and +// was kept as inline code (unresolvedMentions), which a script misses the +// same way. + +package output + +import ( + "errors" + "fmt" + "strings" + + "github.com/spf13/cobra" +) + +// StrictFlag is the flag that fails a write when a {token} in it didn't +// bind. +const StrictFlag = "strict" + +// StrictHelp is --strict's help. +const StrictHelp = "Exit 1 when a {token} or a mention in what you wrote binds to nothing and is kept as text. The change is saved either way" + +// unboundAnswer is what --strict reads of an answer. +type unboundAnswer struct { + UnresolvedReferences []struct { + Path string `json:"path"` + Token string `json:"token"` + Reason string `json:"reason"` + } `json:"unresolvedReferences"` + UnresolvedMentions []struct { + Path string `json:"path"` + Mention string `json:"mention"` + } `json:"unresolvedMentions"` +} + +// strictVerdict reads res before it is printed, and returns what sets the +// command's error once it has been: an error only with --strict, when a +// {token} or mention didn't bind and nothing else went wrong. +func strictVerdict(cmd *cobra.Command, res interface{}) func(*error) { + f := cmd.Flags().Lookup(StrictFlag) + if f == nil || f.Value.String() != "true" { + return func(*error) {} + } + var a unboundAnswer + if !PeekJSON(extractHTTPResponse(res), &a) || len(a.UnresolvedReferences)+len(a.UnresolvedMentions) == 0 { + return func(*error) {} + } + return func(err *error) { + if *err == nil { + *err = unbound(cmd, a) + } + } +} + +// unbound reports the {tokens} and mentions in a that didn't bind. +func unbound(cmd *cobra.Command, a unboundAnswer) error { + var names, why []string + for _, r := range a.UnresolvedReferences { + names = append(names, "{"+r.Token+"}") + why = append(why, "{"+r.Token+"}"+where(r.Path)+": "+unboundReason(r.Reason)+".") + } + for _, m := range a.UnresolvedMentions { + names = append(names, "`"+m.Mention+"`") + why = append(why, "`"+m.Mention+"`"+where(m.Path)+": no tool, playbook or workflow attached here has that name.") + } + title := fmt.Sprintf("%d references didn't bind, and were kept as text", len(names)) + if len(names) == 1 { + title = names[0] + " didn't bind, and was kept as text" + } + why = append(why, "The change was saved: --strict fails the command, it doesn't undo it.") + return Report(cmd, Explanation{ + Type: "unresolved_references", + Title: title, + Why: why, + Next: []string{"Create the variable, entity or tool it names, or fix the spelling, then write the field again"}, + }, errors.New(title)) +} + +// where is " in path", or nothing without a path. +func where(path string) string { + if path == "" { + return "" + } + return " in " + path +} + +// unboundReason says why a {token} didn't bind, from the API's reason. +func unboundReason(reason string) string { + switch reason { + case "unknown": + return "no variable or entity has that name" + case "secret-not-allowed": + return "it names a secret, and this field can't use one" + case "path-on-non-variable": + return "only a variable has fields" + case "resource-id": + return "it is an ID; a {token} takes a name" + case "invalid-name": + return "a name is letters, digits and _, up to 64" + case "dangling": + return "what it named is gone" + } + return strings.ReplaceAll(reason, "-", " ") +} From 0e6541e14f032f1c2a06d04b71f9bc4d605f0879 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:48:26 -0500 Subject: [PATCH 06/31] fix(environment): diff says the global prompt isn't compared, not "No differences." The API's environment diff counts resources but leaves out the agent's global prompt, so after `agent patch-prompt` or `agent update --prompt` it still answers three zero counts and an empty list. Since 972814f, pretty output then ended with "No differences.", and testers read it as "nothing to publish" while the published version kept running the old prompt. Nothing the SDK calls can read the published version's prompt (read-prompt reads the draft; releases are backups with no read), so vf can't compare it either. Pretty output now says "No differences in the environment's resources (workflows, playbooks, tools, variables, the agent's instructions and the like)" when the counts are zero, and always "Not compared: the agent's global prompt", with how to ship an edit. JSON, YAML, TOON, --jq and agent mode get the API's answer with a new notCompared key saying the same; the API's own fields are byte-for-byte as sent. diff --help says what it compares. nodiff.go becomes diffcoverage.go. Round-5 sweep R5 #2 (agent-ci:F1, fix-verifier:N1). --- internal/cli/environment/diff.go | 5 +- internal/cli/environment/diffcoverage.go | 129 +++++++++++++++++++++++ internal/cli/environment/nodiff.go | 34 ------ internal/cli/outputview_test.go | 72 +++++++++---- 4 files changed, 185 insertions(+), 55 deletions(-) create mode 100644 internal/cli/environment/diffcoverage.go delete mode 100644 internal/cli/environment/nodiff.go diff --git a/internal/cli/environment/diff.go b/internal/cli/environment/diff.go index 218f1dc5..7d6bea47 100644 --- a/internal/cli/environment/diff.go +++ b/internal/cli/environment/diff.go @@ -30,6 +30,7 @@ func initDiffCmd(parent *cobra.Command) error { RunE: runDiffCmd, } flagutil.RegisterFlags(cmd, diffCmdMeta) + sayWhatDiffCovers(cmd) // diffcoverage.go: help says the global prompt isn't compared if err := flagutil.ValidateMeta[operations.StableEnvironmentControllerDiffRequest](diffCmdMeta); err != nil { return fmt.Errorf("invalid metadata for diff: %w", err) } @@ -75,9 +76,9 @@ func runDiffCmd(cmd *cobra.Command, args []string) error { return output.Error(cmd, err) } - if err := output.Result(cmd, res); err != nil { + if err := output.Result(cmd, withCoverage(cmd, res)); err != nil { // diffcoverage.go: JSON and agent output say what wasn't compared return err } - sayNoDifferences(cmd, res) // nodiff.go: a diff that found nothing says so + sayWhatWasCompared(cmd, res) // diffcoverage.go: no differences in resources, and the prompt not compared return nil } diff --git a/internal/cli/environment/diffcoverage.go b/internal/cli/environment/diffcoverage.go new file mode 100644 index 00000000..b015e375 --- /dev/null +++ b/internal/cli/environment/diffcoverage.go @@ -0,0 +1,129 @@ +// This file is not generated by Speakeasy. It has `vf environment diff` say +// what it compared, and that the agent's global prompt isn't part of it. +// +// The API's diff counts resources: workflows, tools, variables, the agent's +// instructions and the like. It leaves out the global prompt, so after +// `agent patch-prompt` or `agent update --prompt` it still answers three zero +// counts and an empty list. vf then ended pretty output with "No +// differences.", and the usability sweep's testers read that as "nothing to +// publish": the published version kept running the old prompt. Nothing the +// SDK can call reads the published version's prompt to compare with the +// draft's (read-prompt reads the draft, and releases are backups with no +// read), so vf can't check it either. +// +// Now pretty output says the resources didn't change, not that nothing did, +// and that the prompt wasn't compared. JSON, YAML, TOON, --jq and agent mode +// get the API's answer with one key more, notCompared, saying the same; the +// API's own fields are as it sent them. Drop all this once the API's diff +// covers the prompt. + +package environment + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" +) + +// notCompared is what JSON and agent output say the diff leaves out. +const notCompared = "the agent's global prompt: the diff doesn't compare it, so an edit to it since the last publish doesn't show here" + +// diffCovers is what diff's help says it compares. +const diffCovers = "It compares the environment's resources: workflows, playbooks, tools, variables, the agent's instructions and the like. " + + "It doesn't compare the agent's global prompt, so an edit to it doesn't show here: JSON and agent output say so under notCompared." + +// sayWhatDiffCovers adds to diff's help what it compares. +func sayWhatDiffCovers(cmd *cobra.Command) { + cmd.Long += "\n\n" + diffCovers +} + +// coveredDiff is the diff's answer with what it didn't compare. +type coveredDiff struct { + Diff components.StableEnvironmentDiffReport `json:"diff"` + NotCompared string `json:"notCompared"` +} + +// coveredDiffResponse carries a coveredDiff where output.Result looks for a +// response: the answer, and the HTTP response that -o json and -o yaml print +// as it came. +type coveredDiffResponse struct { + HTTPMeta components.HTTPMetadata `json:"-"` + Result *coveredDiff +} + +// withCoverage is the diff's answer as output prints it: for JSON, YAML, +// TOON, --jq and agent mode, with notCompared added; for a person, as it came, +// since sayWhatWasCompared says it in words. +func withCoverage(cmd *cobra.Command, res *operations.StableEnvironmentControllerDiffResponse) any { + if res == nil || client.IsDryRun(cmd) || forPeople(cmd) { + return res + } + addNotCompared(res.HTTPMeta.Response) + if typed := res.StableEnvironmentDiffResponse; typed != nil { + return &coveredDiffResponse{HTTPMeta: res.HTTPMeta, Result: &coveredDiff{Diff: typed.Diff, NotCompared: notCompared}} + } + return res +} + +// forPeople is whether output is pretty or a table: a person reads it. +func forPeople(cmd *cobra.Command) bool { + if output.WantsRawJSON(cmd) || output.IsAgentMode() { + return false + } + format := output.FormatOf(cmd) + return format == "pretty" || format == "table" +} + +// addNotCompared puts notCompared last in the raw answer, which -o json, +// --jq and -o yaml print, leaving every other byte as it was. +func addNotCompared(httpRes *http.Response) { + if httpRes == nil || httpRes.Body == nil { + return + } + raw, err := io.ReadAll(httpRes.Body) + httpRes.Body.Close() + httpRes.Body = io.NopCloser(bytes.NewReader(raw)) + if err != nil { + return + } + trimmed := bytes.TrimRight(raw, " \t\r\n") + if !json.Valid(trimmed) || len(trimmed) < 2 || trimmed[0] != '{' || trimmed[len(trimmed)-1] != '}' { + return + } + value, _ := json.Marshal(notCompared) + head := bytes.TrimRight(trimmed[:len(trimmed)-1], " \t\r\n") + sep := "," + if bytes.HasSuffix(head, []byte("{")) { + sep = "" + } + patched := append(append(append([]byte{}, head...), []byte(sep+`"notCompared":`)...), value...) + patched = append(patched, '}') + if json.Valid(patched) { + httpRes.Body = io.NopCloser(bytes.NewReader(patched)) + } +} + +// sayWhatWasCompared ends pretty output by saying what the diff compared: +// that the resources didn't change, when they didn't, and that the global +// prompt wasn't compared. +func sayWhatWasCompared(cmd *cobra.Command, res *operations.StableEnvironmentControllerDiffResponse) { + if res == nil || res.StableEnvironmentDiffResponse == nil || client.IsDryRun(cmd) || !output.ForAPerson(cmd) { + return + } + w := cmd.OutOrStdout() + u := output.UI(cmd, w) + d := res.StableEnvironmentDiffResponse.Diff + if d.Created+d.Updated+d.Deleted == 0 && len(d.Resources) == 0 { + fmt.Fprintln(w, u.Fit("No differences in the environment's resources (workflows, playbooks, tools, variables, the agent's instructions and the like).", 0)) + } + fmt.Fprintln(w, u.Fit("Not compared: the agent's global prompt. An edit to it since the last publish doesn't show here; 'vf environment publish' ships it.", 0)) +} diff --git a/internal/cli/environment/nodiff.go b/internal/cli/environment/nodiff.go deleted file mode 100644 index d97a2c70..00000000 --- a/internal/cli/environment/nodiff.go +++ /dev/null @@ -1,34 +0,0 @@ -// This file is not generated by Speakeasy. It has `vf environment diff` say -// so when there is nothing to publish. -// -// An environment whose draft matches its last publish came back as five -// fields: three zero counts, an empty list and `truncated: false`. Nothing -// said in words that the two were the same, so a person checking before a -// publish had to read the counts and decide. Now pretty output ends with -// "No differences." JSON, YAML, TOON, tables, --jq and agent mode get the -// response alone, as before. - -package environment - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/voiceflow/cli/internal/client" - "github.com/voiceflow/cli/internal/output" - "github.com/voiceflow/cli/internal/sdk/models/operations" -) - -// sayNoDifferences prints "No differences." under a diff that found none, -// for a person reading pretty output. -func sayNoDifferences(cmd *cobra.Command, res *operations.StableEnvironmentControllerDiffResponse) { - if res == nil || res.StableEnvironmentDiffResponse == nil || client.IsDryRun(cmd) || !output.ForAPerson(cmd) { - return - } - d := res.StableEnvironmentDiffResponse.Diff - if d.Created+d.Updated+d.Deleted > 0 || len(d.Resources) > 0 { - return - } - fmt.Fprintln(cmd.OutOrStdout(), "No differences.") -} diff --git a/internal/cli/outputview_test.go b/internal/cli/outputview_test.go index 01b9a93b..67aa19a5 100644 --- a/internal/cli/outputview_test.go +++ b/internal/cli/outputview_test.go @@ -1,5 +1,5 @@ // This file is not generated by Speakeasy. It covers the views commands add -// to pretty output for a person: environment/nodiff.go, +// to pretty output for a person: environment/diffcoverage.go, // knowledgebase/answer.go and test/run/runview.go. package cli @@ -67,34 +67,68 @@ const ( changedDiff = `{"diff":{"created":1,"updated":0,"deleted":0,"resources":[{"type":"playbook","id":"pb1","name":"Refunds","change":"created"}],"truncated":false}}` ) -func TestEnvironmentDiffSaysWhenThereAreNoDifferences(t *testing.T) { +// The API's diff leaves out the agent's global prompt (round-5 sweep R5 #2): +// after a prompt edit it answers zero counts, and vf said "No differences." +// while the published version still ran the old prompt. Pretty output now +// says only the resources didn't change, and that the prompt wasn't +// compared; JSON and agent output carry that under notCompared, with the +// API's fields as it sent them. +func TestEnvironmentDiffSaysThePromptIsNotCompared(t *testing.T) { diff := []string{"environment", "diff", "-p", "p1", "-e", "main"} + const ( + sameResources = "No differences in the environment's resources" + promptLine = "Not compared: the agent's global prompt." + ) cases := []struct { - name string - body string - agent bool - args []string - want bool + name string + body string + agent bool + args []string + want, not []string }{ - {name: "pretty, unchanged", body: unchangedDiff, want: true}, - {name: "pretty, changed", body: changedDiff}, - {name: "agent mode, unchanged", body: unchangedDiff, agent: true}, - {name: "json, unchanged", body: unchangedDiff, args: []string{"-o", "json"}}, - {name: "yaml, unchanged", body: unchangedDiff, args: []string{"-o", "yaml"}}, - {name: "jq, unchanged", body: unchangedDiff, args: []string{"--jq", ".diff.created"}}, + {name: "pretty, unchanged", body: unchangedDiff, want: []string{"diff:", sameResources, promptLine}, not: []string{"No differences.", "notCompared"}}, + {name: "pretty, changed", body: changedDiff, want: []string{"diff:", promptLine}, not: []string{"No differences", "notCompared"}}, + {name: "agent mode, unchanged", body: unchangedDiff, agent: true, want: []string{"diff:", "notCompared:", "global prompt"}, not: []string{"No differences", promptLine}}, + {name: "yaml, unchanged", body: unchangedDiff, args: []string{"-o", "yaml"}, want: []string{"diff:", "notCompared:", "global prompt"}, not: []string{"No differences", promptLine}}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { url := viewServer(t, map[string]string{"/v1/stable/environment/main/diff": c.body}) out, _ := runView(t, url, c.agent, append(diff, c.args...)...) - if got := strings.Contains(out, "No differences."); got != c.want { - t.Errorf("says no differences: %v, want %v\n--- got:\n%s", got, c.want, out) - } - if c.want && !strings.HasSuffix(out, "\nNo differences.\n") { - t.Errorf("not the last line:\n%s", out) - } + wantInOrder(t, out, c.want, c.not) }) } + + t.Run("json keeps the API's answer and adds notCompared", func(t *testing.T) { + url := viewServer(t, map[string]string{"/v1/stable/environment/main/diff": unchangedDiff}) + out, _ := runView(t, url, false, append(diff, "-o", "json")...) + var got map[string]json.RawMessage + if err := json.Unmarshal([]byte(out), &got); err != nil { + t.Fatalf("not JSON: %v\n%s", err, out) + } + if !strings.HasPrefix(out, strings.TrimSuffix(unchangedDiff, "}")) { + t.Errorf("the API's fields changed:\n%s", out) + } + var note string + if err := json.Unmarshal(got["notCompared"], ¬e); err != nil || !strings.Contains(note, "global prompt") { + t.Errorf("notCompared = %s, want it to name the global prompt", got["notCompared"]) + } + }) + + t.Run("jq reads the API's fields", func(t *testing.T) { + url := viewServer(t, map[string]string{"/v1/stable/environment/main/diff": unchangedDiff}) + out, _ := runView(t, url, false, append(diff, "--jq", ".diff.created")...) + if out != "0\n" { + t.Errorf("got %q, want %q", out, "0\n") + } + }) + + t.Run("help says so", func(t *testing.T) { + out, _ := runView(t, "http://127.0.0.1:1", false, append(diff, "--help")...) + if !strings.Contains(out, "doesn't compare the agent's global prompt") { + t.Errorf("help doesn't say the prompt isn't compared:\n%s", out) + } + }) } // kbChunks are two chunks as the API sends them: the better one second. From 2a7e33366a9bf900091234887ffcbd18540a5151 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:52:41 -0500 Subject: [PATCH 07/31] fix(document): update --wait shows the outcome, and its answer carries the final status MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `document update --wait` printed the API's message as a ✓ line ("…It is being processed again, so `vf document get` shows status PENDING until it is searchable"), then "✓ Updated refunds.md (d1) · ready". Two ✓ lines contradicted each other. Agent mode and -o json got only the message, stale by then, with no status to check: the only sign of success was exit 0. With --wait, a person at a terminal now sees only how the wait ended. JSON, YAML, TOON, --jq and agent mode get the API's message with a new status key beside it, holding the status the wait ended on, as a create's --wait answer carries it; -o json keeps the API's bytes and adds the key last. A wait that couldn't read the status leaves the answer as it came. Round-5 sweep R5 #27 (fix-verifier:N4, human-kb:F4). --- internal/cli/docready_test.go | 15 +++++ internal/cli/document/docready.go | 83 ++++++++++++++++++++++++-- internal/cli/document/docready_test.go | 46 +++++++++++++- internal/cli/document/update.go | 4 +- 4 files changed, 138 insertions(+), 10 deletions(-) diff --git a/internal/cli/docready_test.go b/internal/cli/docready_test.go index 19a32744..1e1fdf5b 100644 --- a/internal/cli/docready_test.go +++ b/internal/cli/docready_test.go @@ -201,6 +201,21 @@ func TestUpdateAndGetWait(t *testing.T) { t.Errorf("update: requests = %q", got) } + // The answer carries the status the wait ended on, beside the API's + // message, which said PENDING (R5 #27): in agent mode, and in -o json + // as the API sent it plus the status. + update := []string{"update", "--document-id", "d1", "-p", "p1", "-e", "main", "--content", "Refunds take 5 days.", "--wait"} + url, _ = documentServer(t, pending, success) + agentOut, _, err := runDocument(t, url, true, update...) + if err != nil || !strings.Contains(agentOut, "message:") || !strings.Contains(agentOut, "status:") || !strings.Contains(agentOut, "SUCCESS") { + t.Errorf("agent mode should get the message and the final status (%v):\n%s", err, agentOut) + } + url, _ = documentServer(t, pending, success) + jsonOut, _, err := runDocument(t, url, false, append(update, "-o", "json")...) + if want := `{"message":"Document d1 now holds the new content.","status":{"type":"SUCCESS"}}`; err != nil || strings.TrimSpace(jsonOut) != want { + t.Errorf("-o json: got %s (%v), want %s", strings.TrimSpace(jsonOut), err, want) + } + url, requests = documentServer(t, pending, success) stdout, stderr, err := runDocument(t, url, false, "get", "--document-id", "d1", "-p", "p1", "-e", "main", "--wait") if err != nil { diff --git a/internal/cli/document/docready.go b/internal/cli/document/docready.go index 64801d96..f11f1290 100644 --- a/internal/cli/document/docready.go +++ b/internal/cli/document/docready.go @@ -202,17 +202,24 @@ func whenProcessed(cmd *cobra.Command, projectID, alias string, res createdDocum // whenReprocessed is whenProcessed for `document update`, whose answer is // only a message. New text is processed again; a move or new metadata is not. -func whenReprocessed(cmd *cobra.Command, req *operations.StableDocumentControllerUpdateV2Request) func() error { +// It returns the answer to print, and what runs once it is printed. +// +// The API's message says the document "shows status PENDING until it is +// searchable", which a wait has made stale by the time it prints. So with +// --wait a person at a terminal sees only how the wait ended, and JSON, +// YAML, TOON, --jq and agent mode get the message with the final status +// beside it, as a create's answer carries it (finalStatus). +func whenReprocessed(cmd *cobra.Command, req *operations.StableDocumentControllerUpdateV2Request, res *operations.StableDocumentControllerUpdateV2Response) (any, func() error) { none := func() error { return nil } if req == nil || client.IsDryRun(cmd) { - return none + return res, none } ref := docRef{id: req.DocumentID, projectID: req.ProjectID, alias: req.EnvironmentAlias} if !waits(cmd) { if req.Body.Content == nil { - return none + return res, none } - return func() error { + return res, func() error { if announces(cmd) { nextSteps(cmd, []ui.Tip{{Command: ref.get(true), Does: "wait until the new text is searchable"}}) } @@ -220,7 +227,73 @@ func whenReprocessed(cmd *cobra.Command, req *operations.StableDocumentControlle } } w := pollDocument(cmd, &ref) - return func() error { return w.outcome(cmd, ref, "Updated") } + return finalStatus(cmd, res, w), func() error { return w.outcome(cmd, ref, "Updated") } +} + +// updatedDocument is an update's answer after --wait: the API's message and +// the status the wait ended on. +type updatedDocument struct { + Message string `json:"message"` + Status components.KBDocumentStatus `json:"status"` +} + +// updatedDocumentResponse carries an updatedDocument where output.Result +// looks for a response. A nil Result prints nothing. +type updatedDocumentResponse struct { + HTTPMeta components.HTTPMetadata `json:"-"` + Result *updatedDocument +} + +// finalStatus is the update's answer as it prints after a wait: nothing for +// a person at a terminal, since the outcome line says it all, and otherwise +// the message with the final status under "status", in the typed answer and +// in the raw one -o json and --jq print. A wait that couldn't read the +// status leaves the answer as it came. +func finalStatus(cmd *cobra.Command, res *operations.StableDocumentControllerUpdateV2Response, w waited) any { + if res == nil { + return res + } + if announces(cmd) { + return &updatedDocumentResponse{HTTPMeta: res.HTTPMeta} + } + if w.err != nil { + return res + } + if value, err := json.Marshal(w.status); err == nil { + addField(res.HTTPMeta.Response, "status", value) + } + if typed := res.StableUpdateResponse; typed != nil { + return &updatedDocumentResponse{HTTPMeta: res.HTTPMeta, Result: &updatedDocument{Message: typed.Message, Status: w.status}} + } + return res +} + +// addField puts key last in the JSON object a raw answer holds, leaving +// every other byte as it was. An answer that isn't an object stays as it is. +func addField(httpRes *http.Response, key string, value []byte) { + if httpRes == nil || httpRes.Body == nil { + return + } + raw, err := io.ReadAll(httpRes.Body) + httpRes.Body.Close() + httpRes.Body = io.NopCloser(bytes.NewReader(raw)) + if err != nil { + return + } + trimmed := bytes.TrimRight(raw, " \t\r\n") + if len(trimmed) < 2 || trimmed[0] != '{' || trimmed[len(trimmed)-1] != '}' || !json.Valid(trimmed) { + return + } + name, _ := json.Marshal(key) + head := bytes.TrimRight(trimmed[:len(trimmed)-1], " \t\r\n") + patched := append([]byte{}, head...) + if !bytes.HasSuffix(head, []byte("{")) { + patched = append(patched, ',') + } + patched = append(append(append(append(patched, name...), ':'), value...), '}') + if json.Valid(patched) { + httpRes.Body = io.NopCloser(bytes.NewReader(patched)) + } } // waitBeforeGet makes `document get --wait` poll the document until it is diff --git a/internal/cli/document/docready_test.go b/internal/cli/document/docready_test.go index 82277899..e8b9dbee 100644 --- a/internal/cli/document/docready_test.go +++ b/internal/cli/document/docready_test.go @@ -5,6 +5,8 @@ package document import ( "bytes" + "io" + "net/http" "strings" "testing" @@ -61,18 +63,56 @@ func TestAnUpdateOfTheTextSaysHowToWait(t *testing.T) { cmd.SetErr(&stderr) text := "new text" req := updateRequest("d1", &text) - if err := whenReprocessed(cmd, req)(); err != nil { - t.Fatal(err) + if _, after := whenReprocessed(cmd, req, nil); after() != nil { + t.Fatal("an update without --wait can't fail after the fact") } if got := stderr.String(); !strings.Contains(got, "vf document get --document-id d1 --wait -p p1 -e main") { t.Errorf("got:\n%s", got) } stderr.Reset() - if err := whenReprocessed(cmd, updateRequest("d1", nil))(); err != nil || stderr.Len() != 0 { + if _, after := whenReprocessed(cmd, updateRequest("d1", nil), nil); after() != nil || stderr.Len() != 0 { t.Errorf("a move isn't processed again, so says nothing, got %q", stderr.String()) } } +// After update --wait a person at a terminal sees only how the wait ended: +// the API's message, which says the document shows PENDING, isn't printed +// (R5 #27). Anywhere else the message prints with the final status. +func TestAnUpdateWaitShowsTheOutcomeNotTheStaleMessage(t *testing.T) { + res := &operations.StableDocumentControllerUpdateV2Response{ + StableUpdateResponse: &components.StableUpdateResponse{Message: "Document d1 now holds the new content. It shows status PENDING until it is searchable."}, + } + ready := waited{status: components.KBDocumentStatus{Type: components.KnowledgeBaseDocumentStatusSuccess}} + cmd := &cobra.Command{Use: "update"} + + shown, ok := finalStatus(cmd, res, ready).(*updatedDocumentResponse) + if !ok || shown.Result == nil || shown.Result.Status.Type != components.KnowledgeBaseDocumentStatusSuccess || shown.Result.Message != res.StableUpdateResponse.Message { + t.Errorf("off a terminal the answer should carry the message and the final status, got %#v", shown) + } + + atATerminal(t) + if shown, ok := finalStatus(cmd, res, ready).(*updatedDocumentResponse); !ok || shown.Result != nil { + t.Errorf("at a terminal nothing but the outcome line should print, got %#v", shown) + } +} + +// A field added to a raw answer goes last; every other byte stays. +func TestAddFieldKeepsEveryOtherByte(t *testing.T) { + for raw, want := range map[string]string{ + `{"message":"x"}`: `{"message":"x","status":{"type":"SUCCESS"}}`, + "{\"message\":\"x\"}\n": `{"message":"x","status":{"type":"SUCCESS"}}`, + `{}`: `{"status":{"type":"SUCCESS"}}`, + `["x"]`: `["x"]`, + } { + res := &http.Response{Body: io.NopCloser(strings.NewReader(raw))} + addField(res, "status", []byte(`{"type":"SUCCESS"}`)) + got, _ := io.ReadAll(res.Body) + if string(got) != want { + t.Errorf("addField(%q) = %s, want %s", raw, got, want) + } + } +} + // Only the status's value changes in a raw answer; every other byte stays. func TestReplaceStatusKeepsEveryOtherByte(t *testing.T) { raw := `{"document":{"id":"d1","data":{"name":"a","status":"x"},"status": {"type":"PENDING"} ,"folderID":null},"status":"top"}` diff --git a/internal/cli/document/update.go b/internal/cli/document/update.go index ae3e17b1..71fa122f 100644 --- a/internal/cli/document/update.go +++ b/internal/cli/document/update.go @@ -84,9 +84,9 @@ func runUpdateCmd(cmd *cobra.Command, args []string) error { if err != nil { return output.Error(cmd, err) } - processed := whenReprocessed(cmd, req) // docready.go: with --wait, polls until new text is processed + shown, processed := whenReprocessed(cmd, req, res) // docready.go: with --wait, polls until new text is processed - if err := output.Result(cmd, res); err != nil { + if err := output.Result(cmd, shown); err != nil { // docready.go: after --wait, the final status, not the stale PENDING message return err } return processed() // docready.go: whether it's ready, and how to check From 228c4331fd069f055f92e88e580d61475807375f Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:55:44 -0500 Subject: [PATCH 08/31] fix(ui): a spinner's frame fits the terminal, so it doesn't leave a line per frame MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A spinner redraws its frame with \r, which returns only to the start of the current line. A frame wider than the terminal wraps, so each redraw left the wrapped part behind. The document wait's frame ("Processing document 6b0e…… 0s · ctrl-c stops waiting, not the processing") is 85 to 97 columns, and at 80 columns a 2-second wait left about 20 lines. Every spinner's frame now fits the terminal's width, measured each frame so a resize is followed: the hint goes first, then the message is cut, ending in "…". The last column stays empty, since a line that reaches it wraps on some terminals. Off a terminal nothing changes. Round-5 sweep R5 #38 (human-kb:F9). --- internal/ui/spinner.go | 51 ++++++++++++++++++++++++++++++++++--- internal/ui/spinner_test.go | 46 +++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 4 deletions(-) diff --git a/internal/ui/spinner.go b/internal/ui/spinner.go index 2d90734b..9b61698c 100644 --- a/internal/ui/spinner.go +++ b/internal/ui/spinner.go @@ -7,6 +7,9 @@ import ( "io" "sync" "time" + + "github.com/charmbracelet/x/ansi" + "golang.org/x/term" ) // SpinnerFrames are the Working glyph's animation, Claude Code's: a dot that @@ -91,15 +94,55 @@ func (s *Spinner) run(delay time.Duration) { } func (s *Spinner) draw(frame int) { - line := s.u.Accent(SpinnerFrames[frame%len(SpinnerFrames)]) + " " + s.msg + " " + - s.u.Muted(formatElapsed(time.Since(s.start))) - if s.hint != "" { - line += s.u.Muted(" " + Separator.Symbol() + " " + s.hint) + glyph := SpinnerFrames[frame%len(SpinnerFrames)] + elapsed := formatElapsed(time.Since(s.start)) + msg, hint := fitSpinner(s.width(), glyph, s.msg, elapsed, s.hint) + line := s.u.Accent(glyph) + " " + msg + " " + s.u.Muted(elapsed) + if hint != "" { + line += s.u.Muted(" " + Separator.Symbol() + " " + hint) } // Erase the line first, so a shorter redraw leaves nothing behind. fmt.Fprint(s.w, "\r\x1b[2K"+line) } +// width is how many columns a frame may take: the terminal's, measured each +// frame so a resize is followed, or u's width off one (0: no limit). +func (s *Spinner) width() int { + if s.u.Width() <= 0 { + return 0 + } + if f, ok := s.w.(interface{ Fd() uintptr }); ok && term.IsTerminal(int(f.Fd())) { + return TerminalWidth(s.w) + } + return s.u.Width() +} + +// fitSpinner fits a frame on one line of width columns. \r only returns to +// the start of the current line, so a frame wider than the terminal wraps, +// and each redraw leaves the wrapped part behind: a 94-column frame left a +// line per frame at 80 columns, about 20 for a 2-second document wait. The +// hint goes first, then the message is cut, ending in "…". The last column +// stays empty, since a line that reaches it wraps on some terminals. A width +// of 0 is no limit. +func fitSpinner(width int, glyph, msg, elapsed, hint string) (string, string) { + if width <= 0 { + return msg, hint + } + room := width - 1 + fixed := ansi.StringWidth(glyph) + 1 + 1 + ansi.StringWidth(elapsed) // "✻ " + msg + " 12s" + withHint := fixed + ansi.StringWidth(msg) + if hint != "" { + withHint += 1 + ansi.StringWidth(Separator.Symbol()) + 1 + ansi.StringWidth(hint) + } + if withHint <= room { + return msg, hint + } + if fixed+ansi.StringWidth(msg) <= room { + return msg, "" + } + return ansi.Truncate(msg, max(room-fixed, 0), "…"), "" +} + // formatElapsed is 0s, 12s, 1m 05s: whole seconds, the way Claude Code counts. func formatElapsed(d time.Duration) string { sec := int(d.Seconds()) diff --git a/internal/ui/spinner_test.go b/internal/ui/spinner_test.go index d8ddd727..d541462d 100644 --- a/internal/ui/spinner_test.go +++ b/internal/ui/spinner_test.go @@ -5,6 +5,8 @@ import ( "strings" "testing" "time" + + "github.com/charmbracelet/x/ansi" ) func TestSpinnerDrawsThenErasesItsLine(t *testing.T) { @@ -32,6 +34,50 @@ func TestSpinnerDrawsThenErasesItsLine(t *testing.T) { } } +// A frame wider than the terminal wraps, and \r can't return past the wrap, +// so every redraw left a line behind (R5 #38: a document wait's 94-column +// frame at 80 columns). Each frame now fits: the hint goes first, then the +// message is cut. +func TestSpinnerFramesFitTheTerminal(t *testing.T) { + const ( + msg = "Processing document 6b0e173f4eb600496d834e02…" + hint = "ctrl-c stops waiting, not the processing" + ) + for _, c := range []struct { + width int + want, not []string + cutMessage bool + }{ + {width: 120, want: []string{msg, hint}}, + {width: 80, want: []string{msg + " 0s"}, not: []string{hint, "ctrl-c"}}, + {width: 30, want: []string{"Processing doc"}, not: []string{"ctrl-c"}, cutMessage: true}, + } { + var out bytes.Buffer + s := New(&out, Options{Decorate: true, Width: c.width}).Spin(&out, msg, hint) + time.Sleep(3 * spinnerTick) + s.Stop() + frames := strings.Split(strings.TrimSuffix(out.String(), "\r\x1b[2K"), "\r\x1b[2K") + for _, f := range frames[1:] { + if w := ansi.StringWidth(f); w >= c.width { + t.Errorf("width %d: a %d-column frame doesn't fit: %q", c.width, w, f) + } + if c.cutMessage && !strings.Contains(f, "… 0s") { + t.Errorf("width %d: a cut message should end in …: %q", c.width, f) + } + } + for _, w := range c.want { + if !strings.Contains(out.String(), w) { + t.Errorf("width %d: missing %q in %q", c.width, w, out.String()) + } + } + for _, n := range c.not { + if strings.Contains(out.String(), n) { + t.Errorf("width %d: %q should be dropped from %q", c.width, n, out.String()) + } + } + } +} + // DESIGN.md: never in a pipe. func TestSpinnerOffATerminalDrawsNothing(t *testing.T) { var out bytes.Buffer From d6ed57740cb9242835595e3146040cf26763282e Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:00:27 -0500 Subject: [PATCH 09/31] fix(document): a rate-limited URL says try again later, and a 409 "still processing" is explained MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A URL whose site answered HTTP 429 ends status ERROR with {"code": "urlRateLimited", "message": "The website is limiting how often pages are fetched (HTTP 429)."}. `create-url --wait` printed "✗ Couldn't process …" and "Fix the source, then add it again with --overwrite true", but nobody can fix Wikipedia. The retry, right away, got 409 "document is still processing, please retry after it finishes" with only "It conflicts with the current state", while the list said ERROR; later the document went INITIALIZED with nobody touching it. The knowledge base was still trying, and a newcomer had no next move. A wait that ends rate-limited now says "The site refused for now (rate-limited): try again in a few minutes", as a ⚠ warning rather than a final ✗, with the API's reason, that the knowledge base may still be trying, and what to do if it still says ERROR later. It still exits 1; JSON and agent mode get error_type document_rate_limited. A create without --wait that comes back rate-limited says the same. The 409 "still processing" now says the knowledge base is still working on the document and takes no new version until done, that its status can read ERROR meanwhile, and to wait a few minutes. Round-5 sweep R5 #13 (human-newcomer:F3). --- internal/cli/docready_test.go | 32 +++++++++++ internal/cli/document/docready.go | 8 +++ internal/cli/document/ratelimited.go | 86 ++++++++++++++++++++++++++++ internal/output/doctype.go | 25 ++++++++ internal/output/doctype_test.go | 24 ++++++++ 5 files changed, 175 insertions(+) create mode 100644 internal/cli/document/ratelimited.go diff --git a/internal/cli/docready_test.go b/internal/cli/docready_test.go index 1e1fdf5b..9de061d1 100644 --- a/internal/cli/docready_test.go +++ b/internal/cli/docready_test.go @@ -149,6 +149,38 @@ func TestADocumentThatFailsToProcessExits1(t *testing.T) { } } +// A URL whose site rate-limited the fetch ends ERROR with the status data +// human-newcomer:F3 saw. The site refused for now: the wait says to try again +// in a few minutes, as a warning, not "✗ Couldn't process" and "Fix the +// source" (R5 #13). It exits 1 all the same: the document isn't ready. +func TestARateLimitedDocumentSaysTryAgainLater(t *testing.T) { + const rateLimitedStatus = `{"type":"ERROR","data":{"code":"urlRateLimited","message":"The website is limiting how often pages are fetched (HTTP 429)."}}` + createURL := []string{"create-url", "-p", "p1", "-e", "main", "--url", "https://en.wikipedia.org/wiki/Cold_brew_coffee", "--wait"} + for _, agent := range []bool{false, true} { + url, _ := documentServer(t, pending, rateLimitedStatus) + stdout, stderr, err := runDocument(t, url, agent, createURL...) + if code := output.ExitCode(err); code != output.ExitFailure { + t.Fatalf("agent %v: exit %d, want %d\n%s%s", agent, code, output.ExitFailure, stdout, stderr) + } + for _, want := range []string{"refused billing.md (d1) for now (rate-limited): try again in a few minutes", "HTTP 429", "--overwrite true", "vf document get --document-id d1 --wait"} { + if !strings.Contains(stderr, want) { + t.Errorf("agent %v: missing %q in:\n%s", agent, want, stderr) + } + } + for _, not := range []string{"✗", "Couldn't process", "Fix the source"} { + if strings.Contains(stderr, not) { + t.Errorf("agent %v: %q is wrong for a site that refused for now:\n%s", agent, not, stderr) + } + } + if agent { + var envelope map[string]any + if json.Unmarshal([]byte(stderr), &envelope) != nil || envelope["error_type"] != "document_rate_limited" { + t.Errorf("agent mode should get the JSON envelope with its own error_type:\n%s", stderr) + } + } + } +} + // A wait that runs out exits with the timeout code and says how to keep // waiting. func TestADocumentWaitThatRunsOutExits5(t *testing.T) { diff --git a/internal/cli/document/docready.go b/internal/cli/document/docready.go index f11f1290..cc09fd0d 100644 --- a/internal/cli/document/docready.go +++ b/internal/cli/document/docready.go @@ -353,6 +353,11 @@ func announceAdded(cmd *cobra.Command, ref docRef, status components.KBDocumentS fmt.Fprintln(w, u.Status(ui.StatusDone, what+" · ready: the knowledge base answers from it")) return case components.KnowledgeBaseDocumentStatusError: + if rateLimited(status) { // ratelimited.go + fmt.Fprintln(w, u.Status(ui.StatusWarn, what+", but the site refused it for now (rate-limited): try again in a few minutes")) + nextSteps(cmd, []ui.Tip{{Command: ref.get(true), Does: "in a few minutes, whether it's ready"}}) + return + } fmt.Fprintln(w, u.Status(ui.StatusWarn, what+", but processing it failed: "+failureReason(status))) nextSteps(cmd, []ui.Tip{{Command: ref.get(false), Does: "see it"}}) return @@ -504,6 +509,9 @@ func (w waited) outcome(cmd *cobra.Command, ref docRef, did string) error { } return nil case components.KnowledgeBaseDocumentStatusError: + if rateLimited(w.status) { // ratelimited.go: the site refused for now, not a source to fix + return reportRateLimited(cmd, ref, w.status) + } message := "Couldn't process " + ref.call() return output.Report(cmd, output.Explanation{ Type: "document_failed", diff --git a/internal/cli/document/ratelimited.go b/internal/cli/document/ratelimited.go new file mode 100644 index 00000000..d1c922ae --- /dev/null +++ b/internal/cli/document/ratelimited.go @@ -0,0 +1,86 @@ +// This file is not generated by Speakeasy. It says what a document that a +// website rate-limited means: the site refused for now, so try again in a +// few minutes. +// +// A URL whose site answers HTTP 429 ends status ERROR, with the data +// {"code": "urlRateLimited", "message": "The website is limiting how often +// pages are fetched (HTTP 429)."}. `document create-url --wait` then printed +// "✗ Couldn't process …" and "Fix the source, then add it again with +// --overwrite true", but nobody can fix Wikipedia. And the knowledge base +// wasn't done: the retry, right away, got 409 "document is still processing", +// and a later list showed the document INITIALIZED, then ERROR again, with +// nobody touching it. A newcomer had no next move (round-5 sweep, +// human-newcomer:F3). +// +// Now a wait that ends this way says the site refused for now and to try +// again in a few minutes, as a warning rather than a final ✗, since the +// knowledge base may still be trying. It still exits 1, as the document +// isn't ready; JSON and agent mode get error_type document_rate_limited. The +// 409 is explained in output/doctype.go. + +package document + +import ( + "errors" + "fmt" + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/ui" +) + +// rateLimitedCode is the code a document's ERROR status carries when its +// website refused to be fetched for now. +const rateLimitedCode = "urlRateLimited" + +// rateLimited is whether status is an ERROR because the document's website +// limited how often its pages are fetched. +func rateLimited(status components.KBDocumentStatus) bool { + if status.Type != components.KnowledgeBaseDocumentStatusError { + return false + } + if data, ok := status.Data.(map[string]any); ok { + if code, _ := data["code"].(string); code == rateLimitedCode { + return true + } + } + return strings.Contains(failureReason(status), "(HTTP 429)") +} + +// refusedForNow is a rate-limited document's outcome. +func refusedForNow(ref docRef) string { + return "The site refused " + ref.call() + " for now (rate-limited): try again in a few minutes" +} + +// whyRefused is what a rate limit means for the document, and what to do +// when trying again doesn't help. +const whyRefused = "The knowledge base can't answer from it until a fetch gets through. It may try again on its own; " + + "meanwhile its status can read ERROR, and adding it again can be refused as still processing." + +// reportRateLimited ends a wait on a rate-limited document. A person gets a +// warning, not a ✗, since the knowledge base may still be trying; JSON and +// agent mode get the error envelope. Either way it exits 1. +func reportRateLimited(cmd *cobra.Command, ref docRef, status components.KBDocumentStatus) error { + title := refusedForNow(ref) + reason := failureReason(status) + err := errors.New(title + ": " + reason) + retry := "If in a few minutes it still says ERROR, add it again with `--overwrite true`, which keeps its ID, or use a different page" + if output.WantsJSONError(cmd) { + return output.Report(cmd, output.Explanation{ + Type: "document_rate_limited", + Title: title, + Message: reason, + Why: []string{whyRefused}, + Next: []string{"In a few minutes, check on it: `" + ref.get(true) + "`", retry}, + }, err) + } + w := cmd.ErrOrStderr() + u := output.UI(cmd, w) + fmt.Fprintln(w, u.Status(ui.StatusWarn, title)) + fmt.Fprintln(w, u.Under(reason, whyRefused, output.Plain(retry)+".")) + nextSteps(cmd, []ui.Tip{{Command: ref.get(true), Does: "in a few minutes, whether it's ready"}}) + return output.WithExitCode(output.AlreadyReported(err), output.ExitFailure) +} diff --git a/internal/output/doctype.go b/internal/output/doctype.go index dae7f2dd..0a91e9dd 100644 --- a/internal/output/doctype.go +++ b/internal/output/doctype.go @@ -11,6 +11,10 @@ // with "Use a different name, or change the one that exists". The fix is // --overwrite true, which replaces the document in place, and nothing said // so; the flag's own help reads only "true or false". +// +// A 409 "document is still processing" got only "It conflicts with the +// current state", while the document's status read ERROR; stillProcessing +// says what it means. package output @@ -27,6 +31,9 @@ const documentTypes = ".txt, .md, .pdf or .docx" // explainDocumentType recognizes the API refusing an uploaded file's type, // or a document whose name is taken. func explainDocumentType(cmd *cobra.Command, status int, message string) (why, next []string, ok bool) { + if why, next, ok := stillProcessing(cmd, status, message); ok { + return why, next, true + } if why, next, ok := duplicateDocument(cmd, status, message); ok { return why, next, true } @@ -42,6 +49,24 @@ func explainDocumentType(cmd *cobra.Command, status int, message string) (why, n return why, next, true } +// stillProcessing recognizes a document change refused with 409 "document is +// still processing, please retry after it finishes". It came right after a +// wait had ended ERROR, on a URL whose site rate-limited the fetch, and read +// as a contradiction: the knowledge base was still trying the document while +// its status said ERROR (round-5 sweep, human-newcomer:F3). +func stillProcessing(cmd *cobra.Command, status int, message string) (why, next []string, ok bool) { + if status != 409 || !strings.Contains(strings.ToLower(message), "still processing") { + return nil, nil, false + } + why = []string{"The knowledge base is still working on this document, and takes no new version until it's done. " + + "It may be trying it again after an error, such as a site that limited how often its pages are fetched: its status can read ERROR meanwhile."} + next = []string{"Wait a few minutes, then run it again"} + if list := listCommand(cmd); list != "" { + next = append(next, "`"+withScope(cmd, list)+" -o table` shows each document's status") + } + return why, next, true +} + // duplicateDocument recognizes a create refused because the knowledge base // has a document of that name or URL, and offers --overwrite true, which // replaces it, to a command that takes it and wasn't given it. diff --git a/internal/output/doctype_test.go b/internal/output/doctype_test.go index 2583c61a..ec8875c0 100644 --- a/internal/output/doctype_test.go +++ b/internal/output/doctype_test.go @@ -73,3 +73,27 @@ func TestADuplicateDocumentSaysOverwriteReplacesIt(t *testing.T) { t.Errorf("a conflict that isn't about the name isn't fixed by --overwrite:\n%s", got) } } + +// A 409 "still processing" says, in plain words, that the knowledge base is +// still working on the document, though its status may read ERROR, and to +// wait (R5 #13: the retry after a rate-limited URL got only "It conflicts +// with the current state"). +func TestADocumentStillProcessingIsExplained(t *testing.T) { + withCredential(t, Credential{Kind: CredentialSession}) + parent := &cobra.Command{Use: "document"} + cmd := &cobra.Command{Use: "create-url", Run: func(*cobra.Command, []string) {}} + cmd.Flags().String("overwrite", "", "") + parent.AddCommand(cmd, &cobra.Command{Use: "list", Run: func(*cobra.Command, []string) {}}) + _ = cmd.Flags().Set("overwrite", "true") + + body := `{"message":"document is still processing, please retry after it finishes","code":409}` + got := joined(explainWith(cmd, apiError(409, body, nil), 409, body, noLookup)) + for _, want := range []string{"still working on this document", "can read ERROR", "Wait a few minutes, then run it again", "-o table` shows each document's status"} { + if !strings.Contains(got, want) { + t.Errorf("missing %q in:\n%s", want, got) + } + } + if strings.Contains(got, "conflicts with the current state") { + t.Errorf("the generic conflict line says nothing here:\n%s", got) + } +} From 63af29af91be1c287f0b3b808ea84ba2470e799f Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:04:53 -0500 Subject: [PATCH 10/31] fix(knowledge-base): help and the home menu lead to the commands that add documents Adding a document lives under `vf document`, but `knowledge-base --help` listed only `query`, and the home prompt's menu matched command names alone: "/upload" gave an empty menu and "/add" only agent, workflow and message commands. A newcomer spent four calls and guesses on "add my FAQ to the knowledge base" before the full `vf help` turned up `document`. `knowledge-base --help` now says documents are added with vf document, with create-text, create-url, create-table and list. In the menu, "upload", "add", "kb" and "faq" (and "website", "spreadsheet") also find the commands that add documents, after the commands the word names. A word that names no command finds the commands whose summary has a word starting with it, before the abbreviation search; summaries are only a fallback, so "pro" still finds just `project`. Round-5 sweep R5 #14 (human-newcomer:F4). --- internal/cli/kbdocuments_test.go | 47 +++++++++++ internal/cli/knowledgebase/documents.go | 31 +++++++ internal/cli/knowledgebase/root.go | 1 + internal/prompt/complete.go | 6 ++ internal/prompt/intents.go | 102 ++++++++++++++++++++++++ internal/prompt/intents_test.go | 54 +++++++++++++ 6 files changed, 241 insertions(+) create mode 100644 internal/cli/kbdocuments_test.go create mode 100644 internal/cli/knowledgebase/documents.go create mode 100644 internal/prompt/intents.go create mode 100644 internal/prompt/intents_test.go diff --git a/internal/cli/kbdocuments_test.go b/internal/cli/kbdocuments_test.go new file mode 100644 index 00000000..026f7019 --- /dev/null +++ b/internal/cli/kbdocuments_test.go @@ -0,0 +1,47 @@ +// This file is not generated by Speakeasy. It covers +// knowledgebase/documents.go and, on vf's own tree, prompt/intents.go: the +// way from "knowledge base" to the commands that add documents. + +package cli + +import ( + "slices" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/prompt" +) + +// knowledge-base --help listed only query, and nothing pointed at vf +// document (R5 #14). Its help now names the commands that add documents. +func TestKnowledgeBaseHelpSaysHowToAddDocuments(t *testing.T) { + for _, name := range []string{"knowledge-base", "kb"} { + help, _ := runView(t, "http://127.0.0.1:1", false, name, "--help") + for _, want := range []string{"To add documents", "vf document create-text --file", "vf document create-url --url", "vf document create-table", "vf document list"} { + if !strings.Contains(help, want) { + t.Errorf("%s --help: missing %q in:\n%s", name, want, help) + } + } + } +} + +// In the home prompt, "/upload", "/add", "/kb" and "/faq" find the commands +// that add documents, on vf's own command tree. +func TestTheHomeMenuFindsHowToAddDocuments(t *testing.T) { + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + complete := prompt.Commands(root, nil) + for _, word := range []string{"/upload", "/add", "/kb", "/faq"} { + var got []string + for _, s := range complete(word) { + got = append(got, s.Label) + } + for _, want := range []string{"document create-text", "document create-url", "document create-table"} { + if !slices.Contains(got, want) { + t.Errorf("%q: %q isn't offered in %q", word, want, got) + } + } + } +} diff --git a/internal/cli/knowledgebase/documents.go b/internal/cli/knowledgebase/documents.go new file mode 100644 index 00000000..c20934a8 --- /dev/null +++ b/internal/cli/knowledgebase/documents.go @@ -0,0 +1,31 @@ +// This file is not generated by Speakeasy. It points `vf knowledge-base` at +// the commands that add to the knowledge base. +// +// Adding a document lives under `vf document`, and `knowledge-base --help` +// listed only `query`, so "add my FAQ to the knowledge base", step one of a +// support agent, cost a newcomer four calls and guesses before the full +// `vf help` turned up `document` (round-5 sweep, human-newcomer:F4). Now the +// help says where documents are added, and the home prompt's menu finds them +// by "upload", "add", "kb" or "faq" (internal/prompt/complete.go). + +package knowledgebase + +import "github.com/spf13/cobra" + +// addingDocuments is what knowledge-base's help says about filling it. +const addingDocuments = `Query the knowledge base: the documents your agent answers from. + +To add documents, use vf document: + vf document create-text --file faq.md + a file: .txt, .md, .pdf or .docx + vf document create-url --url https://example.com/faq + a web page + vf document create-table --name Plans --csv plans.csv + rows of structured data, from a spreadsheet + vf document list -o table + what's in it, and each document's status` + +// pointToDocuments says in cmd's help where documents are added. +func pointToDocuments(cmd *cobra.Command) { + cmd.Long = addingDocuments +} diff --git a/internal/cli/knowledgebase/root.go b/internal/cli/knowledgebase/root.go index 280a8466..11a8f2cc 100644 --- a/internal/cli/knowledgebase/root.go +++ b/internal/cli/knowledgebase/root.go @@ -21,6 +21,7 @@ func InitKnowledgeBaseRoot(parent *cobra.Command) error { }, Aliases: []string{"kb"}, } + pointToDocuments(KnowledgeBaseCmd) // documents.go: help says documents are added with vf document if err := initQueryCmd(KnowledgeBaseCmd); err != nil { return err diff --git a/internal/prompt/complete.go b/internal/prompt/complete.go index 570f89ea..6fa50443 100644 --- a/internal/prompt/complete.go +++ b/internal/prompt/complete.go @@ -160,6 +160,9 @@ func subcommands(root, cmd *cobra.Command, partial token, cmdStart int, extra [] } } out := append(prefix, contains...) + if cmd == root { + out = append(out, byIntent(root, p, cmdStart, out)...) // intents.go: "upload", "add", "kb", "faq" + } // At the top level, a word that names no command may name a deeper one. if cmd == root && len(p) >= deepSearchMin { @@ -181,6 +184,9 @@ func subcommands(root, cmd *cobra.Command, partial token, cmdStart int, extra [] }) sortByLabel(deep) out = append(out, deep...) + if len(out) == 0 { + out = byDescription(root, p, cmdStart, out) // intents.go: no name has it, so a word in what a command does + } } // Nothing starts with, contains or deeply names the word: try it as an diff --git a/internal/prompt/intents.go b/internal/prompt/intents.go new file mode 100644 index 00000000..6f115eab --- /dev/null +++ b/internal/prompt/intents.go @@ -0,0 +1,102 @@ +// This file is not generated by Speakeasy. It lets the home prompt's menu +// find a command by what it does, not only by its name. +// +// The menu matched names alone. A newcomer who wanted to add an FAQ to the +// knowledge base typed "/upload" and got an empty menu, and "/add" listed +// only agent, workflow and message commands: the commands that add +// documents are `document create-text`, `create-url` and `create-table`, and +// none of those words is "upload" or "add" (round-5 sweep, human-newcomer:F4). +// +// Now a few words people use for a task find the commands that do it +// ("upload", "add", "kb", "faq" find the three that add documents), after +// the commands those words name. And a word at the top level that names no +// command finds the commands whose summary has a word starting with it +// ("chunk" finds the one whose summary mentions chunking), before the menu +// tries it as an abbreviation. Summaries are a fallback only: "pro" would +// find every command that mentions a project. + +package prompt + +import ( + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/usage" +) + +// addingDocuments are the commands that add to the knowledge base. +var addingDocuments = []string{"document create-text", "document create-url", "document create-table"} + +// intents are words people type for a task, and the commands that do it. +var intents = map[string][]string{ + "upload": addingDocuments, + "add": addingDocuments, + "kb": addingDocuments, + "faq": addingDocuments, + + "website": {"document create-url"}, + "spreadsheet": {"document create-table"}, +} + +// intentMin is how many characters a word needs before it is read as the +// start of an intent: "kb" is one. +const intentMin = 2 + +// byIntent is the commands for the intents p starts, skipping those already +// offered. +func byIntent(root *cobra.Command, p string, from int, offered []Suggestion) []Suggestion { + if len(p) < intentMin { + return nil + } + want := map[string]bool{} + for word, paths := range intents { + if strings.HasPrefix(word, strings.ToLower(p)) { + for _, path := range paths { + want[path] = true + } + } + } + return matching(root, from, offered, func(_ *cobra.Command, path string) bool { return want[path] }) +} + +// byDescription is the commands whose summary has a word starting with p, +// skipping those already offered, at most fuzzyMax of them. +func byDescription(root *cobra.Command, p string, from int, offered []Suggestion) []Suggestion { + if len(p) < deepSearchMin { + return nil + } + p = strings.ToLower(p) + out := matching(root, from, offered, func(c *cobra.Command, _ string) bool { + for _, word := range strings.FieldsFunc(strings.ToLower(usage.SummaryOf(c)), notInWord) { + if strings.HasPrefix(word, p) { + return true + } + } + return false + }) + return out[:min(len(out), fuzzyMax)] +} + +func notInWord(r rune) bool { + return !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') +} + +// matching is every command below root that keep keeps and that offered +// lacks, as a menu row that replaces the line from from on, by name. +func matching(root *cobra.Command, from int, offered []Suggestion, keep func(*cobra.Command, string) bool) []Suggestion { + seen := map[string]bool{} + for _, s := range offered { + seen[s.Label] = true + } + var out []Suggestion + walk(root, func(c *cobra.Command, path string) { + if seen[path] || !keep(c, path) { + return + } + seen[path] = true + out = append(out, Suggestion{Label: path, Detail: usage.SummaryOf(c), Group: hasSubcommands(c), From: from}) + }) + sortByLabel(out) + return out +} diff --git a/internal/prompt/intents_test.go b/internal/prompt/intents_test.go new file mode 100644 index 00000000..6c680b56 --- /dev/null +++ b/internal/prompt/intents_test.go @@ -0,0 +1,54 @@ +// This file is not generated by Speakeasy. It covers intents.go. + +package prompt + +import ( + "reflect" + "testing" + + "github.com/spf13/cobra" +) + +// kbTree is the part of vf's tree a newcomer looked through to add an FAQ. +func kbTree() *cobra.Command { + op := func(use, short string) *cobra.Command { + return &cobra.Command{Use: use, Short: short, Run: func(*cobra.Command, []string) {}} + } + root := &cobra.Command{Use: "vf"} + document := &cobra.Command{Use: "document", Short: "Manage knowledge base documents and sitemaps"} + document.AddCommand(op("create-text", "Upload a file as a document"), op("create-url", "Create a new document from a URL"), + op("create-table", "Create a new document from structured data"), op("list", "List all documents"), + op("update-managed-sitemap", "Update a managed sitemap's URL patterns, refresh rate or smart chunking")) + kb := &cobra.Command{Use: "knowledge-base", Short: "Query the knowledge base", Aliases: []string{"kb"}} + kb.AddCommand(op("query", "Execute a query against documents in the knowledge base")) + agent := &cobra.Command{Use: "agent", Short: "Configure the agent"} + agent.AddCommand(op("add-workflow", "Add a workflow to the agent"), op("get", "Get the agent")) + root.AddCommand(document, kb, agent) + return root +} + +// "/upload" gave an empty menu and "/add" only agent commands (R5 #14): +// the words people use for adding to the knowledge base now find the +// commands that do it. +func TestTheMenuFindsCommandsByWhatTheyDo(t *testing.T) { + complete := Commands(kbTree(), nil) + adds := []string{"document create-table", "document create-text", "document create-url"} + cases := []struct { + line string + want []string + }{ + {"upload", adds}, + {"/upload", adds}, + {"faq", adds}, + {"kb", append([]string{"knowledge-base"}, adds...)}, // the alias first + {"add", append(append([]string{}, adds...), "agent add-workflow")}, // and the command named add-… + {"website", []string{"document create-url"}}, + {"chunk", []string{"document update-managed-sitemap"}}, // a word in a summary, when no name has it + {"doc", []string{"document"}}, // a name match keeps summaries out + } + for _, c := range cases { + if got := labels(complete(c.line)); !reflect.DeepEqual(got, c.want) { + t.Errorf("%q: got %q, want %q", c.line, got, c.want) + } + } +} From c9a0e38a2dd5746765448f671c80fad79e131898 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:11:47 -0500 Subject: [PATCH 11/31] fix(conversation): send and knowledge-base query talk to the draft unless told otherwise What was wrong: `conversation send` and `knowledge-base query` required --version-param, with no default and no word on what draft or published means, while `conversation run-script` already defaulted to draft. Left out, vf opened a draft/published picker on every turn, or failed with "missing required flag" without a terminal. The query's one example passed published, so people searched the knowledge base their live agent sees, not the one they had just added documents to. And --synthesis didn't show its default, so agents passed --synthesis=false "to be safe", not knowing whether a model call (and its credits) was on. (Round-5 sweep R5 #21 and #33: human-newcomer F6, human-kb F5, agent-builder F12, agent-migrator F6.) What changed: both commands default --version-param to draft, and its help says what each version is: draft, the latest edits (compiled first when a conversation starts; that still happens with the default), and published, what live users get since the last `vf environment publish`. --synthesis shows "(default true)", says it uses credits and reports its tokens, and that --synthesis=false makes no model call; left unset it is still not sent. The examples lead with the default and show published once. The hooks are one line in each generated file; the rest is in conversation/version.go and knowledgebase/version.go. Tests: TestSendAndQueryTalkToTheDraftByDefault, TestVersionHelpSaysWhatEachVersionIs. --- internal/cli/conversation/send.go | 1 + internal/cli/conversation/text.go | 10 +- internal/cli/conversation/version.go | 28 +++++ internal/cli/knowledgebase/query.go | 1 + internal/cli/knowledgebase/version.go | 57 +++++++++ internal/cli/versiondefault_test.go | 167 ++++++++++++++++++++++++++ 6 files changed, 260 insertions(+), 4 deletions(-) create mode 100644 internal/cli/conversation/version.go create mode 100644 internal/cli/knowledgebase/version.go create mode 100644 internal/cli/versiondefault_test.go diff --git a/internal/cli/conversation/send.go b/internal/cli/conversation/send.go index 3f8ca4ee..2e0ff428 100644 --- a/internal/cli/conversation/send.go +++ b/internal/cli/conversation/send.go @@ -34,6 +34,7 @@ func initSendCmd(parent *cobra.Command) error { Example: " vf conversation send --user-id --project-id --environment-alias --action '{\"type\":\"end\"}' --version-param draft", // text.go replaces it RunE: runSendCmd, } + draftUnlessPublished(sendCmdMeta) // version.go: --version-param defaults to draft, as run-script's does flagutil.RegisterFlags(cmd, sendCmdMeta) addNoCompileFlag(cmd) // autocompile.go: --no-compile addShowDebugFlag(cmd) // reply.go: --show-debug diff --git a/internal/cli/conversation/text.go b/internal/cli/conversation/text.go index 59a542a4..3bfb64f5 100644 --- a/internal/cli/conversation/text.go +++ b/internal/cli/conversation/text.go @@ -32,10 +32,12 @@ const ( // sendExample leads with typed words, the usual turn, then starts and ends // a conversation. Each line runs as written; an end needs a reason (see -// endaction.go). -const sendExample = ` vf conversation send --user-id --project-id --environment-alias --version-param draft --text 'What are your hours?' - vf conversation send --user-id --project-id --environment-alias --version-param draft --action '{"type":"launch"}' - vf conversation send --user-id --project-id --environment-alias --version-param draft --action '{"type":"end","payload":{"reason":"done"}}'` +// endaction.go). They talk to the draft, the default (version.go), but for +// the one that says how to talk to the published version. +const sendExample = ` vf conversation send --user-id --project-id --environment-alias --text 'What are your hours?' + vf conversation send --user-id --project-id --environment-alias --action '{"type":"launch"}' + vf conversation send --user-id --project-id --environment-alias --action '{"type":"end","payload":{"reason":"done"}}' + vf conversation send --user-id --project-id --environment-alias --version-param published --text 'What are your hours?'` // addTextFlag gives cmd --text, and examples that use it. func addTextFlag(cmd *cobra.Command) { diff --git a/internal/cli/conversation/version.go b/internal/cli/conversation/version.go new file mode 100644 index 00000000..559845f3 --- /dev/null +++ b/internal/cli/conversation/version.go @@ -0,0 +1,28 @@ +// This file is not generated by Speakeasy. It has `vf conversation send` +// talk to the draft unless told otherwise, as run-script does. +// +// send's --version-param was required, with no default and no word on which +// to pick, while run-script defaulted to draft. Talking to an agent took +// three flags every turn, and leaving --version-param out opened a +// draft/published picker each time (round-5 sweep, human-newcomer:F6, +// agent-builder:F12). Now it defaults to draft, and its help says what each +// version is. A send to the draft is compiled first when it starts a +// conversation (autocompile.go), whether draft was given or defaulted. + +package conversation + +import "github.com/voiceflow/cli/internal/flagutil" + +const sendVersionHelp = "Which version to talk to: draft, your latest edits, compiled first when a conversation starts; " + + "or published, what your live users talk to since the last 'vf environment publish'. (options: draft, published)" + +// draftUnlessPublished makes send's --version-param default to draft. It +// runs before meta's flags are registered. +func draftUnlessPublished(meta []flagutil.FlagMeta) { + for i := range meta { + if meta[i].FlagName == "version-param" { + meta[i].Required, meta[i].HasDefault, meta[i].DefaultStr = false, true, "draft" + meta[i].Description = sendVersionHelp + } + } +} diff --git a/internal/cli/knowledgebase/query.go b/internal/cli/knowledgebase/query.go index d92c7f53..cf079a71 100644 --- a/internal/cli/knowledgebase/query.go +++ b/internal/cli/knowledgebase/query.go @@ -36,6 +36,7 @@ func initQueryCmd(parent *cobra.Command) error { Example: " vf knowledge-base query --project-id --environment-alias --version-param published --question ", RunE: runQueryCmd, } + draftUnlessPublished(cmd, queryCmdMeta) // version.go: --version-param defaults to draft; --synthesis shows its default flagutil.RegisterFlags(cmd, queryCmdMeta) addShowDebugFlag(cmd) // answer.go: --show-debug if err := flagutil.ValidateMeta[operations.StableKnowledgeBaseControllerQueryRequest](queryCmdMeta); err != nil { diff --git a/internal/cli/knowledgebase/version.go b/internal/cli/knowledgebase/version.go new file mode 100644 index 00000000..43095886 --- /dev/null +++ b/internal/cli/knowledgebase/version.go @@ -0,0 +1,57 @@ +// This file is not generated by Speakeasy. It gives `vf knowledge-base +// query` the defaults a person would pick, and says what they are. +// +// --version-param was required, with no default and no word on which to +// pick: "Whether to query the draft or the published version of the +// knowledge base". Leaving it out opened a draft/published picker, and the +// help's one example passed published. A help-center editor didn't know +// whether her uploads were in "the published version of the knowledge +// base", and guessed draft (round-5 sweep, human-kb:F5, human-newcomer:F6, +// agent-builder:F12). `conversation run-script` already defaulted to draft. +// +// And --synthesis didn't show its default, so agents passed +// --synthesis=false "to be safe", not knowing whether a model call (and its +// credits) was on by default (agent-migrator:F6, agent-builder:F12). +// +// Now --version-param defaults to draft and says what each version is, and +// --synthesis shows that it is on unless turned off, and what it costs. + +package knowledgebase + +import ( + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" +) + +const ( + versionHelp = "Which version of the agent's knowledge base to search: draft, as the draft agent sees it, with the documents you just added; " + + "or published, as your live agent sees it since the last 'vf environment publish'. (options: draft, published)" + synthesisHelp = "Have a model write an answer from the chunks found. It's on unless you pass --synthesis=false, " + + "and uses credits: the answer reports its tokens. --synthesis=false returns only the chunks, with no model call." + queryExample = " vf knowledge-base query --project-id --environment-alias --question 'How long do refunds take?'\n" + + " vf knowledge-base query --project-id --environment-alias --version-param published --question 'How long do refunds take?' --synthesis=false" +) + +// draftUnlessPublished makes query's --version-param default to draft, and +// --synthesis show that it is on unless turned off. It runs before meta's +// flags are registered. +func draftUnlessPublished(cmd *cobra.Command, meta []flagutil.FlagMeta) { + for i := range meta { + switch meta[i].FlagName { + case "version-param": + meta[i].Required, meta[i].HasDefault, meta[i].DefaultStr = false, true, "draft" + meta[i].Description = versionHelp + case "synthesis": + // Left unset the API synthesizes; a default of true says so in + // help, and still sends nothing unless the flag is given. + meta[i].DefaultBool = true + meta[i].Description = synthesisHelp + } + } + if strings.Contains(cmd.Example, "--version-param published --question ") { + cmd.Example = queryExample + } +} diff --git a/internal/cli/versiondefault_test.go b/internal/cli/versiondefault_test.go new file mode 100644 index 00000000..0c1dafba --- /dev/null +++ b/internal/cli/versiondefault_test.go @@ -0,0 +1,167 @@ +package cli + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// bodyServer answers a request whose path ends in one of routes with that +// route's answer, and records each as the route and the JSON body it carried. +func bodyServer(t *testing.T, routes map[string]string) (url string, seen func() []sentRequest) { + t.Helper() + var mu sync.Mutex + var got []sentRequest + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + body := map[string]json.RawMessage{} + _ = json.Unmarshal(raw, &body) + w.Header().Set("Content-Type", "application/json") + for route, answer := range routes { + if strings.HasSuffix(r.URL.Path, route) { + mu.Lock() + got = append(got, sentRequest{route: route, body: body}) + mu.Unlock() + io.WriteString(w, answer) + return + } + } + t.Errorf("unexpected request %s %s", r.Method, r.URL) + http.NotFound(w, r) + })) + t.Cleanup(srv.Close) + return srv.URL, func() []sentRequest { + mu.Lock() + defer mu.Unlock() + return append([]sentRequest(nil), got...) + } +} + +type sentRequest struct { + route string + body map[string]json.RawMessage +} + +// runMode runs vf with args against url, in agent mode or not, and returns +// all it printed and the error. +func runMode(t *testing.T, url string, agent bool, 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("")) + mode := "--agent-mode=false" + if agent { + mode = "--agent-mode" + } + root.SetArgs(append(args, mode, "--no-interactive")) + _, err = root.ExecuteC() + return buf.String(), err +} + +// `conversation send` and `knowledge-base query` talk to the draft unless +// --version-param says published, as run-script does. Both required +// --version-param: left out, vf stopped to ask for it, or failed without a +// terminal. A send to the draft still compiles it first when it starts a +// conversation, and an unset --synthesis still sends nothing, so the API +// decides. +func TestSendAndQueryTalkToTheDraftByDefault(t *testing.T) { + routes := map[string]string{"/compile": `{"message":"Environment compiled","durationMs":5}`, "/conversation/u1": freshTurn, + "/knowledge-base/query": kbAnswer} + cases := []struct { + name string + args []string + requests string // the routes requested, in order + version string // the version the last request carried + }{ + {"send", []string{"conversation", "send", "-u", "u1", "-p", "p1", "-e", "main", "-a", `{"type":"launch"}`}, "/compile /conversation/u1", `"draft"`}, + {"send --version-param published", []string{"conversation", "send", "-u", "u1", "-p", "p1", "-e", "main", "-a", `{"type":"launch"}`, "-v", "published"}, "/conversation/u1", `"published"`}, + {"query", []string{"knowledge-base", "query", "-p", "p1", "-e", "main", "--question", "When?"}, "/knowledge-base/query", `"draft"`}, + {"query --version-param published", []string{"knowledge-base", "query", "-p", "p1", "-e", "main", "--question", "When?", "-v", "published"}, "/knowledge-base/query", `"published"`}, + } + for _, c := range cases { + for _, agent := range []bool{false, true} { + t.Run(c.name+map[bool]string{false: "", true: ", agent"}[agent], func(t *testing.T) { + url, seen := bodyServer(t, routes) + out, err := runMode(t, url, agent, c.args...) + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + got := seen() + var paths []string + for _, r := range got { + paths = append(paths, r.route) + } + if p := strings.Join(paths, " "); p != c.requests { + t.Fatalf("requests = %q, want %q\n%s", p, c.requests, out) + } + last := got[len(got)-1].body + if v := string(last["version"]); v != c.version { + t.Errorf("version = %s, want %s", v, c.version) + } + if s, ok := last["synthesis"]; ok { + t.Errorf("sent synthesis %s, which no flag asked for", s) + } + }) + } + } + + t.Run("--synthesis=false is sent", func(t *testing.T) { + url, seen := bodyServer(t, routes) + out, err := runMode(t, url, false, "knowledge-base", "query", "-p", "p1", "-e", "main", "--question", "When?", "--synthesis=false") + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + if s := string(seen()[0].body["synthesis"]); s != "false" { + t.Errorf("synthesis = %q, want false", s) + } + }) +} + +// Help says what draft and published are, that draft is the default, and +// that --synthesis is on unless turned off, and costs credits. +func TestVersionHelpSaysWhatEachVersionIs(t *testing.T) { + cases := []struct { + cmd []string + want []string + }{ + {[]string{"conversation", "send"}, []string{`(default "draft")`, "draft, your latest edits", "published, what your live users talk to"}}, + {[]string{"knowledge-base", "query"}, []string{`(default "draft")`, "draft, as the draft agent sees it", "published, as your live agent sees it", + "--synthesis", "It's on unless you pass --synthesis=false", "uses credits", "(default true)"}}, + } + for _, c := range cases { + t.Run(strings.Join(c.cmd, " "), func(t *testing.T) { + out, err := runMode(t, "http://127.0.0.1:1", false, append(c.cmd, "--help")...) + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + flat := strings.Join(strings.Fields(out), " ") + for _, w := range c.want { + if !strings.Contains(flat, w) { + t.Errorf("help doesn't say %q:\n%s", w, out) + } + } + for _, line := range strings.Split(out, "\n") { + if strings.Contains(line, "--version-param") && strings.Contains(line, "[required]") { + t.Errorf("--version-param is still required:\n%s", line) + } + } + }) + } +} From d1f3f235eb50c18ba599e8d50927239ae6096168 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:20:58 -0500 Subject: [PATCH 12/31] fix(document): the list table names each document's folder, and folder create says how to fill it What was wrong: no list showed which documents were in a folder. A document carries only its folder's 24-character ID, so `document list -o table` had a FOLDER ID column of hex (the first column left out at 80 and 100 columns), `document folder list` shows no documents, and testers matched folderID values by eye in the YAML. And after `document folder create` the only Next line was "list them": nothing said that `document update --folder-id` moves a document in. (Round-5 sweep R5 #6: human-kb F2, F3.) What changed: `document list -o table` reads the folder list once, only when a document is in a folder, and shows a FOLDER column with the folder's name, or its path when nested (FAQ/Billing). A folder the list doesn't have, or a folder list vf can't read, shows the ID as before. JSON, YAML, TOON, --jq, pretty output and agent mode print the API's answer as it came and read no folders. `document folder create` now ends with "vf document update --document-id --folder-id move a document into it" and "vf document list -o table each document's ID, and the folder it's in", ahead of "list them". A create command names its own next steps through a command annotation (output/ownsteps.go); created.go has a one-line hook for it. Not done: --folder-id on `document list`. The API's document list filters only by sitemap, not by folder. Tests: TestTheDocumentTableNamesEachFolder, TestAFolderCreateSaysHowToFillIt, TestAFolderedDocumentKeepsEveryField, TestAFolderIsNamedByItsPath, TestACreateNamesItsOwnNextSteps; TestOutputTableShowsADocumentsNameTypeAndStatus updated for the FOLDER header. --- .../cli/document/documentfolder/create.go | 1 + internal/cli/document/documentfolder/fill.go | 29 ++++ internal/cli/document/foldernames.go | 130 ++++++++++++++++++ internal/cli/document/foldernames_test.go | 61 ++++++++ internal/cli/document/list.go | 2 +- internal/cli/folders_test.go | 100 ++++++++++++++ internal/cli/tableview_test.go | 2 +- internal/output/created.go | 2 +- internal/output/ownsteps.go | 37 +++++ internal/output/ownsteps_test.go | 25 ++++ 10 files changed, 386 insertions(+), 3 deletions(-) create mode 100644 internal/cli/document/documentfolder/fill.go create mode 100644 internal/cli/document/foldernames.go create mode 100644 internal/cli/document/foldernames_test.go create mode 100644 internal/cli/folders_test.go create mode 100644 internal/output/ownsteps.go create mode 100644 internal/output/ownsteps_test.go diff --git a/internal/cli/document/documentfolder/create.go b/internal/cli/document/documentfolder/create.go index 735a3e98..741b4792 100644 --- a/internal/cli/document/documentfolder/create.go +++ b/internal/cli/document/documentfolder/create.go @@ -32,6 +32,7 @@ func initCreateCmd(parent *cobra.Command) error { RunE: runCreateCmd, } flagutil.RegisterFlags(cmd, createCmdMeta) + sayHowToFill(cmd) // fill.go: Next says how to put documents in the folder if err := flagutil.ValidateMeta[operations.StableDocumentFolderControllerCreateRequest](createCmdMeta); err != nil { return fmt.Errorf("invalid metadata for create: %w", err) } diff --git a/internal/cli/document/documentfolder/fill.go b/internal/cli/document/documentfolder/fill.go new file mode 100644 index 00000000..8f363b5b --- /dev/null +++ b/internal/cli/document/documentfolder/fill.go @@ -0,0 +1,29 @@ +// This file is not generated by Speakeasy. It has `vf document folder +// create` say how to put documents in the new folder. +// +// Its only Next line was "list them", and the folder commands don't move +// documents: `document update --folder-id` does. In the usability sweep a +// help-center editor found that only in create-text's help (round-5 sweep +// R5 #6, human-kb:F3). Now the Next lines say how to move a document in, +// with the new folder's ID filled in, and where to find documents' IDs +// (`document list -o table`, which names each one's folder: foldernames.go). + +package documentfolder + +import ( + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/output" +) + +const fillSteps = "vf document update --document-id --folder-id {id}\tmove a document into it\n" + + "vf document list -o table\teach document's ID, and the folder it's in" + +// sayHowToFill gives cmd, folder create, the next steps that fill the +// folder. output/created.go prints them after the folder. +func sayHowToFill(cmd *cobra.Command) { + if cmd.Annotations == nil { + cmd.Annotations = map[string]string{} + } + cmd.Annotations[output.NextSteps] = fillSteps +} diff --git a/internal/cli/document/foldernames.go b/internal/cli/document/foldernames.go new file mode 100644 index 00000000..22361046 --- /dev/null +++ b/internal/cli/document/foldernames.go @@ -0,0 +1,130 @@ +// This file is not generated by Speakeasy. It has `vf document list -o +// table` say which folder each document is in by the folder's name. +// +// A document carries only its folder's 24-character ID, so the table's +// FOLDER ID column was a string of hex nobody could read, and the first +// column left out at 80 and 100 columns. In the usability sweep a help-center +// editor filed three documents into "FAQ" and then couldn't see them there: +// `document folder list` shows no documents, and she matched folderID values +// by eye in the YAML (round-5 sweep R5 #6, human-kb:F2). +// +// Now the table has a FOLDER column with the folder's name, and a nested +// folder's path (FAQ/Billing). vf reads the folder list for it, once, and +// only when a document is in a folder. A folder the list doesn't have, or a +// folder list vf can't read, shows the ID, as before. JSON, YAML, TOON, --jq, +// pretty output and agent mode get the API's answer as it came. +// +// The API can't list one folder's documents (`document list` filters only by +// sitemap), so there is no --folder-id here. + +package document + +import ( + "strings" + + "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" +) + +// documentsByFolder is what `document list -o table` prints: the list, with +// each document's folder by name. output.Result prints Result. +type documentsByFolder struct { + HTTPMeta components.HTTPMetadata `json:"-"` + Result *folderedList +} + +type folderedList struct { + Documents []folderedDocument `json:"documents"` +} + +// folderedDocument is a components.StableDocument with its folder's name in +// place of its folder's ID. TestAFolderedDocumentKeepsEveryField fails when +// the API's document gains a field this doesn't carry. +type folderedDocument struct { + ID string `json:"id"` + Data *components.StableDocumentData `json:"data"` + Status components.KBDocumentStatus `json:"status"` + SmartChunking *components.StableDocumentSmartChunking `json:"smartChunking"` + Folder *string `json:"folder"` +} + +// withFolderNames is the list as output prints it: for -o table, with each +// document's folder by name; otherwise as it came. +func withFolderNames(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableDocumentControllerListRequest, res *operations.StableDocumentControllerListResponse) any { + if res == nil || res.StableDocumentListResponse == nil || client.IsDryRun(cmd) || + output.WantsRawJSON(cmd) || output.FormatOf(cmd) != "table" { + return res + } + docs := res.StableDocumentListResponse.Documents + if !anyInAFolder(docs) { + return res + } + opts, err := output.PrepareCallOpts(cmd) + if err != nil { + return res + } + folders, err := s.Document.Folder.List(cmd.Context(), operations.StableDocumentFolderControllerListRequest{ + ProjectID: req.ProjectID, EnvironmentAlias: req.EnvironmentAlias, + }, opts...) + if err != nil || folders == nil || folders.StableDocumentFolderListResponse == nil { + return res // the IDs, as before + } + return &documentsByFolder{HTTPMeta: res.HTTPMeta, Result: &folderedList{ + Documents: fileUnder(docs, folderPaths(folders.StableDocumentFolderListResponse.Folders)), + }} +} + +func anyInAFolder(docs []components.StableDocument) bool { + for _, d := range docs { + if d.FolderID != nil { + return true + } + } + return false +} + +// folderPaths maps each folder's ID to its name, after its parents' names +// for a nested one: FAQ/Billing. +func folderPaths(folders []components.StableDocumentFolder) map[string]string { + byID := map[string]components.StableDocumentFolder{} + for _, f := range folders { + byID[f.ID] = f + } + paths := map[string]string{} + for _, f := range folders { + names := []string{f.Name} + seen := map[string]bool{f.ID: true} + for parent := f.ParentID; parent != nil && !seen[*parent]; { + p, ok := byID[*parent] + if !ok { + break + } + seen[p.ID] = true + names = append([]string{p.Name}, names...) + parent = p.ParentID + } + paths[f.ID] = strings.Join(names, "/") + } + return paths +} + +// fileUnder is docs with each folder ID replaced by its path, or kept when +// paths doesn't have it. +func fileUnder(docs []components.StableDocument, paths map[string]string) []folderedDocument { + out := make([]folderedDocument, 0, len(docs)) + for _, d := range docs { + folder := d.FolderID + if folder != nil { + if path, ok := paths[*folder]; ok { + folder = &path + } + } + out = append(out, folderedDocument{ID: d.ID, Data: d.Data, Status: d.Status, SmartChunking: d.SmartChunking, Folder: folder}) + } + return out +} diff --git a/internal/cli/document/foldernames_test.go b/internal/cli/document/foldernames_test.go new file mode 100644 index 00000000..b51fa415 --- /dev/null +++ b/internal/cli/document/foldernames_test.go @@ -0,0 +1,61 @@ +package document + +import ( + "reflect" + "slices" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/sdk/models/components" +) + +func jsonNames(t reflect.Type) []string { + var names []string + for i := 0; i < t.NumField(); i++ { + if name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ","); name != "" && name != "-" { + names = append(names, name) + } + } + return names +} + +// The table prints a folderedDocument in place of the API's document, so a +// field the API's document gains must be carried, or the table drops it. +func TestAFolderedDocumentKeepsEveryField(t *testing.T) { + carried := jsonNames(reflect.TypeOf(folderedDocument{})) + for _, name := range jsonNames(reflect.TypeOf(components.StableDocument{})) { + if name != "folderID" && !slices.Contains(carried, name) { + t.Errorf("folderedDocument doesn't carry %q", name) + } + } +} + +func TestAFolderIsNamedByItsPath(t *testing.T) { + id := func(s string) *string { return &s } + paths := folderPaths([]components.StableDocumentFolder{ + {ID: "f-billing", Name: "Billing", ParentID: id("f-faq")}, + {ID: "f-faq", Name: "FAQ"}, + {ID: "f-orphan", Name: "Orphan", ParentID: id("f-gone")}, + {ID: "f-a", Name: "A", ParentID: id("f-b")}, + {ID: "f-b", Name: "B", ParentID: id("f-a")}, + }) + want := map[string]string{"f-billing": "FAQ/Billing", "f-faq": "FAQ", "f-orphan": "Orphan", "f-a": "B/A", "f-b": "A/B"} + if !reflect.DeepEqual(paths, want) { + t.Errorf("paths = %v\nwant %v", paths, want) + } + + docs := fileUnder([]components.StableDocument{ + {ID: "d1", FolderID: id("f-billing")}, {ID: "d2"}, {ID: "d3", FolderID: id("f-deleted")}, + }, paths) + var got []string + for _, d := range docs { + if d.Folder == nil { + got = append(got, d.ID+":") + } else { + got = append(got, d.ID+":"+*d.Folder) + } + } + if s := strings.Join(got, " "); s != "d1:FAQ/Billing d2: d3:f-deleted" { + t.Errorf("filed under %s", s) + } +} diff --git a/internal/cli/document/list.go b/internal/cli/document/list.go index 374f6935..87760d02 100644 --- a/internal/cli/document/list.go +++ b/internal/cli/document/list.go @@ -76,7 +76,7 @@ func runListCmd(cmd *cobra.Command, args []string) error { return output.Error(cmd, err) } - if err := output.Result(cmd, res); err != nil { + if err := output.Result(cmd, withFolderNames(cmd, s, req, res)); err != nil { // foldernames.go: -o table names each document's folder return err } return nil diff --git a/internal/cli/folders_test.go b/internal/cli/folders_test.go new file mode 100644 index 00000000..13d436e6 --- /dev/null +++ b/internal/cli/folders_test.go @@ -0,0 +1,100 @@ +package cli + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +const ( + // folderedDocs are three documents: one in a nested folder, one at the + // top level, and one in a folder the folder list doesn't have. + folderedDocs = `{"documents":[` + + `{"id":"6b0e171cef80cdc9a190df12","data":{"type":"md","name":"billing.md","canEdit":true},"status":{"type":"SUCCESS"},"smartChunking":null,"folderID":"6b0e17a9297e8fc83d56fdec"},` + + `{"id":"6b0e1751531cd7f76532bc3a","data":{"type":"table","name":"Plans","canEdit":true},"status":{"type":"SUCCESS"},"smartChunking":null,"folderID":null},` + + `{"id":"6b0e17520000000000000003","data":{"type":"md","name":"refunds.md","canEdit":true},"status":{"type":"PENDING"},"smartChunking":null,"folderID":"6b0e17a90000000000000999"}]}` + folders = `{"folders":[` + + `{"id":"6b0e17a9297e8fc83d56fdec","name":"Billing","parentID":"6b0e17a90000000000000001","createdAt":"2026-11-01T00:00:00Z","updatedAt":"2026-11-01T00:00:00Z"},` + + `{"id":"6b0e17a90000000000000001","name":"FAQ","parentID":null,"createdAt":"2026-11-01T00:00:00Z","updatedAt":"2026-11-01T00:00:00Z"}]}` +) + +// `document list -o table` names each document's folder: a document carries +// only its folder's 24-character ID, which nobody could match to a folder +// but by eye. Every other format prints the API's answer as it came, and +// reads no folders. +func TestTheDocumentTableNamesEachFolder(t *testing.T) { + routes := map[string]string{"/v1/stable/document": folderedDocs, "/v1/stable/document-folder": folders} + list := []string{"document", "list", "-p", "p1", "-e", "main"} + + for _, agent := range []bool{false, true} { + url, seen := bodyServer(t, routes) + out, err := runMode(t, url, agent, append(list, "-o", "table")...) + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + lines := strings.Split(out, "\n") + if !strings.HasSuffix(strings.TrimSpace(lines[0]), "FOLDER") || strings.Contains(out, "FOLDER ID") { + t.Errorf("the header isn't ... FOLDER:\n%s", out) + } + for _, want := range []string{"billing.md", "FAQ/Billing"} { + if !strings.Contains(lines[1], want) { + t.Errorf("row 1 doesn't say %q:\n%s", want, out) + } + } + if strings.Contains(lines[2], "6b0e17a9") { + t.Errorf("a document at the top level has a folder:\n%s", out) + } + if !strings.Contains(lines[3], "6b0e17a90000000000000999") { + t.Errorf("a folder vf can't name doesn't keep its ID:\n%s", out) + } + if len(seen()) != 2 { + t.Errorf("requests = %v, want the documents and the folders", seen()) + } + } + + for _, format := range []string{"json", "yaml", "pretty"} { + url, seen := bodyServer(t, routes) + out, err := runMode(t, url, false, append(list, "-o", format)...) + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + if len(seen()) != 1 || strings.Contains(out, "FAQ/Billing") || !strings.Contains(out, "6b0e17a9297e8fc83d56fdec") { + t.Errorf("-o %s: %d requests, and printed:\n%s", format, len(seen()), out) + } + } + + t.Run("a folder list vf can't read keeps the IDs", func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if strings.HasSuffix(r.URL.Path, "/document-folder") { + w.WriteHeader(http.StatusForbidden) + w.Write([]byte(`{"message":"Forbidden"}`)) + return + } + w.Write([]byte(folderedDocs)) + })) + t.Cleanup(srv.Close) + out, err := runMode(t, srv.URL, false, append(list, "-o", "table")...) + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + if !strings.Contains(out, "FOLDER ID") || !strings.Contains(out, "6b0e17a9297e8fc83d56fdec") { + t.Errorf("didn't keep the IDs:\n%s", out) + } + }) +} + +// After `document folder create`, Next says how to move a document into the +// new folder; the only Next line was "list them". +func TestAFolderCreateSaysHowToFillIt(t *testing.T) { + create := find(t, testRoot(t), "document", "folder", "create") + steps := create.Annotations[output.NextSteps] + for _, want := range []string{"vf document update --document-id --folder-id {id}\t", "vf document list -o table\t"} { + if !strings.Contains(steps, want) { + t.Errorf("Next doesn't say %q:\n%s", want, steps) + } + } +} diff --git a/internal/cli/tableview_test.go b/internal/cli/tableview_test.go index dfe6c10b..f213e306 100644 --- a/internal/cli/tableview_test.go +++ b/internal/cli/tableview_test.go @@ -75,7 +75,7 @@ func TestOutputTableShowsADocumentsNameTypeAndStatus(t *testing.T) { {"id":"6b0d-doc2","data":{"type":"url","name":"https://example.com/hours","url":"https://example.com/hours"},"status":{"type":"ERROR","data":{"message":"HTTP 429"}},"folderID":"f1"}]}`, "document", "list", "-p", "p1", "-e", "main") wantLines(t, lines, - "ID NAME TYPE STATUS FOLDER ID", + "ID NAME TYPE STATUS FOLDER", // a folder vf can't name keeps its ID (foldernames.go) "6b0d-doc1 faq.txt text SUCCESS", "6b0d-doc2 https://example.com/hours url ERROR f1") } diff --git a/internal/output/created.go b/internal/output/created.go index 71a299f0..34d51384 100644 --- a/internal/output/created.go +++ b/internal/output/created.go @@ -185,7 +185,7 @@ func nextSteps(cmd *cobra.Command, group, id string) []ui.Tip { {Command: with("vf project get", "--project-id "+id), Does: "see it"}, } } - var tips []ui.Tip + tips := ownSteps(cmd, id) // ownsteps.go: the command's own, such as how to fill a new folder idFlag := group + "-id" for _, sibling := range cmd.Parent().Commands() { switch { diff --git a/internal/output/ownsteps.go b/internal/output/ownsteps.go new file mode 100644 index 00000000..056d52c7 --- /dev/null +++ b/internal/output/ownsteps.go @@ -0,0 +1,37 @@ +// This file is not generated by Speakeasy. It lets a create command name +// its own next steps, ahead of the "see it" and "list them" every create +// gets (created.go). +// +// After `vf document folder create` the only Next line was `vf document +// folder list list them`, and nothing said how to put documents in the +// folder: that's `document update --folder-id`, which a help-center editor in +// the usability sweep found only in create-text's help (round-5 sweep R5 #6, +// human-kb:F3). The command that knows the way now says it. + +package output + +import ( + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/ui" +) + +// NextSteps is the annotation that holds a create command's own next +// steps: one per line, "\t", with {id} standing for +// what was made. -p and -e are added as the other next steps get them. +const NextSteps = "vf:next-steps" + +// ownSteps are the next steps cmd names for id, the thing it made. +func ownSteps(cmd *cobra.Command, id string) []ui.Tip { + var tips []ui.Tip + for _, line := range strings.Split(cmd.Annotations[NextSteps], "\n") { + command, does, ok := strings.Cut(line, "\t") + if !ok { + continue + } + tips = append(tips, ui.Tip{Command: withScope(cmd, strings.ReplaceAll(command, "{id}", id)), Does: does}) + } + return tips +} diff --git a/internal/output/ownsteps_test.go b/internal/output/ownsteps_test.go new file mode 100644 index 00000000..b43d9a70 --- /dev/null +++ b/internal/output/ownsteps_test.go @@ -0,0 +1,25 @@ +package output + +import ( + "strings" + "testing" +) + +// A create's own next steps come first, with what it made and the scope +// flags filled in, then the "see it" and "list them" every create gets. +func TestACreateNamesItsOwnNextSteps(t *testing.T) { + cmd := scoped(t, "folder", "create", map[string]string{"project-id": "p1", "environment-alias": "main"}) + cmd.Annotations = map[string]string{NextSteps: "vf folder list --folder-id {id}\tits contents\nnot a step"} + var got []string + for _, tip := range nextSteps(cmd, "folder", "f1") { + got = append(got, tip.Command+" "+tip.Does) + } + want := []string{ + "vf folder list --folder-id f1 --project-id p1 --environment-alias main its contents", + "vf folder get --folder-id f1 --project-id p1 --environment-alias main see it", + "vf folder list --project-id p1 --environment-alias main list them", + } + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Errorf("tips =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) + } +} From 312594fb35103427e3e9cbeb76172a9654d22a73 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:46:05 -0500 Subject: [PATCH 13/31] fix(errors): a command too long for the line has a line of its own, whole MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The wrapper kept a command whole only while it fitted the room left on the line. A longer one broke between its words, and vf wrote the break itself: "Pass it: vf conversation send --environment-alias main --project-id" / " 6b0e… --user-id u1 --version-param draft --text ". A copy of the missing-flag hint, the commonest one, pasted two lines, and the shell ran the first half alone, with no --user-id and no --text. Now a command is one unbreakable word to the wrapper however long it is: it moves to a line of its own after "Pass it:" and runs past the edge, where the terminal's soft wrap shows it and a copy takes it whole. That holds for a command in the accent color, a quoted one, and, with NO_COLOR, "vf" and its flags typed into a sentence (ui/commandspan.go finds where such a command ends). Found by the round-5 sweep's fix-verifier (N2) and human-poweruser (F10). --- internal/cli/helpwrap_test.go | 12 +++- internal/ui/commandspan.go | 112 ++++++++++++++++++++++++++++++++++ internal/ui/wrap.go | 50 +++++++++------ internal/ui/wrap_test.go | 30 +++++++++ 4 files changed, 181 insertions(+), 23 deletions(-) create mode 100644 internal/ui/commandspan.go diff --git a/internal/cli/helpwrap_test.go b/internal/cli/helpwrap_test.go index c269c88a..d19b3959 100644 --- a/internal/cli/helpwrap_test.go +++ b/internal/cli/helpwrap_test.go @@ -41,10 +41,10 @@ func checkWrapped(t *testing.T, unwrapped, wrapped string, width int) { if helpHeading.MatchString(line) { section = line } - // A word wider than the room it has can only have a line of its own, - // and an indented line of the description is code. + // A word or a command wider than the room it has can only have a line + // of its own, and an indented line of the description is code. code := asWritten[section] || (section == "" && strings.HasPrefix(line, " ")) - if !code && ansi.StringWidth(line) > width && len(strings.Fields(line)) > 1 { + if !code && ansi.StringWidth(line) > width && len(strings.Fields(line)) > 1 && !aCommand(line) { t.Errorf("a line is wider than %d columns: %q", width, line) } } @@ -53,6 +53,12 @@ func checkWrapped(t *testing.T, unwrapped, wrapped string, width int) { } } +// aCommand reports whether line holds just a command, perhaps quoted and +// ending a sentence: "vf document create-text --file --overwrite true." +func aCommand(line string) bool { + return ui.IsCommand(strings.Trim(strings.TrimSpace(line), "'`.,;:")) +} + // At 72 and 100 columns, help broke mid-word ("--body - reads it f" / "rom // stdin"). At a terminal it now breaks between words, and a flag's // description continues under the description. diff --git a/internal/ui/commandspan.go b/internal/ui/commandspan.go new file mode 100644 index 00000000..739389ad --- /dev/null +++ b/internal/ui/commandspan.go @@ -0,0 +1,112 @@ +// This file is not generated by Speakeasy. It finds the commands in a line +// of text, so the wrapper (wrap.go) never breaks one. +// +// The wrapper kept a command whole only while it fitted the room left on the +// line. A longer one broke between its words, and vf wrote the break itself: +// +// Pass it: vf conversation send --environment-alias main --project-id +// 6b0e16efd0b0ddfb3be6e16b --user-id u1 --version-param draft +// +// A copy of that pastes two lines, and the shell runs the first half on its +// own, with no --user-id and no --text. Now a command is one unbreakable word +// to the wrapper, however long: it moves to a line of its own and runs past +// the edge, where the terminal's soft wrap shows it and a copy takes it whole. + +package ui + +import ( + "regexp" + "strings" +) + +var ( + // commandWord is a subcommand or a plain argument: document, + // create-text, 6b0e16efd0b0ddfb3be6e16b, api-reference/authentication. + commandWord = regexp.MustCompile(`^[a-z0-9][a-z0-9._/:-]*$`) + // flagToken is a flag as typed in a command: -o, --project-id, + // --body-param.name, --text=hi. + flagToken = regexp.MustCompile(`^--?[A-Za-z][\w.\[\]-]*(?:=\S*)?$`) + // placeholder is a value to fill in: , . + placeholder = regexp.MustCompile(`^<[^\s<>]+>$`) +) + +// commandEnd is the index of the last word of the command that starts at +// words[i], or -1 when no command starts there. words are plain text. +// +// A command is "vf", or "$" and a program, then its subcommands and +// arguments, then its flags, each with its value, through a "| program …" +// after it. It ends before the first word that is none of these: in "vf +// document list --project-id shows what's there" it ends at . A +// run of plain words with no flag and no counts only up to +// four words long, so "vf compiles your draft before each turn" in a +// sentence isn't taken for one. +func commandEnd(words []string, i int) int { + if i >= len(words) || (words[i] != "vf" && words[i] != "$") { + return -1 + } + if words[i] == "$" { + if i+1 == len(words) { + return -1 + } + i++ // the program + } + end, args, marked, value := i, 0, false, false + for j := i + 1; j < len(words); j = end + 1 { + w, k := words[j], -1 + switch { + case flagToken.MatchString(w): + k, marked, value = j, true, !strings.Contains(w, "=") + case (w == "|" || w == "&&") && j+1 < len(words): + k, marked, value = j+1, true, false // the next program + case value: + k, value = quotedEnd(words, j), false + case strings.HasPrefix(w, "<"): + if k = quotedEnd(words, j); placeholder.MatchString(strings.Join(words[j:k+1], "_")) { + marked = true + } else { + k = -1 + } + case isQuoted(w): + k = quotedEnd(words, j) + case !marked && args < 5 && commandWord.MatchString(w): + k, args = j, args+1 + } + if k < 0 { + break + } + end = k + } + if !marked && end-i > 3 { + return -1 + } + return end +} + +// isQuoted reports whether w opens a quoted value: 'hello, "Hi there", `.id`. +func isQuoted(w string) bool { + return w != "" && strings.ContainsRune(`'"`+"`", rune(w[0])) +} + +// quotedEnd is the index of the word that closes the quoted value or the +// that words[j] opens ("Hi there", ), or j for a +// word that opens neither or closes its own. An unclosed one is just the +// one word. +func quotedEnd(words []string, j int) int { + w := words[j] + if !isQuoted(w) && !strings.HasPrefix(w, "<") { + return j + } + q := w[:1] + if q == "<" { + q = ">" + } + if len(w) > 1 && strings.Contains(w[1:], q) { + return j + } + for k := j + 1; k < len(words) && k < j+40; k++ { + if strings.Contains(words[k], q) { + return k + } + } + return j +} diff --git a/internal/ui/wrap.go b/internal/ui/wrap.go index 0a3c08b8..9f7c2950 100644 --- a/internal/ui/wrap.go +++ b/internal/ui/wrap.go @@ -187,16 +187,21 @@ func cutAt(s string, col int) (head, rest string) { return s, "" } -// keepTogether glues the words that must stay on one line, as long as they -// fit in room: a quoted command or flag ('vf environment list', `--jq .id`), -// a flag and its value (-o json, --body -), and a run in one color, which -// is how a terminal shows a command (vf auth login). +// keepTogether glues the words that must stay on one line: a command, however +// long (commandspan.go), and, as long as they fit in room, a flag and its +// value (-o json, --body -) and a run in one color. A command is a run in +// the accent color (vf auth login), a quoted command or flag ('vf +// environment list', `--jq .id`), or "vf" and its flags typed in a sentence. func keepTogether(s string, room int) string { words := strings.Split(s, " ") + plain := make([]string, len(words)) + for i, w := range words { + plain[i] = ansi.Strip(w) + } var out []string for i := 0; i < len(words); i++ { - end := phraseEnd(words, i) - if end > i && ansi.StringWidth(strings.Join(words[i:end+1], " ")) <= room { + end, command := phraseEnd(words, plain, i) + if end > i && (command || ansi.StringWidth(strings.Join(words[i:end+1], " ")) <= room) { out = append(out, strings.Join(words[i:end+1], glue)) i = end continue @@ -207,37 +212,42 @@ func keepTogether(s string, room int) string { } // phraseEnd is the index of the last word of the phrase that starts at -// words[i], or i when no phrase starts there. -func phraseEnd(words []string, i int) int { - plain := ansi.Strip(words[i]) +// words[i], or i when no phrase starts there; command says the phrase is a +// command, which stays whole however long it is. plain is words without +// their escapes. +func phraseEnd(words, plain []string, i int) (end int, command bool) { // A run in one color: from the word that opens it to the one that ends it. if loc := sgr.FindAllStringIndex(words[i], -1); len(loc) > 0 && !sgrReset.MatchString(words[i][loc[len(loc)-1][0]:]) { for j := i + 1; j < len(words); j++ { if sgrReset.MatchString(words[j]) { - return j + return j, commandEnd(plain, i) > i } } - return i + return i, false } // A quoted command or flag. for _, q := range []string{"'", "`"} { - inner, ok := strings.CutPrefix(plain, q) + inner, ok := strings.CutPrefix(plain[i], q) if !ok || strings.Contains(inner, q) || !(strings.HasPrefix(inner, "vf") || strings.HasPrefix(inner, "-")) { continue } - for j := i + 1; j < len(words) && j < i+8; j++ { - if strings.Contains(ansi.Strip(words[j]), q) { - return j + for j := i + 1; j < len(words) && j < i+40; j++ { + if strings.Contains(plain[j], q) { + return j, true } } - return i + return i, false + } + // A command typed into a sentence: "Pass it: vf conversation send …". + if j := commandEnd(plain, i); j > i { + return j, true } // A flag and its value. - if flagWord.MatchString(plain) && i+1 < len(words) { - next := ansi.Strip(words[i+1]) + if flagWord.MatchString(plain[i]) && i+1 < len(words) { + next := plain[i+1] if next == "-" || (next != "" && !strings.HasPrefix(next, "-") && utf8.RuneCountInString(next) <= 20) { - return i + 1 + return i + 1, false } } - return i + return i, false } diff --git a/internal/ui/wrap_test.go b/internal/ui/wrap_test.go index a2c56fb8..b4cf5198 100644 --- a/internal/ui/wrap_test.go +++ b/internal/ui/wrap_test.go @@ -75,6 +75,36 @@ func TestAColoredCommandStaysWhole(t *testing.T) { } } +// vf broke a long "Pass it:" command between its words, so a copy pasted two +// lines and the shell ran the first half alone, with no --user-id or --text. +// A command too long for the line now has a line of its own, whole, for the +// terminal to soft-wrap: colored or not, quoted or typed into a sentence. +func TestALongCommandHasALineOfItsOwn(t *testing.T) { + command := "vf conversation send --environment-alias main --project-id 6b0e16efd0b0ddfb3be6e16b --user-id u1 --version-param draft --text " + for _, color := range []bool{true, false} { + u := New(io.Discard, Options{Color: color, Decorate: true, Width: 72}) + got := ansi.Strip(" " + u.Fit("Pass it: "+u.Accent(command), 4)) + if want := " Pass it:\n " + command; got != want { + t.Errorf("color %v: got\n%s\nwant\n%s", color, got, want) + } + } + retype := "vf document create-text --file --project-id 6b0e16efd0b0ddfb3be6e16b --environment-alias " + if got := New(io.Discard, Options{Decorate: true, Width: 72}).Fit("Pass it: "+retype, 4); got != "Pass it:\n "+retype { + t.Errorf("a with a space in it should not end the command:\n%s", got) + } + for _, text := range []string{ + "Then run " + command + " to send it.", + "Then run '" + command + "' to send it.", + } { + for width := 40; width <= 140; width += 10 { + got := Wrap(text, width) + if !strings.Contains(got, strings.Trim(command, "'")) { + t.Errorf("at %d columns the command was broken:\n%s", width, got) + } + } + } +} + // A status line, the stale-build warning among them, continues under its // message, not under the glyph. func TestAStatusWrapsUnderItsMessage(t *testing.T) { From 1f611d7f2e5c5b81b07337ef761337dd41ae4181 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:58:26 -0500 Subject: [PATCH 14/31] fix(output): hints, forms, runs, values and docs pages break between words MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 240288c wrapped help, warnings and replies, but text vf printed elsewhere still ran past the terminal's edge and broke mid-word. At a terminal each now goes through the shared wrapper (ui/wrap.go), so prose breaks at its words and a command or a URL stays whole: - A hint that is a command and then prose ("vf document list --project-id 6b0e… --environment-alias main shows what's there") counted as a command, so it was left whole and broke at `--environment` / `-alias`. A command now ends where the prose starts (ui/commandspan.go). - The description above a form ("Word (" / ".docx)") and a field's description, which lipgloss broke at a hyphen ("· --" / "version-param"), in interactive/formwrap.go. - The home prompt's "Nothing is current yet … or use project" and its "is now your current project" note. - test run get's check reasons ("no disc" / "repancy"), its turns, and its summary line. - Pretty output's values and blocks: a chunk's text, a diff, a long description (output/prettywrap.go), under the value or at the block's indent. An ID or a URL too long for the room has a line of its own. - docs get's page; its code blocks and tables stay as written. Pipes, -o json and agent mode are unchanged. Found by the round-5 sweep's fix-verifier (N3), human-poweruser (F10), human-kb (F9) and human-newcomer (F10, F11). --- internal/cli/docs.go | 28 +++++++++- internal/cli/home.go | 4 +- internal/cli/test/run/runview.go | 17 +++--- internal/cli/test/run/runview_test.go | 47 ++++++++++++++++ internal/cli/wrapresidue_test.go | 78 +++++++++++++++++++++++++++ internal/interactive/formwrap.go | 19 +++++++ internal/interactive/formwrap_test.go | 31 +++++++++++ internal/interactive/interactive.go | 6 +-- internal/output/created.go | 2 +- internal/output/output.go | 2 +- internal/output/prettywrap.go | 67 +++++++++++++++++++++++ internal/output/prettywrap_test.go | 62 +++++++++++++++++++++ internal/ui/commandspan.go | 13 +++++ internal/ui/wrap.go | 8 +-- internal/ui/wrap_test.go | 26 +++++++++ 15 files changed, 392 insertions(+), 18 deletions(-) create mode 100644 internal/cli/test/run/runview_test.go create mode 100644 internal/cli/wrapresidue_test.go create mode 100644 internal/output/prettywrap.go create mode 100644 internal/output/prettywrap_test.go diff --git a/internal/cli/docs.go b/internal/cli/docs.go index 4c854d80..be78a10d 100644 --- a/internal/cli/docs.go +++ b/internal/cli/docs.go @@ -23,6 +23,7 @@ import ( "github.com/voiceflow/cli/internal/client" "github.com/voiceflow/cli/internal/flagutil" "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/ui" ) const ( @@ -210,10 +211,35 @@ func runDocsGetCmd(cmd *cobra.Command, args []string) error { } out, done := output.ResultWriter(cmd) // folds inside the home prompt defer done() - fmt.Fprintln(out, strings.TrimSpace(string(body))) + fmt.Fprintln(out, fitPage(output.UI(cmd, cmd.OutOrStdout()), strings.TrimSpace(string(body)))) return nil } +// fitPage is a docs page's markdown with its prose broken between words to +// fit the terminal. `docs get` printed the page as it came, and the terminal +// broke it mid-word: "with permissio" / "n to create". A code block and a +// table stay as written, and a URL or a command is never broken (ui/wrap.go). +// Off a terminal the page is exactly as it came. +func fitPage(u *ui.UI, page string) string { + if u.Width() <= 0 { + return page + } + lines := strings.Split(page, "\n") + code := false + for i, line := range lines { + trimmed := strings.TrimSpace(line) + if strings.HasPrefix(trimmed, "```") || strings.HasPrefix(trimmed, "~~~") { + code = !code + continue + } + if code || strings.HasPrefix(trimmed, "|") { + continue + } + lines[i] = ui.WrapLine(line, u.Width(), ui.Hang(line)) + } + return strings.Join(lines, "\n") +} + // docsPageURL normalizes a page argument (path or full URL) to its markdown // rendition URL. Full URLs are validated by their PARSED components — scheme, // host, and path — never by substring matching, and the returned URL is diff --git a/internal/cli/home.go b/internal/cli/home.go index f0909122..f158494d 100644 --- a/internal/cli/home.go +++ b/internal/cli/home.go @@ -253,14 +253,14 @@ func showCurrent(u *ui.UI) { } } 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.")) + fmt.Fprintln(os.Stderr, u.Fit(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."), 0)) // ui/wrap.go: breaks between words 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.")) + fmt.Fprintln(os.Stderr, u.Fit(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."), 0)) } // foldLines is how many lines of a result show before the rest folds away: diff --git a/internal/cli/test/run/runview.go b/internal/cli/test/run/runview.go index a07eb4ea..eec899a3 100644 --- a/internal/cli/test/run/runview.go +++ b/internal/cli/test/run/runview.go @@ -192,7 +192,7 @@ func buttons(v any) string { func writeRun(u *ui.UI, out io.Writer, run components.StableTestRun, r runLogs, debug bool) { fmt.Fprintln(out, verdict(u, run)) if run.FailReason != nil && strings.TrimSpace(*run.FailReason) != "" { - writeIndented(out, " ", u.Muted("Why: ")+*run.FailReason) + writeIndented(u, out, " ", u.Muted("Why: ")+*run.FailReason) } for _, c := range r.checks { mark := u.Success(u.Glyph(ui.Done)) @@ -203,7 +203,7 @@ func writeRun(u *ui.UI, out io.Writer, run components.StableTestRun, r runLogs, if reason == "" { reason = u.Muted("(no reason given)") } - writeIndented(out, " ", mark+" "+reason) + writeIndented(u, out, " ", mark+" "+reason) } sep := " " + u.Glyph(ui.Separator) + " " about := []string{"Run " + run.ID + " of test " + run.TestID} @@ -213,7 +213,7 @@ func writeRun(u *ui.UI, out io.Writer, run components.StableTestRun, r runLogs, if run.StartedAt != nil && run.FinishedAt != nil { about = append(about, "took "+run.FinishedAt.Sub(*run.StartedAt).Round(time.Second).String()) } - fmt.Fprintln(out, u.Muted(strings.Join(about, sep))) + fmt.Fprintln(out, u.Fit(u.Muted(strings.Join(about, sep)), 0)) if len(r.said) > 0 { fmt.Fprintln(out) @@ -234,7 +234,7 @@ func writeRun(u *ui.UI, out io.Writer, run components.StableTestRun, r runLogs, if l.agent && strings.HasPrefix(l.text, "[") { text = u.Accent(text) } - fmt.Fprintln(out, strings.TrimRight(lead+text, " ")) + fmt.Fprintln(out, strings.TrimRight(lead+u.Fit(text, len(label)), " ")) // a long turn breaks between words, under itself } } @@ -306,12 +306,15 @@ func plural(n int, noun string) string { } // writeIndented writes text with each of its lines after indent, and a -// second line lined up under the first's text. -func writeIndented(out io.Writer, indent, text string) { +// second line lined up under the first's text. At a terminal a line too +// long for it breaks between words and continues there too: a check's +// reason broke mid-word ("no disc" / "repancy"). +func writeIndented(u *ui.UI, out io.Writer, indent, text string) { for i, l := range strings.Split(strings.TrimRight(text, "\n"), "\n") { if i > 0 { l = " " + l } - fmt.Fprintln(out, strings.TrimRight(indent+l, " ")) + line := indent + l + fmt.Fprintln(out, strings.TrimRight(ui.WrapLine(line, u.Width(), ui.Hang(line)), " ")) } } diff --git a/internal/cli/test/run/runview_test.go b/internal/cli/test/run/runview_test.go new file mode 100644 index 00000000..49454bca --- /dev/null +++ b/internal/cli/test/run/runview_test.go @@ -0,0 +1,47 @@ +// This file is not generated by Speakeasy. It covers how runview.go lays a +// run out at a terminal. + +package run + +import ( + "bytes" + "io" + "strings" + "testing" + + "github.com/charmbracelet/x/ansi" + + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/ui" +) + +// A check's reason and a turn ran past the terminal's edge, which broke them +// mid-word ("no disc" / "repancy", "explicit" / "ly"). They now break +// between words, a reason under its text and a turn under the turn. +func TestARunBreaksBetweenWords(t *testing.T) { + reason := `The agent's reply exactly matches the expected output, "MANGO," so the check passes with no discrepancy at all.` + reply := "Today we have mango. You can get it explicitly without added sugar or syrup, and it uses no extra credits." + r := runLogs{checks: []check{{passed: true, reason: reason}}, said: []line{{agent: true, text: reply}}} + run := components.StableTestRun{ID: "6b0e17aa0000000000000001", TestID: "6b0e17aa0000000000000002", Status: components.StableTestRunStatusPassed} + for _, color := range []bool{false, true} { + var out bytes.Buffer + writeRun(ui.New(io.Discard, ui.Options{Color: color, Decorate: true, Width: 72}), &out, run, r, false) + got := ansi.Strip(out.String()) + for _, l := range strings.Split(got, "\n") { + if ansi.StringWidth(l) > 72 { + t.Errorf("a line is wider than 72: %q", l) + } + } + for _, words := range []string{reason, reply} { + if !strings.Contains(strings.Join(strings.Fields(got), " "), words) { + t.Errorf("%q broke mid-word:\n%s", words, got) + } + } + if !strings.Contains(got, " ✓ The agent's reply") || !strings.Contains(got, "\n the check passes") { + t.Errorf("a reason should continue under its text, at column 4:\n%s", got) + } + if !strings.Contains(got, "\nAgent Today we have mango.") || !strings.Contains(got, "\n sugar or syrup") { + t.Errorf("a turn should continue under the turn, at column 7:\n%s", got) + } + } +} diff --git a/internal/cli/wrapresidue_test.go b/internal/cli/wrapresidue_test.go new file mode 100644 index 00000000..b8ef40d0 --- /dev/null +++ b/internal/cli/wrapresidue_test.go @@ -0,0 +1,78 @@ +// This file is not generated by Speakeasy. It covers the home prompt's +// "use" text (home.go) and `docs get`'s page (docs.go) breaking between +// words at a terminal. + +package cli + +import ( + "io" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/charmbracelet/x/ansi" + + "github.com/voiceflow/cli/internal/session" + "github.com/voiceflow/cli/internal/ui" +) + +// checkFits checks that every line of got fits width, but a line of one +// word, and that got says what was written, word for word. +func checkFits(t *testing.T, written, got string, width int) { + t.Helper() + for _, line := range strings.Split(ansi.Strip(got), "\n") { + if ansi.StringWidth(line) > width && len(strings.Fields(line)) > 1 { + t.Errorf("a line is wider than %d: %q", width, line) + } + } + if a, b := strings.Fields(ansi.Strip(written)), strings.Fields(ansi.Strip(got)); strings.Join(a, " ") != strings.Join(b, " ") { + t.Errorf("the words changed:\n%s", ansi.Strip(got)) + } +} + +// The home prompt's "Nothing is current yet …" broke mid-word at 100 +// columns: "or use pro" / "ject to pick one now." +func TestTheHomeUseTextBreaksBetweenWords(t *testing.T) { + for _, flag := range session.Levels { + session.Clear(flag) + } + stderr := filepath.Join(t.TempDir(), "stderr") + f, err := os.Create(stderr) + if err != nil { + t.Fatal(err) + } + saved := os.Stderr + os.Stderr = f + showCurrent(ui.New(io.Discard, ui.Options{Color: true, Decorate: true, Width: 60})) + os.Stderr = saved + f.Close() + said, _ := os.ReadFile(stderr) + checkFits(t, "Nothing is current yet. Create or pick a workspace or project, and later commands use it; or use project to pick one now.", string(said), 60) + if !strings.Contains(ansi.Strip(string(said)), "use project") { + t.Errorf("'use project' should stay on one line:\n%s", said) + } +} + +// `docs get` printed the page as it came, and the terminal broke its prose +// mid-word ("with permissio" / "n to create"). The prose now breaks between +// words; code and tables stay as written. +func TestDocsPageBreaksBetweenWords(t *testing.T) { + code := " curl -X POST https://general-runtime.voiceflow.com/state/user/abc/interact -H 'Authorization: VF.DM.123'" + table := "| Name | What it does, in a sentence much longer than seventy columns of terminal width |" + prose := "Create an API key with permission to create and publish projects, and name it **Northstar Support** so you can find it again later." + page := "# Build an FAQ agent\n\n" + prose + "\n\n```bash\n" + code + "\n```\n\n" + table + "\n- " + prose + got := fitPage(ui.New(io.Discard, ui.Options{Decorate: true, Width: 70}), page) + for _, whole := range []string{code, table} { + if !strings.Contains(got, "\n"+whole+"\n") { + t.Errorf("%q should stay as written:\n%s", whole, got) + } + } + checkFits(t, prose, fitPage(ui.New(io.Discard, ui.Options{Decorate: true, Width: 70}), prose), 70) + if !strings.Contains(got, "\n- Create an API key with permission to create and publish projects,\n and name it") { + t.Errorf("a list item should continue under its text:\n%s", got) + } + if fitPage(ui.Plain(), page) != page { + t.Error("off a terminal the page should be as it came") + } +} diff --git a/internal/interactive/formwrap.go b/internal/interactive/formwrap.go index 94349f9c..a448f54a 100644 --- a/internal/interactive/formwrap.go +++ b/internal/interactive/formwrap.go @@ -18,6 +18,8 @@ package interactive import ( "github.com/charmbracelet/huh" "github.com/charmbracelet/lipgloss" + + "github.com/voiceflow/cli/internal/ui" ) // fieldTextWidth is how wide a field's text can be in a form formWidth() @@ -45,3 +47,20 @@ func selectHeight(options int, title, desc string) int { } return options + lines } + +// fitHeader is the command's description printed above a form, broken +// between words to fit the terminal. It was printed as one line, and the +// terminal broke it wherever its edge fell: "or Word (" / ".docx)", "--o" / +// "verwrite". +func fitHeader(s string) string { + return ui.Wrap(s, formWidth()) +} + +// fitDescription is a field's description broken between words to the +// width the field has inside its border. The theme wraps it too +// (wrapDescriptions), but lipgloss breaks at a hyphen as well as a space, +// so the flag a description ends with came out as "--" / "version-param". +// A line this leaves no wider than the field, the theme leaves alone. +func fitDescription(s string) string { + return ui.Wrap(s, fieldTextWidth(formTheme())) +} diff --git a/internal/interactive/formwrap_test.go b/internal/interactive/formwrap_test.go index 96e26850..4e9f1ad4 100644 --- a/internal/interactive/formwrap_test.go +++ b/internal/interactive/formwrap_test.go @@ -64,3 +64,34 @@ func TestALongDescriptionLeavesTheInputInView(t *testing.T) { t.Errorf("the input line isn't the field's last line:\n%s", view) } } + +// A description broke at the hyphen of the flag it ends with ("[required] · +// --" / "version-param"), and the header above a form broke mid-word ("Word +// (" / ".docx)"). Both now break between words. +func TestFormTextBreaksBetweenWords(t *testing.T) { + words := strings.Fields("Upload a file to the knowledge base as a document: text (.txt), Markdown (.md), PDF (.pdf) or Word (.docx). The file's name becomes the document's name, and --overwrite true replaces the document of that name, keeping its ID.") + for n := 1; n <= len(words); n++ { + m := flagutil.FlagMeta{FlagName: "version-param", Kind: flagutil.FlagKindString, Required: true, + Description: strings.Join(words[:n], " ") + " [required]"} + field, _ := buildFormField(m) + view := strings.Join(strings.Fields(strings.ReplaceAll(screen(t, field), "┃", " ")), " ") + if !strings.Contains(view, "· --version-param") { + t.Fatalf("the flag's name broke:\n%s", screen(t, field)) + } + for _, w := range words[:n] { + if !strings.Contains(" "+view+" ", " "+w+" ") { + t.Fatalf("%q broke:\n%s", w, screen(t, field)) + } + } + } + header := strings.Join(words, " ") + got := fitHeader(header) + for _, line := range strings.Split(got, "\n") { + if ansi.StringWidth(line) > formWidth() { + t.Errorf("a header line is wider than %d: %q", formWidth(), line) + } + } + if strings.Join(strings.Fields(got), " ") != header { + t.Errorf("the header's words changed:\n%s", got) + } +} diff --git a/internal/interactive/interactive.go b/internal/interactive/interactive.go index 3e973362..24b4d013 100644 --- a/internal/interactive/interactive.go +++ b/internal/interactive/interactive.go @@ -216,9 +216,9 @@ func printCommandHeader(cmd *cobra.Command, totalRequired, totalOptional int) { if cmd.Long != "" { longLines := strings.SplitN(cmd.Long, "\n", 2) - fmt.Fprintln(os.Stderr, descStyle.Render(longLines[0])) + fmt.Fprintln(os.Stderr, descStyle.Render(fitHeader(longLines[0]))) // formwrap.go: breaks between words } else if cmd.Short != "" { - fmt.Fprintln(os.Stderr, descStyle.Render(cmd.Short)) + fmt.Fprintln(os.Stderr, descStyle.Render(fitHeader(cmd.Short))) // formwrap.go: breaks between words } var parts []string @@ -377,7 +377,7 @@ func applyBindings(cmd *cobra.Command, bindings []flagBinding) error { // buildFormField creates a huh form field and its value binding for a FlagMeta entry. func buildFormField(m flagutil.FlagMeta) (huh.Field, flagBinding) { title := flagDisplayName(m) - desc := flagDescription(m) + desc := fitDescription(flagDescription(m)) // formwrap.go: breaks between words, not at a flag's hyphen switch m.Kind { case flagutil.FlagKindBool: diff --git a/internal/output/created.go b/internal/output/created.go index 34d51384..1f166b8b 100644 --- a/internal/output/created.go +++ b/internal/output/created.go @@ -84,7 +84,7 @@ func afterResult(cmd *cobra.Command, res interface{}) func() { 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.")) + fmt.Fprintln(os.Stderr, u.Fit(u.Muted(call+" is now your current "+group+": later commands use it. ")+u.Accent("use")+u.Muted(" changes it."), 0)) // ui/wrap.go: breaks between words } } } diff --git a/internal/output/output.go b/internal/output/output.go index fe89183b..27d365ee 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -287,7 +287,7 @@ func Result(cmd *cobra.Command, res interface{}) (err error) { if writeDone(cmd, out, content) { // done.go: an update's or a delete's message, as a ✓ line return nil } - if err := prettyPrint(out, content, colorize); err != nil { + if err := prettyPrintFor(cmd, out, content, colorize); err != nil { // prettywrap.go: a long value breaks between words at a terminal return err } } diff --git a/internal/output/prettywrap.go b/internal/output/prettywrap.go new file mode 100644 index 00000000..92555b8b --- /dev/null +++ b/internal/output/prettywrap.go @@ -0,0 +1,67 @@ +// This file is not generated by Speakeasy. It breaks pretty output's long +// values between words at a terminal. +// +// The generated printer writes a value on its key's line, and a multi-line +// value as a block under its key (prettyshape.go), one line each however +// long. At a terminal the terminal broke them wherever its edge fell: a +// knowledge-base chunk at `perfo` / `rmance`, an instructions diff at +// `search th` / `e knowledge base`. Now a line too long for the terminal +// breaks at spaces (ui/wrap.go) and continues under its own text: a value +// under the value, past its key; a block's line at the block's indent. +// +// A word too long for the room left, an ID or a URL, is never broken: it +// has a line of its own. Off a terminal (a pipe, agent mode) and in every +// other format, the output is exactly as it was. + +package output + +import ( + "bytes" + "io" + "regexp" + "strings" + + "github.com/charmbracelet/x/ansi" + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/ui" +) + +// prettyKey is the start of a pretty line up to its value: the indent, a +// list's "- ", the key and the gap after it: " - content: ". +var prettyKey = regexp.MustCompile(`^ *(?:- )?[^\s:]+: +`) + +// prettyPrintFor is prettyPrint, wrapped to the terminal's width when cmd's +// output goes to one. +func prettyPrintFor(cmd *cobra.Command, out io.Writer, content interface{}, colorize bool) error { + width := UI(cmd, cmd.OutOrStdout()).Width() // the stream, not out, which folds inside the home prompt + if width <= 0 { + return prettyPrint(out, content, colorize) + } + var buf bytes.Buffer + if err := prettyPrint(&buf, content, colorize); err != nil { + return err + } + _, err := io.WriteString(out, fitPretty(buf.String(), width)) + return err +} + +// fitPretty breaks each line of pretty, the printer's output, that is wider +// than width. +func fitPretty(pretty string, width int) string { + lines := strings.Split(pretty, "\n") + for i, line := range lines { + if ansi.StringWidth(line) <= width { + continue + } + plain := ansi.Strip(line) + hang := len(plain) - len(strings.TrimLeft(plain, " ")) // a block's line: its indent + if m := prettyKey.FindString(plain); m != "" && len(m) < len(plain) { + hang = ansi.StringWidth(m) // a value: under the value + } else if rest := strings.TrimLeft(plain, " "); strings.HasPrefix(rest, "- ") { + hang += 2 // a list's item: under the item + } + lines[i] = ui.WrapLine(line, width, hang) + } + return strings.Join(lines, "\n") +} diff --git a/internal/output/prettywrap_test.go b/internal/output/prettywrap_test.go new file mode 100644 index 00000000..fde8b5d3 --- /dev/null +++ b/internal/output/prettywrap_test.go @@ -0,0 +1,62 @@ +// This file is not generated by Speakeasy. It covers prettywrap.go. + +package output + +import ( + "bytes" + "strings" + "testing" + + "github.com/charmbracelet/x/ansi" + "github.com/spf13/cobra" +) + +// A chunk's text and a block's lines ran past the terminal's edge, which +// broke them mid-word ("perfo" / "rmance"). At a terminal they now break +// between words: a value under the value, a block's line at its indent. +func TestPrettyValuesBreakBetweenWords(t *testing.T) { + url := "https://www.voiceflow.com/docs/documentation/deploy/widget/web-chat-extensions" + doc := map[string]any{"document": map[string]any{ + "id": "6b0e171cef80cdc9a190df12", + "chunks": []any{ + map[string]any{"chunkID": "6b0e171cef80cdc9a190df13", "content": "Northwind Coffee offers three plans. The Growth plan includes priority support with a guaranteed response within four business hours, plus quarterly performance reviews. See " + url + " for details."}, + map[string]any{"chunkID": "6b0e171cef80cdc9a190df14", "content": "Refunds\nA customer can ask for a refund within thirty days of purchase, and the refund goes back to the card that paid for the order."}, + }, + }} + for _, colorize := range []bool{false, true} { + var buf bytes.Buffer + if err := prettyPrint(&buf, doc, colorize); err != nil { + t.Fatal(err) + } + written := buf.String() + got := fitPretty(written, 72) + for _, line := range strings.Split(got, "\n") { + if w := ansi.StringWidth(line); w > 72 && strings.TrimSpace(ansi.Strip(line)) != url { + t.Errorf("a line is %d wide: %q", w, ansi.Strip(line)) + } + } + if a, b := strings.Fields(ansi.Strip(written)), strings.Fields(ansi.Strip(got)); strings.Join(a, " ") != strings.Join(b, " ") { + t.Errorf("the words changed:\n%s", ansi.Strip(got)) + } + plain := ansi.Strip(got) + if !strings.Contains(plain, " content: Northwind Coffee offers three plans. The Growth plan\n includes") { + t.Errorf("a value should continue under the value:\n%s", plain) + } + if !strings.Contains(plain, "\n A customer can ask for a refund within thirty days of purchase,\n and the refund") { + t.Errorf("a block's line should continue at the block's indent:\n%s", plain) + } + } +} + +// Off a terminal nothing changes. +func TestPrettyFitsNothingWithoutAWidth(t *testing.T) { + cmd := &cobra.Command{Use: "get"} + var out bytes.Buffer + cmd.SetOut(&out) + if err := prettyPrintFor(cmd, &out, map[string]any{"content": strings.Repeat("word ", 40)}, false); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "\n") != 1 { + t.Errorf("pretty output to a pipe should not wrap:\n%s", out.String()) + } +} diff --git a/internal/ui/commandspan.go b/internal/ui/commandspan.go index 739389ad..b3cd175c 100644 --- a/internal/ui/commandspan.go +++ b/internal/ui/commandspan.go @@ -11,6 +11,12 @@ // own, with no --user-id and no --text. Now a command is one unbreakable word // to the wrapper, however long: it moves to a line of its own and runs past // the edge, where the terminal's soft wrap shows it and a copy takes it whole. +// +// And a line that was a command followed by prose ("vf document list +// --project-id 6b0e… shows what's there") counted as a command, so it was +// left unwrapped and the terminal broke it mid-word: `--environment` / +// `-alias`. Here a command ends where the prose starts, so the prose wraps +// at its words and only the command stays whole. package ui @@ -110,3 +116,10 @@ func quotedEnd(words []string, j int) int { } return j } + +// isWholeCommand reports whether text, a line's words after its indent and +// any list marker, is one command and nothing more. +func isWholeCommand(text string) bool { + words := strings.Fields(text) + return len(words) > 0 && commandEnd(words, 0) == len(words)-1 +} diff --git a/internal/ui/wrap.go b/internal/ui/wrap.go index 9f7c2950..dc27469f 100644 --- a/internal/ui/wrap.go +++ b/internal/ui/wrap.go @@ -114,8 +114,10 @@ func Hang(line string) int { // IsCommand reports whether line is a command to copy and run, after its // indent and any list marker: "vf …" or "$ …" with a flag or a -// in it, or just a few words long. A sentence that starts with vf ("vf -// document create-text takes no arguments (got …); pass …") is not one. +// in it, or just a few words long, and nothing after it. A sentence that +// starts with vf ("vf document create-text takes no arguments (got …); pass +// …"), or a command and then prose ("vf secret list --project-id shows +// what's there"), is not one (commandspan.go). func IsCommand(line string) bool { text := strings.TrimSpace(ansi.Strip(line)) text = text[len(marker.FindString(text)):] @@ -127,7 +129,7 @@ func IsCommand(line string) bool { return false } } - return !strings.HasSuffix(text, ".") && + return !strings.HasSuffix(text, ".") && isWholeCommand(text) && (strings.Contains(text, " -") || strings.Contains(text, "<") || len(strings.Fields(text)) <= 4) } diff --git a/internal/ui/wrap_test.go b/internal/ui/wrap_test.go index b4cf5198..5e8f48c9 100644 --- a/internal/ui/wrap_test.go +++ b/internal/ui/wrap_test.go @@ -105,6 +105,28 @@ func TestALongCommandHasALineOfItsOwn(t *testing.T) { } } +// A command and then prose counted as a command, so vf left the line whole +// and the terminal broke it mid-flag: "--environment" / "-alias main shows +// what's there". Now the prose wraps at its words, and the command stays +// whole. +func TestACommandThenProseWrapsAtTheProse(t *testing.T) { + command := "vf document list --project-id 6b0e16efd0b0ddfb3be6e16b --environment-alias main" + hint := command + " shows what's there, and which of them is the one with this name" + for _, color := range []bool{true, false} { + u := New(io.Discard, Options{Color: color, Decorate: true, Width: 100}) + got := ansi.Strip(" " + u.Fit(u.Accent(command)+" shows what's there, and which of them is the one with this name", 4)) + lines := strings.Split(got, "\n") + if len(lines) < 2 || !strings.HasPrefix(lines[0], " "+command+" ") { + t.Fatalf("color %v: the command should lead the first line, whole:\n%s", color, got) + } + fitsAndKeepsWords(t, " "+hint, got, 100) + } + got := Wrap(" "+hint, 72) + if lines := strings.Split(got, "\n"); len(lines) != 2 || lines[0] != " "+command || lines[1] != " shows what's there, and which of them is the one with this name" { + t.Errorf("at 72 the command should have its own line, and the prose the next:\n%s", got) + } +} + // A status line, the stale-build warning among them, continues under its // message, not under the glyph. func TestAStatusWrapsUnderItsMessage(t *testing.T) { @@ -171,6 +193,10 @@ func TestIsCommand(t *testing.T) { "vf is the Voiceflow CLI. Build, test, and operate AI agents": false, `vf document create-text takes no arguments (got "hello"); pass values with flags`: false, "Run vf project list to see them": false, + " vf document list --project-id 6b0e16efd0b0ddfb3be6e16b --environment-alias main shows what's there": false, + "vf document create-text --file --project-id 6b0e --environment-alias ": true, + `vf conversation send --text "Hi there" -p 6b0e`: true, + "vf project list -o json | jq '.[] | .id'": true, } { if got := IsCommand(line); got != want { t.Errorf("IsCommand(%q) = %v, want %v", line, got, want) From 028b01a65d409c10348489970b9b285e72430489 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:03:06 -0500 Subject: [PATCH 15/31] fix(help): wrapped help keeps its two columns at a narrow terminal Help wrapping continued each row under the description its own gap pointed to, and at 72 columns two kinds of row lost their column. A command whose name fills the padding has a one-space gap, so `secret --help`'s list-overrides summary continued at the row's indent as "version", which read as a command. And `evaluation create --help`'s longest flag is 45 columns, which left its descriptions under 24, so they fell back to the flags' indent and ran under the flags. Now a section's description column is the one its rows share, and every row continues there (helpcolumns.go). When that column leaves a description less than two-fifths of the width, the section moves it left to two-fifths, and a flag too long for it has its description on the line below. Every command's help is checked at 60, 72 and 100 columns. Found by the round-5 sweep's human-poweruser (F5, F6). --- internal/cli/helpcolumns.go | 103 +++++++++++++++++++++++++ internal/cli/helpcolumns_test.go | 126 +++++++++++++++++++++++++++++++ internal/cli/helpwrap.go | 32 +++++--- 3 files changed, 252 insertions(+), 9 deletions(-) create mode 100644 internal/cli/helpcolumns.go create mode 100644 internal/cli/helpcolumns_test.go diff --git a/internal/cli/helpcolumns.go b/internal/cli/helpcolumns.go new file mode 100644 index 00000000..3754a4ac --- /dev/null +++ b/internal/cli/helpcolumns.go @@ -0,0 +1,103 @@ +// This file is not generated by Speakeasy. It keeps help's two columns apart +// when help wraps at a narrow terminal. +// +// Help wrapping (helpwrap.go) continued each row under the description the +// row's own gap pointed to. At 72 columns two kinds of row lost their column: +// +// - A command whose name fills the padding has a one-space gap, so its +// summary continued at the row's indent and read as a command of its own: +// "list-overrides List which secrets are overridden per environment" / +// "version". +// - In `evaluation create --help` the longest flag is 45 columns, which +// leaves its descriptions too little room, so they fell back to the +// flags' indent and ran under the flags. +// +// Now a section's description column is the one its rows share, and every +// row continues there. When that column leaves a description less than +// two-fifths of the width, the section moves the column left, to two-fifths +// of the width, and a flag too long for it has its description on the line +// below, as man pages lay one out. + +package cli + +import ( + "strings" + + "github.com/charmbracelet/x/ansi" + + "github.com/voiceflow/cli/internal/ui" +) + +// layoutColumns wraps lines, one section of help after its heading, to +// width, keeping the section's two columns (see the top of this file). +func layoutColumns(lines []string, width int) []string { + col := descriptionColumn(lines) + if col == 0 { + for i, line := range lines { + lines[i] = ui.WrapLine(line, width, ui.Hang(line)) + } + return lines + } + to := col + if room := width - col; room < max(24, width*2/5) { + to = width * 2 / 5 + } + var out []string + for _, line := range lines { + plain := strings.TrimRight(ansi.Strip(line), " ") + term, text := splitAtColumn(plain, col) + switch { + case text == "": + // A blank line, or a row with no description. + out = append(out, strings.TrimRight(line, " ")) + case !strings.HasSuffix(term, " "): + // A line not set in the columns. + out = append(out, ui.WrapLine(line, width, ui.Hang(line))) + case strings.TrimSpace(term) == "": + // A row's description, continued on a line of its own. + out = append(out, ui.WrapLine(strings.Repeat(" ", to)+text, width, to)) + case to == col || ansi.StringWidth(strings.TrimRight(term, " "))+2 <= to: + out = append(out, ui.WrapLine(padTo(strings.TrimRight(term, " "), to)+text, width, to)) + default: + // A term too long for the column: its description goes below. + out = append(out, strings.TrimRight(term, " "), ui.WrapLine(strings.Repeat(" ", to)+text, width, to)) + } + } + return out +} + +// descriptionColumn is the column the descriptions of lines' rows start at: +// the one most rows' gaps point to, or 0 when no row has a gap. +func descriptionColumn(lines []string) int { + count := map[int]int{} + col := 0 + for _, line := range lines { + plain := strings.TrimRight(ansi.Strip(line), " ") + indent := len(plain) - len(strings.TrimLeft(plain, " ")) + if h := ui.Hang(plain); h > indent && h < ansi.StringWidth(plain) { + count[h]++ + if count[h] > count[col] || (count[h] == count[col] && h > col) { + col = h + } + } + } + return col +} + +// splitAtColumn splits s after its first col columns: the term and its gap, +// then the description. +func splitAtColumn(s string, col int) (term, text string) { + w := 0 + for i, r := range s { + if w >= col { + return s[:i], s[i:] + } + w += ansi.StringWidth(string(r)) + } + return s, "" +} + +// padTo is s with spaces after it to make it col columns wide. +func padTo(s string, col int) string { + return s + strings.Repeat(" ", max(0, col-ansi.StringWidth(s))) +} diff --git a/internal/cli/helpcolumns_test.go b/internal/cli/helpcolumns_test.go new file mode 100644 index 00000000..b8ba7d0b --- /dev/null +++ b/internal/cli/helpcolumns_test.go @@ -0,0 +1,126 @@ +// This file is not generated by Speakeasy. It covers helpcolumns.go. + +package cli + +import ( + "bytes" + "io" + "strconv" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +// sections splits help into its sections after their headings, keyed by +// heading, leaving out the description and the sections there to copy. +func sections(help string) (names []string, bodies map[string][]string) { + bodies = map[string][]string{} + section := "" + for _, line := range strings.Split(help, "\n") { + if helpHeading.MatchString(line) { + section = line + names = append(names, section) + continue + } + if section != "" && !asWritten[section] { + bodies[section] = append(bodies[section], line) + } + } + return names, bodies +} + +func indentOf(line string) int { return len(line) - len(strings.TrimLeft(line, " ")) } + +// checkColumns checks that wrapped, unwrapped wrapped to a terminal, keeps +// each section's two columns: a row starts at a row's indent with the name +// it started with, and every description and every line continuing one +// starts at one column, right of the names. +func checkColumns(t *testing.T, path, unwrapped, wrapped string) { + t.Helper() + names, before := sections(unwrapped) + _, after := sections(wrapped) + for _, name := range names { + col := descriptionColumn(before[name]) + if col == 0 { + continue + } + // A line at column 0 is not in the columns: "Use … for more + // information about a command." + var heads []string + terms := map[string]bool{} + rowIndent := 0 + for _, line := range before[name] { + if term, _ := splitAtColumn(line, col); strings.TrimSpace(term) != "" && indentOf(line) > 0 { + heads = append(heads, strings.Fields(line)[0]) + terms[strings.TrimRight(term, " ")] = true + rowIndent = max(rowIndent, indentOf(line)) + } + } + var got []string + column := -1 + for _, line := range after[name] { + if strings.TrimSpace(line) == "" || indentOf(line) == 0 { + continue + } + if indentOf(line) <= rowIndent { + got = append(got, strings.Fields(line)[0]) + continue + } + if column >= 0 && indentOf(line) != column { + t.Errorf("%s: %s lines continue at columns %d and %d:\n%s", path, name, column, indentOf(line), strings.Join(after[name], "\n")) + return + } + column = indentOf(line) + } + if strings.Join(got, " ") != strings.Join(heads, " ") { + t.Errorf("%s: %s should start rows %q, started %q:\n%s", path, name, heads, got, strings.Join(after[name], "\n")) + continue + } + for _, line := range after[name] { + if indentOf(line) > 0 && indentOf(line) <= rowIndent && !terms[line] && column > 0 && len(line) > column && (line[column-1] != ' ' || line[column] == ' ') { + t.Errorf("%s: %s: a description should start at column %d: %q", path, name, column, line) + } + } + } +} + +// At 72 columns `evaluation create --help`'s descriptions ran under its +// flags, and `secret --help`'s list-overrides summary continued as +// "version", which read as a command. Every command's help keeps its +// columns at 72, and at 60 and 100 too. +func TestEveryCommandsHelpKeepsItsColumns(t *testing.T) { + root := testRoot(t) + saved := helpWidth + t.Cleanup(func() { helpWidth = saved }) + render := func(c *cobra.Command, width int) string { + helpWidth = func(io.Writer) int { return width } + var out bytes.Buffer + c.SetOut(&out) + c.HelpFunc()(c, nil) + return out.String() + } + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, width := range []int{60, 72, 100} { + checkColumns(t, c.CommandPath()+" at "+strconv.Itoa(width), render(c, 0), render(c, width)) + } + for _, sub := range c.Commands() { + walk(sub) + } + } + walk(root) + + got := helpAt(t, 72, "evaluation", "create") + for _, want := range []string{ + " --body-param.boolean.description string\n A human-readable description", + " --body string Request body as JSON", + } { + if !strings.Contains(got, want) { + t.Errorf("evaluation create --help at 72 should hold %q:\n%s", want, got) + } + } + if got := helpAt(t, 72, "secret"); !strings.Contains(got, " list-overrides List which secrets are overridden per environment\n version\n") { + t.Errorf("list-overrides' summary should continue under the summaries:\n%s", got) + } +} diff --git a/internal/cli/helpwrap.go b/internal/cli/helpwrap.go index 9ec9c91b..9f2957e3 100644 --- a/internal/cli/helpwrap.go +++ b/internal/cli/helpwrap.go @@ -69,20 +69,34 @@ func writeWrapped(out io.Writer, width int, write func(io.Writer)) { io.WriteString(out, wrapHelpText(buf.String(), width)) //nolint:errcheck // help to a terminal } -// wrapHelpText wraps help, section by section (see the top of this file). +// wrapHelpText wraps help, section by section (see the top of this file). A +// section of rows keeps its two columns (helpcolumns.go). func wrapHelpText(help string, width int) string { lines := strings.Split(help, "\n") - section := "" // the description, before the first heading - for i, line := range lines { - plain := strings.TrimRight(ansi.Strip(line), " ") + var out []string + section, start := "", 0 // the description, before the first heading + flush := func(end int) { + body := lines[start:end] switch { - case helpHeading.MatchString(plain): - section = plain case asWritten[section]: - case section == "" && strings.HasPrefix(plain, " "): + case section == "": + for i, line := range body { + if !strings.HasPrefix(ansi.Strip(line), " ") { + body[i] = ui.WrapLine(line, width, ui.Hang(line)) + } + } default: - lines[i] = ui.WrapLine(line, width, ui.Hang(line)) + body = layoutColumns(body, width) + } + out = append(out, body...) + } + for i, line := range lines { + if plain := strings.TrimRight(ansi.Strip(line), " "); helpHeading.MatchString(plain) { + flush(i) + out = append(out, line) + section, start = plain, i+1 } } - return strings.Join(lines, "\n") + flush(len(lines)) + return strings.Join(out, "\n") } From 2be15c13e2a7e2742c838b22e5d0d948ca70c8cc Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:11:19 -0500 Subject: [PATCH 16/31] fix(output): a narrow table keeps the ID, the name and what says what a row is A table too wide for the terminal left out its last columns in the API's order and cut the widest. At 72 columns event list dropped GOES TO and REQUEST NAME but kept CREATED AT, test run search dropped PASSED CHECKS, document list kept a mostly empty TITLE over FOLDER ID, and a secret's NAME was cut mid-word (SALESFORCE_OAUTH_CLIEN...). Now times go first, then mostly empty columns, true/false columns, other things' IDs and long text, then the rest. The row's ID and its name stay whole; the name is cut only when the two alone don't fit. The note still names what was left out. Pipes, -o json and agent mode are unchanged. --- internal/output/tablefit.go | 197 +++++++++++++++++++++++++++++++ internal/output/tablefit_test.go | 108 +++++++++++++++++ internal/output/tableview.go | 12 +- 3 files changed, 307 insertions(+), 10 deletions(-) create mode 100644 internal/output/tablefit.go create mode 100644 internal/output/tablefit_test.go diff --git a/internal/output/tablefit.go b/internal/output/tablefit.go new file mode 100644 index 00000000..ae1836a9 --- /dev/null +++ b/internal/output/tablefit.go @@ -0,0 +1,197 @@ +// This file is not generated by Speakeasy. It chooses which columns a table +// keeps when it doesn't fit the terminal. +// +// A table too wide for the terminal left out its last columns, in the API's +// order, and cut its widest. So at 72 columns `event list` kept its +// timestamps' neighbours and dropped GOES TO, `test run search` dropped +// PASSED CHECKS, `document list` kept a mostly empty TITLE and dropped +// FOLDER ID, and NAME was cut mid-word (`SALESFORCE_OAUTH_CLIEN…`) beside +// an ID that never is. +// +// Now the columns that say least go first: times, then columns most rows +// leave empty, then true/false columns, then IDs of other things, then long +// text, then the rest, the widest first. A long text that stays is cut to +// fit, as before. The row's own ID and its name stay, and stay whole: the ID +// is what the next command takes, and a cut ID can't be pasted. The name is +// cut only when the ID and the name alone don't fit. The note under the +// table names what was left out, and -o json still shows everything. + +package output + +import ( + "regexp" + "sort" + "strings" + + "github.com/charmbracelet/x/ansi" +) + +// timestamp is a cell that holds a time: 2026-12-01T00:47:30Z. +var timestamp = regexp.MustCompile(`^\d{4}-\d\d-\d\d[T ]\d\d:\d\d`) + +// longText is how wide a column's widest cell is for it to be long text. +const longText = 40 + +// fitTable fits table, a header and its rows, to width: it chooses the +// columns to keep and how wide each is (see the top of this file). It +// returns the table of the kept columns, their widths, and the headers of +// the columns left out. A width of 0 keeps everything as it is. +func fitTable(cols []column, table [][]string, width int) (kept [][]string, widths []int, hidden []string) { + natural := naturalWidths(table) + if width <= 0 { + return table, natural, nil + } + own, name := keyColumns(cols) + order, tiers := dropOrder(cols, table[1:], own, name) + floors := make([]int, len(cols)) + for i, c := range cols { + floors[i] = natural[i] + if !isIDColumn(c) && i != name && tiers[i] != timeTier { + floors[i] = min(natural[i], max(ansi.StringWidth(c.header), minCell)) // an ID, the name and a time are never cut + } + } + sort.Slice(order, func(a, b int) bool { // by tier, then the widest first + i, j := order[a], order[b] + if tiers[i] != tiers[j] { + return tiers[i] < tiers[j] + } + if floors[i] != floors[j] { + return floors[i] > floors[j] + } + return i > j + }) + + keep := make([]bool, len(cols)) + for i := range keep { + keep[i] = true + } + total := func() int { + sum := -columnGap + for i, k := range keep { + if k { + sum += floors[i] + columnGap + } + } + return sum + } + for _, i := range order { + if total() <= width { + break + } + keep[i] = false + } + if over := total() - width; over > 0 && name >= 0 { + floors[name] = max(min(natural[name], minCell), floors[name]-over) // only now is the name cut + } + + var index []int + for i, k := range keep { + if k { + index = append(index, i) + widths = append(widths, natural[i]) + } else { + hidden = append(hidden, cols[i].header) + } + } + excess := columnGap*(len(widths)-1) - width + for _, w := range widths { + excess += w + } + for ; excess > 0; excess-- { + widest := -1 + for j, w := range widths { + if w > floors[index[j]] && (widest < 0 || w > widths[widest]) { + widest = j + } + } + if widest < 0 { + break + } + widths[widest]-- + } + for _, row := range table { + cells := make([]string, len(index)) + for j, i := range index { + cells[j] = row[i] + } + kept = append(kept, cells) + } + return kept, widths, hidden +} + +// keyColumns are the indexes of the row's own ID and of its name (or its +// title), or -1 for one a row doesn't have. +func keyColumns(cols []column) (own, name int) { + own, name = -1, -1 + for i, c := range cols { + leaf := c.path[len(c.path)-1] + switch { + case own < 0 && len(c.path) == 1 && leaf == "id": + own = i + case name < 0 && leaf == "name": + name = i + } + } + if name < 0 { + for i, c := range cols { + if c.path[len(c.path)-1] == "title" { + return own, i + } + } + } + return own, name +} + +// The tiers columns are left out in, the one that says least first. +const ( + timeTier = iota + emptyTier + flagTier + otherIDTier + longTextTier + restTier +) + +// dropOrder is the columns that may be left out, all but the row's own ID +// and its name, and each one's tier: a time, mostly empty, true/false, the +// ID of something else, long text, or the rest. +func dropOrder(cols []column, rows [][]string, own, name int) (order []int, tiers map[int]int) { + tier := func(i int) int { + empty, flags, times, widest := 0, 0, 0, 0 + for _, row := range rows { + cell := row[i] + widest = max(widest, ansi.StringWidth(cell)) + switch { + case cell == "": + empty++ + case cell == "true" || cell == "false": + flags++ + case timestamp.MatchString(cell): + times++ + } + } + filled := len(rows) - empty + leaf := cols[i].path[len(cols[i].path)-1] + switch { + case strings.HasSuffix(leaf, "At") || (filled > 0 && times == filled): + return timeTier + case empty*2 > len(rows): + return emptyTier + case filled > 0 && flags == filled: + return flagTier + case isIDColumn(cols[i]): + return otherIDTier + case widest > longText: + return longTextTier + } + return restTier + } + tiers = map[int]int{} + for i := range cols { + if i != own && i != name { + order = append(order, i) + tiers[i] = tier(i) + } + } + return order, tiers +} diff --git a/internal/output/tablefit_test.go b/internal/output/tablefit_test.go new file mode 100644 index 00000000..363ce53c --- /dev/null +++ b/internal/output/tablefit_test.go @@ -0,0 +1,108 @@ +// This file is not generated by Speakeasy. It covers tablefit.go. + +package output + +import ( + "encoding/json" + "sort" + "strconv" + "strings" + "testing" +) + +// decoded is s, a response's JSON, as a value to print. Its keys print in +// order, so its columns are in that order, then id, name and the like first. +func decoded(t *testing.T, s string) any { + t.Helper() + var v any + if err := json.Unmarshal([]byte(s), &v); err != nil { + t.Fatal(err) + } + return v +} + +// sorted is words sorted, then joined. +func sorted(words []string) string { + words = append([]string(nil), words...) + sort.Strings(words) + return strings.Join(words, "|") +} + +const ts = `"2026-12-01T00:39:35.000Z"` + +// narrowTables are human-poweruser:F9's and human-kb:F2's lists. +var narrowTables = map[string]string{ + "secrets": `{"secrets":[ + {"id":"6b0e17470369ea7ad5c777f5","name":"STRIPE_API_KEY","visibility":"masked","hasValue":true,"createdAt":` + ts + `,"updatedAt":` + ts + `}, + {"id":"6b0e17470369ea7ad5c777f6","name":"SALESFORCE_OAUTH_CLIENT_SECRET","visibility":"masked","hasValue":false,"createdAt":` + ts + `,"updatedAt":` + ts + `}]}`, + "runs": `{"runs":[ + {"id":"6b0e17aa0000000000000001","status":"passed","testID":"6b0e17aa0000000000000002","totalChecks":2,"passedChecks":2,"totalCredits":1.0055,"createdAt":` + ts + `,"finishedAt":` + ts + `}, + {"id":"6b0e17aa0000000000000003","status":"failed","testID":"6b0e17aa0000000000000004","totalChecks":3,"passedChecks":1,"totalCredits":2.5,"createdAt":` + ts + `,"finishedAt":` + ts + `}]}`, + "documents": `{"documents":[ + {"id":"6b0e171cef80cdc9a190df12","data":{"name":"billing.md","title":"","type":"md"},"status":{"type":"SUCCESS"},"folderID":"6b0e17a9297e8fc83d56fdec"}, + {"id":"6b0e1751531cd7f76532bc3a","data":{"name":"Plans","title":"Plans and prices","type":"table"},"status":{"type":"SUCCESS"},"folderID":null}, + {"id":"6b0e177e4eb600496d834e07","data":{"name":"refunds.md","type":"md"},"status":{"type":"ERROR"},"folderID":"6b0e17a9297e8fc83d56fdec"}]}`, + "events": `{"events":[ + {"id":"6b0e177ad0b0ddfb3be6e2d9","name":"Cart Abandoned","requestName":"cart_abandoned","description":"Fired by the shop when a cart sits idle for an hour after checkout started","goesTo":"global_agent","isSystem":false,"createdAt":` + ts + `}, + {"id":"6b0e177ad0b0ddfb3be6e2da","name":"Order Shipped","requestName":"order_shipped","description":"Fired when a parcel ships","goesTo":"flow","isSystem":false,"createdAt":` + ts + `}]}`, +} + +// At 72 columns a table kept its IDs and dropped the columns that say what +// a row is (GOES TO, PASSED CHECKS, FOLDER ID), and cut the name +// (SALESFORCE_OAUTH_CLIEN…). Now times, mostly empty columns, true/false +// columns, other things' IDs and long text go first, and the row's ID and +// its name stay whole. +func TestANarrowTableKeepsWhatSaysWhatARowIs(t *testing.T) { + for _, c := range []struct { + table string + width int + header string + left string + }{ + {"secrets", 72, "ID|NAME|VISIBILITY", "HAS VALUE|CREATED AT|UPDATED AT"}, + {"secrets", 100, "ID|NAME|VISIBILITY|HAS VALUE", "CREATED AT|UPDATED AT"}, + {"runs", 72, "ID|STATUS|TOTAL CHECKS|PASSED CHECKS", "TEST ID|TOTAL CREDITS|CREATED AT|FINISHED AT"}, + {"documents", 80, "ID|NAME|TYPE|STATUS|FOLDER ID", "TITLE"}, + {"events", 100, "ID|NAME|REQUEST NAME|GOES TO|DESCRIPTION|IS SYSTEM", "CREATED AT"}, + {"events", 72, "ID|NAME|REQUEST NAME|GOES TO", "DESCRIPTION|IS SYSTEM|CREATED AT"}, + } { + out, err := tableAt(t, decoded(t, narrowTables[c.table]), c.width) + if err != nil { + t.Fatal(err) + } + lines := strings.Split(strings.TrimRight(out, "\n"), "\n") + if got, want := sorted(columnsOf(lines[0])), sorted(strings.Split(c.header, "|")); got != want { + t.Errorf("%s at %d: columns %s, want %s:\n%s", c.table, c.width, got, want, out) + } + lead := "(Left out to fit " + strconv.Itoa(c.width) + " columns: " + note := strings.ReplaceAll(out[max(0, strings.Index(out, lead)):], "\n", " ") + note, _, _ = strings.Cut(strings.TrimPrefix(note, lead), ".") + if got, want := sorted(strings.Split(note, ", ")), sorted(strings.Split(c.left, "|")); got != want { + t.Errorf("%s at %d: the note names %s, want %s:\n%s", c.table, c.width, got, want, out) + } + for _, line := range lines { + if n := len([]rune(line)); n > c.width { + t.Errorf("%s at %d: a line is %d wide:\n%s", c.table, c.width, n, out) + } + } + if strings.Contains(lines[0], "CREATED AT") && !strings.Contains(out, "2026-12-01T00:39:35.000Z") { + t.Errorf("%s at %d: a time should be whole or left out:\n%s", c.table, c.width, out) + } + } + out, _ := tableAt(t, decoded(t, narrowTables["secrets"]), 72) + if !strings.Contains(out, "SALESFORCE_OAUTH_CLIENT_SECRET") || !strings.Contains(out, "6b0e17470369ea7ad5c777f6") { + t.Errorf("the name and the ID should be whole:\n%s", out) + } +} + +// The name is cut only when the ID and the name alone don't fit, and the +// ID never is. +func TestATableCutsTheNameOnlyWhenItMust(t *testing.T) { + out, err := tableAt(t, decoded(t, narrowTables["secrets"]), 50) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(out, "6b0e17470369ea7ad5c777f6 SALESFORCE_OAUTH_CLIENT…\n") { + t.Errorf("at 50 the name should be cut to fit beside the whole ID:\n%s", out) + } +} diff --git a/internal/output/tableview.go b/internal/output/tableview.go index 20859ae4..173bdbff 100644 --- a/internal/output/tableview.go +++ b/internal/output/tableview.go @@ -325,19 +325,11 @@ func printRows(out io.Writer, items []any, width int) error { table = append(table, cells) } - natural := naturalWidths(table) - floors := make([]int, len(cols)) - for i, c := range cols { - floors[i] = natural[i] - if !isIDColumn(c) { - floors[i] = min(natural[i], max(ansi.StringWidth(c.header), minCell)) - } - } - widths := fitWidths(natural, floors, width, 1) + table, widths, hidden := fitTable(cols, table, width) // tablefit.go: what says least goes first; the ID and the name stay whole if err := writeTable(out, table, widths); err != nil { return err } - if hidden := headers[len(widths):]; len(hidden) > 0 { + if len(hidden) > 0 { note := fmt.Sprintf("(Left out to fit %d columns: %s. -o json shows everything)", width, strings.Join(hidden, ", ")) _, err := fmt.Fprintln(out, ansi.Wordwrap(note, width, "")) return err From 528617602f91f590e0ebb70b33916827a70b8c95 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:16:49 -0500 Subject: [PATCH 17/31] fix(help): a described JSON flag says what JSON it takes A JSON flag showed its shape only when the spec gave it no description. --playbooks and --workflows on agent update said what the list is for and that it replaces the stored one, but not what an item holds; only the error on a wrong value gave [{ ..., playbookID: string }]. 54 flags were like that. Now the spec's words come first, then 'JSON: ', the same shape the error gives. Their words still name vf commands; the shape's keys are left as typed. --- internal/cli/barehelp_test.go | 27 ++++++++++++++++++++++++++- internal/flagutil/description.go | 21 +++++++++++++++------ 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/internal/cli/barehelp_test.go b/internal/cli/barehelp_test.go index 9d30c2e7..d0ea3095 100644 --- a/internal/cli/barehelp_test.go +++ b/internal/cli/barehelp_test.go @@ -1,5 +1,5 @@ // This file is not generated by Speakeasy. It covers barehelp.go and the -// JSON shapes flagutil/description.go gives undescribed JSON flags. +// JSON shapes flagutil/description.go gives JSON flags. package cli @@ -62,6 +62,31 @@ func TestFlagsTheSpecLeftUndescribedSayWhatTheyAre(t *testing.T) { } } + // R5 #40: a JSON flag the spec described gave no shape, though the error + // on a wrong value did. It now says what it's for, then what it takes, + // and its words still name vf's commands. + for _, tc := range []struct { + path []string + flag, lead string + keys []string + }{ + {[]string{"agent", "update"}, "playbooks", "Playbooks available for the agent to invoke. This list REPLACES the registry", []string{"JSON: [{ condition?: {", "description: string | null", "playbookID: string }]"}}, + {[]string{"agent", "update"}, "workflows", "Workflows available for the agent to invoke. This list REPLACES the registry", []string{"JSON: [{ condition?: {", "workflowID: string }]"}}, + {[]string{"agent", "update-workflow"}, "required-variables", "Replaces the stored list. Keep the id of each variable you keep, as read with 'vf agent get'.", []string{"JSON: [{ id?: string, description: string | null, variableOrEntityID: string | null }]"}}, + {[]string{"persona", "create"}, "items", "The variable values this persona presets.", []string{"JSON: [{ variable: string, value: string | null }]"}}, + } { + f := find(t, root, tc.path...).Flags().Lookup(tc.flag) + if f == nil || !strings.HasPrefix(f.Usage, tc.lead) { + t.Errorf("vf %s --%s should start with what it's for, %q: %q", strings.Join(tc.path, " "), tc.flag, tc.lead, helpOfFlag(f)) + continue + } + for _, key := range tc.keys { + if !strings.Contains(f.Usage, key) { + t.Errorf("vf %s --%s lacks %q: %q", strings.Join(tc.path, " "), tc.flag, key, f.Usage) + } + } + } + // update-variant's --text says what add-variant's does. add := find(t, root, "message", "add-variant").Flags().Lookup("text") update := find(t, root, "message", "update-variant").Flags().Lookup("text") diff --git a/internal/flagutil/description.go b/internal/flagutil/description.go index ee08544b..7e8e2c91 100644 --- a/internal/flagutil/description.go +++ b/internal/flagutil/description.go @@ -170,9 +170,13 @@ func describe(name string, kind FlagKind, description string) string { // description for: what kind of JSON, which says less than its shape. var shapeOnly = map[string]bool{"": true, "JSON object": true, "list of values": true} -// describeShape gives JSON flag name on cmd, of type t, the JSON it takes -// when the spec said only "JSON object", or nothing: --settings showed -// "JSON object", and now `JSON: { model?: …, maxTokens?: number, … }`. +// describeShape gives JSON flag name on cmd, of type t, the JSON it takes. +// Where the spec said only "JSON object", or nothing, the shape is the +// help: --settings showed "JSON object", and now `JSON: { model?: …, +// maxTokens?: number, … }`. Where the spec said what the flag is for, the +// shape follows it: --playbooks said what playbooks are for and that the +// list replaces the stored one, but not what an item holds, which only the +// error on a wrong value gave. func describeShape(cmd *cobra.Command, name string, t reflect.Type) { f := cmd.Flags().Lookup(name) if f == nil { @@ -180,14 +184,19 @@ func describeShape(cmd *cobra.Command, name string, t reflect.Type) { } text, required := strings.CutSuffix(strings.TrimSpace(f.Usage), "[required]") shape := jsonShape(t) - if !shapeOnly[strings.TrimSpace(text)] || shape == "" { + if shape == "" { return } - f.Usage = "JSON: " + shape + text = strings.TrimSpace(text) + if shapeOnly[text] { + f.Usage = "JSON: " + shape + _ = cmd.Flags().SetAnnotation(name, usage.OwnHelp, []string{"true"}) // its keys are keys, not flags (namehelp.go) + } else { + f.Usage = text + " JSON: " + shape // the spec's words still name vf's commands (namehelp.go); a shape's keys never matched one + } if required { f.Usage += " [required]" } - _ = cmd.Flags().SetAnnotation(name, usage.OwnHelp, []string{"true"}) // its keys are keys, not flags (namehelp.go) } // booleanOrEnum is a union of a boolean and its string form, which the From 835005dda23d7c6cf68b177017df97508e7534c5 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:20:15 -0500 Subject: [PATCH 18/31] fix(help): function create and update show what the code looks like Help said only that --code is the JavaScript run when the function runs, with the example --code . What the code exports, where its inputs arrive and how it returns outputs and picks a path were in the docs alone: one tester spent three calls finding them, and code written from a guess fails only when it runs. Both commands' help now shows the smallest function that works (export default async function main(args), args.inputVars, outputVars, next.path), the commands that declare its variables and paths, and the docs page with the whole contract. --- internal/cli/function/codehelp.go | 35 ++++++++++++++++++++ internal/cli/function/codehelp_test.go | 46 ++++++++++++++++++++++++++ internal/cli/function/create.go | 1 + internal/cli/function/update.go | 1 + 4 files changed, 83 insertions(+) create mode 100644 internal/cli/function/codehelp.go create mode 100644 internal/cli/function/codehelp_test.go diff --git a/internal/cli/function/codehelp.go b/internal/cli/function/codehelp.go new file mode 100644 index 00000000..ca34c1aa --- /dev/null +++ b/internal/cli/function/codehelp.go @@ -0,0 +1,35 @@ +// This file is not generated by Speakeasy. It has `function create --help` +// show what the code it takes looks like. +// +// Help said only "The JavaScript source code executed when the function +// runs", with the example `--code `. What the code exports, where its +// inputs arrive (args.inputVars) and how it returns outputs (outputVars) and +// picks a path (next.path) were in the docs alone, so a coder looked them up +// with three more calls, and one who guessed wrote code that failed only when +// it ran. Help now shows the smallest function that works and where the rest +// is. + +package function + +import "github.com/spf13/cobra" + +// codeContract is what a function's code looks like. Each paragraph is one +// line, which help wraps to the terminal; the code is indented, which it +// leaves as written. +const codeContract = `The code exports one async function. It reads its inputs from args.inputVars and returns its outputs as outputVars and, for a function with paths, the path to take as next.path: + + export default async function main(args) { + const { order_number } = args.inputVars; + return { + outputVars: { status: "shipped" }, + next: { path: "success" }, + }; + } + +Declare its inputs and outputs with 'vf function variable create' and its paths with 'vf function path create'. 'vf function check' runs it on test cases. The whole contract: 'vf docs get documentation/build/tools/function-tool'.` + +// describeCode adds what the code looks like to the help of cmd, a command +// that takes --code. +func describeCode(cmd *cobra.Command) { + cmd.Long += "\n\n" + codeContract +} diff --git a/internal/cli/function/codehelp_test.go b/internal/cli/function/codehelp_test.go new file mode 100644 index 00000000..8ca8a2e9 --- /dev/null +++ b/internal/cli/function/codehelp_test.go @@ -0,0 +1,46 @@ +// This file is not generated by Speakeasy. It covers codehelp.go. + +package function + +import ( + "strings" + "testing" + + "github.com/spf13/cobra" +) + +// R5 #39: `function create --help` said only "The JavaScript source code +// executed when the function runs". It now shows the code's shape and where +// the rest of the contract is, as `function update --help` does. +func TestFunctionHelpShowsWhatTheCodeLooksLike(t *testing.T) { + parent := &cobra.Command{Use: "function"} + if err := initCreateCmd(parent); err != nil { + t.Fatal(err) + } + if err := initUpdateCmd(parent); err != nil { + t.Fatal(err) + } + for _, c := range parent.Commands() { + for _, want := range []string{ + "export default async function main(args) {", + "args.inputVars", + "outputVars:", + "next: { path:", + "'vf function variable create'", + "'vf function path create'", + "'vf docs get documentation/build/tools/function-tool'", + } { + if !strings.Contains(c.Long, want) { + t.Errorf("function %s --help should hold %q:\n%s", c.Name(), want, c.Long) + } + } + if first, _, _ := strings.Cut(c.Long, "\n"); strings.Contains(first, "code") { + t.Errorf("function %s --help should still start with what it does: %q", c.Name(), first) + } + for _, line := range strings.Split(c.Long, "\n") { + if strings.HasPrefix(line, " ") && len(line) > 72 { + t.Errorf("function %s --help: code is left as written, so it should fit 72 columns: %q", c.Name(), line) + } + } + } +} diff --git a/internal/cli/function/create.go b/internal/cli/function/create.go index 960d5ac8..fab80572 100644 --- a/internal/cli/function/create.go +++ b/internal/cli/function/create.go @@ -35,6 +35,7 @@ func initCreateCmd(parent *cobra.Command) error { } flagutil.RegisterFlags(cmd, createCmdMeta) flagutil.ReadsText(cmd, "code") // flagutil/textfile.go: @file and - read the text + describeCode(cmd) // codehelp.go: help shows what the code looks like if err := flagutil.ValidateMeta[operations.StableFunctionControllerCreateRequest](createCmdMeta); err != nil { return fmt.Errorf("invalid metadata for create: %w", err) } diff --git a/internal/cli/function/update.go b/internal/cli/function/update.go index d67c3366..6721e97e 100644 --- a/internal/cli/function/update.go +++ b/internal/cli/function/update.go @@ -37,6 +37,7 @@ func initUpdateCmd(parent *cobra.Command) error { } flagutil.RegisterFlags(cmd, updateCmdMeta) flagutil.ReadsText(cmd, "code") // flagutil/textfile.go: @file and - read the text + describeCode(cmd) // codehelp.go: help shows what the code looks like if err := flagutil.ValidateMeta[operations.StableFunctionControllerUpdateRequest](updateCmdMeta); err != nil { return fmt.Errorf("invalid metadata for update: %w", err) } From 43d5be2ef77b021b2db23f204147ce79890be8bc Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:24:19 -0500 Subject: [PATCH 19/31] fix(output): document list at a terminal is a line per document The default output gave each document about fifteen lines of YAML (data, folderID, id, smartChunking, then status under its own key). Six documents folded behind '... +68 lines', and finding which were ready meant scrolling past chunking settings. -o table showed them on six lines, for whoever knew to ask. At a terminal document list now prints its table: ID, name, type, status and folder, fitted to the width. An empty list, a pipe, -o yaml/json and agent mode print what they did. --- internal/output/listtable.go | 70 +++++++++++++++++++++++++++++++ internal/output/listtable_test.go | 54 ++++++++++++++++++++++++ internal/output/output.go | 3 ++ 3 files changed, 127 insertions(+) create mode 100644 internal/output/listtable.go create mode 100644 internal/output/listtable_test.go diff --git a/internal/output/listtable.go b/internal/output/listtable.go new file mode 100644 index 00000000..e14dae1d --- /dev/null +++ b/internal/output/listtable.go @@ -0,0 +1,70 @@ +// This file is not generated by Speakeasy. It has `document list` print a +// line per document at a terminal. +// +// The default output gave each document about fifteen lines of YAML: data, +// folderID, id, the smartChunking settings, then status under its own key. +// Six documents ran past a screen (`… +68 lines · ctrl-o to show them`), and +// checking which ones were ready meant scrolling past chunking settings to +// each status. `-o table` showed all six on six lines, but only for whoever +// knew to ask for it. At a terminal the list is now that table. A pipe, -o +// yaml and agent mode get what they got. + +package output + +import ( + "bytes" + "io" + + "github.com/spf13/cobra" +) + +// tableAtTerminal are the commands whose default output at a terminal is +// their -o table. +var tableAtTerminal = map[string]bool{"vf document list": true} + +// writeListTable writes content, the result of cmd, as its table when cmd +// is one of tableAtTerminal and a person is reading. It reports whether it +// wrote it; a result with no table to show falls back to the usual output. +func writeListTable(cmd *cobra.Command, out io.Writer, content any) bool { + if !UI(cmd, cmd.OutOrStdout()).Decorated() { + return false + } + table, ok := listTable(cmd.CommandPath(), content, tableWidth(cmd)) + if ok { + _, _ = io.WriteString(out, table) + } + return ok +} + +// listTable is content, the result of the command at path, as the table a +// terminal width columns wide shows, when the command is one of +// tableAtTerminal and the result has rows. An empty list prints as before. +func listTable(path string, content any, width int) (string, bool) { + if !tableAtTerminal[path] || !hasRows(content) { + return "", false + } + var table bytes.Buffer + if err := writeTableOf(&table, content, width); err != nil { + return "", false + } + return table.String(), true +} + +// hasRows is whether content holds a list with something in it. +func hasRows(content any) bool { + value, err := jsonValue(content) + if err != nil { + return false + } + fields, ok := value.(map[string]any) + if !ok { + list, ok := value.([]any) + return ok && len(list) > 0 + } + for _, field := range fields { + if list, ok := field.([]any); ok && len(list) > 0 { + return true + } + } + return false +} diff --git a/internal/output/listtable_test.go b/internal/output/listtable_test.go new file mode 100644 index 00000000..ea83cd6b --- /dev/null +++ b/internal/output/listtable_test.go @@ -0,0 +1,54 @@ +// This file is not generated by Speakeasy. It covers listtable.go. + +package output + +import ( + "bytes" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +// R5 #29: at a terminal, `document list` gave each document about fifteen +// lines of YAML. It now gives each one line, its ID, name and status among +// them, as -o table does. +func TestDocumentListAtATerminalIsALinePerDocument(t *testing.T) { + content := decoded(t, narrowTables["documents"]) + got, ok := listTable("vf document list", content, 100) + if !ok { + t.Fatal("document list at a terminal should be its table") + } + lines := strings.Split(strings.TrimRight(got, "\n"), "\n") + if len(lines) != 4 { + t.Fatalf("a header and a line per document, 4 lines, not %d:\n%s", len(lines), got) + } + for _, want := range []string{"6b0e171cef80cdc9a190df12 billing.md", "SUCCESS", "ERROR", "STATUS"} { + if !strings.Contains(got, want) { + t.Errorf("the table should hold %q:\n%s", want, got) + } + } + + // Other commands keep what they print, and so does an empty list. + if _, ok := listTable("vf project list", content, 80); ok { + t.Error("only document list turns into its table") + } + if got, ok := listTable("vf document list", decoded(t, `{"documents":[],"total":0}`), 80); ok { + t.Errorf("an empty list should print as before, not as %q", got) + } +} + +// A pipe, and agent mode, get the result as before. +func TestDocumentListOffATerminalIsUnchanged(t *testing.T) { + root := &cobra.Command{Use: "vf"} + document := &cobra.Command{Use: "document"} + list := &cobra.Command{Use: "list"} + root.AddCommand(document) + document.AddCommand(list) + list.Flags().String("color", "auto", "") + var out bytes.Buffer + list.SetOut(&out) + if writeListTable(list, &out, decoded(t, narrowTables["documents"])) || out.Len() > 0 { + t.Errorf("a pipe should get the usual output:\n%s", out.String()) + } +} diff --git a/internal/output/output.go b/internal/output/output.go index 27d365ee..46adbe5f 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -287,6 +287,9 @@ func Result(cmd *cobra.Command, res interface{}) (err error) { if writeDone(cmd, out, content) { // done.go: an update's or a delete's message, as a ✓ line return nil } + if writeListTable(cmd, out, content) { // listtable.go: document list at a terminal, a line per document + return nil + } if err := prettyPrintFor(cmd, out, content, colorize); err != nil { // prettywrap.go: a long value breaks between words at a terminal return err } From 133bf0b3c4e7c7d445ea678a5eeb6750c227141a Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:47:50 -0500 Subject: [PATCH 20/31] fix(widget): the snippet warns when the widget serves an old version MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit widget get-snippet pins the widget to the environment's published version. A new project's only release is "First version", made with the project, so a newcomer who edited the agent and never published got a snippet for the empty template agent, and nothing said so. The snippet also printed under `snippet: |`, which came along when it was copied. Now a person gets the snippet bare, then where to paste it. After the snippet vf reads the environment and warns when nothing has been published since it was made, with `Next: vf environment publish …`. When a later release exists, the environment's diff says whether the draft has changes the release lacks. JSON, YAML, TOON, --jq and agent mode print the snippet as before, with the warning on stderr (a JSON event with the hint in agent mode). A draft snippet, a dry run or a failed read checks nothing. Found by the round-5 sweep's human-newcomer. --- internal/cli/widget/getsnippet.go | 2 +- internal/cli/widget/snippetcheck.go | 170 ++++++++++++++++++++++++++++ internal/cli/widgetsnippet_test.go | 167 +++++++++++++++++++++++++++ 3 files changed, 338 insertions(+), 1 deletion(-) create mode 100644 internal/cli/widget/snippetcheck.go create mode 100644 internal/cli/widgetsnippet_test.go diff --git a/internal/cli/widget/getsnippet.go b/internal/cli/widget/getsnippet.go index dcb3465d..0ee3f581 100644 --- a/internal/cli/widget/getsnippet.go +++ b/internal/cli/widget/getsnippet.go @@ -77,7 +77,7 @@ func runGetSnippetCmd(cmd *cobra.Command, args []string) error { return output.Error(cmd, err) } - if err := output.Result(cmd, res); err != nil { + if err := showSnippet(cmd, s, req, res); err != nil { // snippetcheck.go: the snippet bare for a person; warns when the widget serves an old version return err } return nil diff --git a/internal/cli/widget/snippetcheck.go b/internal/cli/widget/snippetcheck.go new file mode 100644 index 00000000..5bd0248c --- /dev/null +++ b/internal/cli/widget/snippetcheck.go @@ -0,0 +1,170 @@ +// This file is not generated by Speakeasy. It prints `vf widget get-snippet` +// ready to copy, and warns when the widget would serve a version without +// the project's edits. +// +// The snippet pins the widget to the environment's published version. A new +// project's only published version is "First version", made with the +// project, so a newcomer who edited the prompt and instructions, added +// documents and never published got a snippet for the empty template agent, +// and nothing said so. The snippet also printed under `snippet: |`, which +// came along when it was copied from the terminal. +// +// Now a person gets the snippet bare, then where to paste it. After the +// snippet, vf reads the environment (one GET) and warns when nothing has +// been published since the environment was made, with the publish command as +// Next. When a later release exists it also asks the environment's diff +// whether the draft has changes the release doesn't. The diff doesn't count +// global prompt edits (an API gap), so those alone don't warn. JSON, YAML, +// TOON, tables, --jq and agent mode print the snippet as before, with the +// warning on stderr: a line for a person, a JSON event with the hint for an +// agent. --version-param draft, a dry run and a failed read check nothing. +// +// Hooked in by one line in getsnippet.go; internal/cli/widgetsnippet_test.go +// covers it. + +package widget + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "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" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/session" +) + +// madeWith is how close to the environment's own creation a release is the +// one made with it: the API makes "First version" within a second. +const madeWith = time.Minute + +// releaseName is the name the publish hint gives the release. +const releaseName = "Website widget" + +// showSnippet prints get-snippet's result: bare for a person, as the API +// sent it otherwise. Then it warns if the widget would serve an old version. +func showSnippet(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableWidgetControllerGetSnippetRequest, res *operations.StableWidgetControllerGetSnippetResponse) error { + headers, _ := flagutil.GetBoolFlag(cmd, "include-headers") + snippet := res.GetStableWidgetGetSnippetResponse() + if snippet != nil && !headers && !client.IsDryRun(cmd) && output.ForAPerson(cmd) { + // Not through output.ResultWriter: a folded snippet can't be copied. + fmt.Fprintln(cmd.OutOrStdout(), strings.TrimRight(snippet.GetSnippet(), "\n")) + u := output.UI(cmd, cmd.ErrOrStderr()) + fmt.Fprintln(cmd.ErrOrStderr(), u.Muted("Paste it just before on each page the widget should appear on.")) + } else if err := output.Result(cmd, res); err != nil { + return err + } + if req == nil || client.IsDryRun(cmd) || (req.Version != nil && *req.Version == operations.StableWidgetControllerGetSnippetVersionDraft) { + return nil + } + if w, ok := servesOldVersion(cmd, s, req.ProjectID, req.EnvironmentAlias); ok { + flagutil.EmitWarning(cmd, w) + } + return nil +} + +// environmentRead is the part of `environment get` the check reads. +type environmentRead struct { + Environment struct { + Alias string `json:"alias"` + IsMain bool `json:"isMain"` + CreatedAt time.Time `json:"createdAt"` + Releases []struct { + Name string `json:"name"` + CreatedAt time.Time `json:"createdAt"` + } `json:"releases"` + } `json:"environment"` +} + +// diffRead is the part of `environment diff` the check reads. +type diffRead struct { + Diff struct { + Created int `json:"created"` + Updated int `json:"updated"` + Deleted int `json:"deleted"` + } `json:"diff"` +} + +// servesOldVersion reads the environment and says what's wrong with the +// version the widget serves, if anything is. +func servesOldVersion(cmd *cobra.Command, s *sdk.VoiceflowSDK, projectID, alias string) (flagutil.Warning, bool) { + ctx := client.WithSpinnerMessage(cmd.Context(), "Checking which version the widget serves…") + res, err := s.Environment.Get(ctx, operations.StableEnvironmentControllerGetRequest{EnvironmentAlias: alias, ProjectID: projectID}, + operations.WithSkipDeserialization()) + var env environmentRead + if err != nil || res == nil || !readBody(res.HTTPMeta.Response, &env) { + return flagutil.Warning{}, false + } + e := env.Environment + where := "environment " + alias + if e.IsMain { + where = "the project" + } + if len(e.Releases) == 0 { + return publishWarning(projectID, alias, "Nothing has been published to environment "+alias+" yet, so the widget has no version to serve."), true + } + newest := e.Releases[0] + for _, r := range e.Releases[1:] { + if r.CreatedAt.After(newest.CreatedAt) { + newest = r + } + } + if !e.CreatedAt.IsZero() && newest.CreatedAt.Sub(e.CreatedAt) < madeWith { + return publishWarning(projectID, alias, fmt.Sprintf( + "The widget serves the published version, %q, made with %s on %s. Nothing has been published since, so it has none of the edits made after that.", + newest.Name, where, stamp(newest.CreatedAt))), true + } + d, err := s.Environment.Diff(ctx, operations.StableEnvironmentControllerDiffRequest{EnvironmentAlias: alias, ProjectID: projectID}, + operations.WithSkipDeserialization()) + var diff diffRead + if err != nil || d == nil || !readBody(d.HTTPMeta.Response, &diff) { + return flagutil.Warning{}, false + } + changes := diff.Diff.Created + diff.Diff.Updated + diff.Diff.Deleted + if changes == 0 { + return flagutil.Warning{}, false + } + them := "changes" + if changes == 1 { + them = "change" + } + return publishWarning(projectID, alias, fmt.Sprintf( + "The widget serves the published version, %q (%s), and the draft has %d %s since that it doesn't.", + newest.Name, stamp(newest.CreatedAt), changes, them)), true +} + +// publishWarning is msg with the publish that fixes it as Next. +func publishWarning(projectID, alias, msg string) flagutil.Warning { + publish := "vf environment publish" + if !session.Active() { + publish += " -p " + projectID + " -e " + alias + } + return flagutil.Warning{ + Type: "widget_serves_old_version", + Message: msg, + Hints: []string{"Next: " + publish + ` --name "` + releaseName + `"`}, + } +} + +// stamp is when t was, in UTC to the minute. +func stamp(t time.Time) string { + return t.UTC().Format("2006-01-02 15:04 UTC") +} + +// readBody decodes the body the SDK left unread. +func readBody(res *http.Response, v any) bool { + if res == nil || res.Body == nil { + return false + } + defer res.Body.Close() + data, err := io.ReadAll(res.Body) + return err == nil && json.Unmarshal(data, v) == nil +} diff --git a/internal/cli/widgetsnippet_test.go b/internal/cli/widgetsnippet_test.go new file mode 100644 index 00000000..e10c45bf --- /dev/null +++ b/internal/cli/widgetsnippet_test.go @@ -0,0 +1,167 @@ +// This file is not generated by Speakeasy. It covers widget/snippetcheck.go: +// a person gets the snippet bare, and every mode warns when the widget would +// serve a version without the project's edits. + +package cli + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" +) + +// snippet is the start of what the API's snippet looks like. +const snippet = "" + +// Environments as `environment get` returns them. The project was made at +// 00:38:00; "First version" came with it, as it does for every project. +const ( + firstVersion = `{"name":"First version","backupID":1892447,"createdAt":"2026-12-01T00:38:00.302Z","description":null,"autogenerated":false}` + launchRelease = `{"name":"Launch","backupID":1892999,"createdAt":"2026-12-01T01:10:00.000Z","description":null,"autogenerated":false}` + neverPublished = `{"environment":{"name":"Main","alias":"main","isMain":true,"createdAt":"2026-12-01T00:38:00.120Z","trafficPercentage":100,"releases":[` + firstVersion + `]}}` + publishedLater = `{"environment":{"name":"Main","alias":"main","isMain":true,"createdAt":"2026-12-01T00:38:00.120Z","trafficPercentage":100,"releases":[` + firstVersion + `,` + launchRelease + `]}}` + twoChangesDiff = `{"diff":{"created":1,"updated":1,"deleted":0,"resources":[{"type":"agent","id":"a1","name":"Main Agent","change":"updated"},{"type":"variable","id":"v1","name":"order_id","change":"created"}],"truncated":false}}` + publishHint = `Next: vf environment publish -p p1 -e main --name "Website widget"` + neverPublishedW = `The widget serves the published version, "First version", made with the project on 2026-12-01 00:38 UTC. Nothing has been published since, so it has none of the edits made after that.` +) + +// snippetServer answers get-snippet, environment get and environment diff +// as the API does, and records the requests. +func snippetServer(t *testing.T, environment, diff 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) { + mu.Lock() + seen = append(seen, r.Method+" "+r.URL.Path) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/v1/stable/widget/snippet": + data, _ := json.Marshal(map[string]string{"snippet": snippet}) + _, _ = w.Write(data) + case "/v1/stable/environment/main": + _, _ = io.WriteString(w, environment) + case "/v1/stable/environment/main/diff": + _, _ = io.WriteString(w, diff) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL) + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + return srv.URL, func() string { + mu.Lock() + defer mu.Unlock() + return strings.Join(seen, ", ") + } +} + +const ( + getSnippet = "GET /v1/stable/widget/snippet" + getEnv = "GET /v1/stable/environment/main" + getDiff = "GET /v1/stable/environment/main/diff" +) + +func TestWidgetSnippetWarnsWhenTheWidgetServesAnOldVersion(t *testing.T) { + args := []string{"widget", "get-snippet", "-p", "p1", "-e", "main"} + cases := []struct { + name, environment, diff string + agent bool + extra []string + requests string + warning string // "" when it shouldn't warn + }{ + {"never published", neverPublished, unchangedDiff, false, nil, + getSnippet + ", " + getEnv, neverPublishedW}, + {"never published, agent mode", neverPublished, unchangedDiff, true, nil, + getSnippet + ", " + getEnv, neverPublishedW}, + {"never published, -o json", neverPublished, unchangedDiff, false, []string{"-o", "json"}, + getSnippet + ", " + getEnv, neverPublishedW}, + {"published, draft unchanged", publishedLater, unchangedDiff, false, nil, + getSnippet + ", " + getEnv + ", " + getDiff, ""}, + {"published, draft edited since", publishedLater, twoChangesDiff, false, nil, + getSnippet + ", " + getEnv + ", " + getDiff, + `The widget serves the published version, "Launch" (2026-12-01 01:10 UTC), and the draft has 2 changes since that it doesn't.`}, + {"nothing published", `{"environment":{"name":"Main","alias":"main","isMain":true,"createdAt":"2026-12-01T00:38:00.120Z","trafficPercentage":100,"releases":[]}}`, + unchangedDiff, false, nil, getSnippet + ", " + getEnv, + "Nothing has been published to environment main yet, so the widget has no version to serve."}, + {"a draft snippet", neverPublished, unchangedDiff, false, []string{"--version-param", "draft"}, getSnippet, ""}, + {"an environment it can't read", `not json`, unchangedDiff, false, nil, getSnippet + ", " + getEnv, ""}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + url, requests := snippetServer(t, c.environment, c.diff) + stdout, stderr := runView(t, url, c.agent, append(append([]string{}, args...), c.extra...)...) + if got := requests(); got != c.requests { + t.Errorf("requests:\n got %s\nwant %s", got, c.requests) + } + if !strings.Contains(stdout, "versionVariant") { + t.Errorf("no snippet on stdout:\n%s", stdout) + } + if c.warning == "" { + if strings.Contains(stderr, "environment publish") { + t.Errorf("warned:\n%s", stderr) + } + return + } + if c.agent { + var event struct { + Warning string `json:"warning"` + Type string `json:"warning_type"` + Hints []string `json:"hints"` + } + if err := json.Unmarshal([]byte(stderr), &event); err != nil { + t.Fatalf("stderr isn't one JSON warning: %v\n%s", err, stderr) + } + if event.Warning != c.warning || event.Type != "widget_serves_old_version" || len(event.Hints) != 1 || event.Hints[0] != publishHint { + t.Errorf("warning: %+v", event) + } + return + } + if !strings.Contains(stderr, c.warning) || !strings.Contains(stderr, "\n "+publishHint+"\n") { + t.Errorf("stderr lacks the warning and its Next line:\n%s", stderr) + } + }) + } +} + +// A person gets the snippet bare, ready to copy: no `snippet: |` line and +// no indent. Every other format keeps the API's shape. +func TestWidgetSnippetPrintsBareForAPerson(t *testing.T) { + args := []string{"widget", "get-snippet", "-p", "p1", "-e", "main", "--version-param", "draft"} + url, _ := snippetServer(t, neverPublished, unchangedDiff) + stdout, stderr := runView(t, url, false, args...) + if stdout != snippet+"\n" { + t.Errorf("stdout isn't the bare snippet:\n%q", stdout) + } + if !strings.Contains(stderr, "Paste it just before ") { + t.Errorf("no word on where it goes:\n%s", stderr) + } + for _, format := range []string{"json", "yaml"} { + stdout, _ := runView(t, url, false, append(args, "-o", format)...) + if !strings.Contains(stdout, "snippet") { + t.Errorf("-o %s lost the snippet key:\n%s", format, stdout) + } + } + if stdout, _ := runView(t, url, true, args...); !strings.HasPrefix(stdout, "snippet:") { + t.Errorf("agent mode lost the snippet key:\n%s", stdout) + } +} + +// A dry run sends nothing, so nothing is checked. +func TestWidgetSnippetDryRunChecksNothing(t *testing.T) { + url, requests := snippetServer(t, neverPublished, unchangedDiff) + _, stderr := runView(t, url, false, "widget", "get-snippet", "-p", "p1", "-e", "main", "--dry-run") + if got := requests(); got != "" { + t.Errorf("a dry run sent %s", got) + } + if strings.Contains(stderr, "environment publish") { + t.Errorf("a dry run warned:\n%s", stderr) + } +} From 3ddd042215de26af1a3c61019076922c05b80560 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:58:03 -0500 Subject: [PATCH 21/31] feat(agent): add-playbook and remove-playbook route a playbook to the agent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit playbook create made a playbook the agent couldn't reach: the agent hands off only to the playbooks in its own list, and nothing said so. add-workflow and remove-workflow exist for workflows, but the only way to route a playbook was agent update --playbooks with the whole list, which replaces it. The API has no endpoint for one playbook, so vf agent add-playbook and remove-playbook read the agent's playbooks, add or drop that entry and send the list back in one agent update. Every other entry goes back as read (description, condition, required variables) and nothing else on the agent is sent; help says so. An entry vf can't read stops the command before it writes. add-playbook's --description defaults to the playbook's own. Adding one already routed exits 1, removing one not routed exits 4, and a dry run shows the read and what the write would send. playbook create now ends with a warning that the playbook isn't routed yet, and `Next: vf agent add-playbook …` (a JSON event in agent mode). agent update --playbooks gives the list's JSON shape. Found by the round-5 sweep's agent-builder. --- internal/cli/agent/playbookroute.go | 326 ++++++++++++++++++++++++++++ internal/cli/agent/root.go | 2 + internal/cli/playbook/create.go | 1 + internal/cli/playbook/routehint.go | 68 ++++++ internal/cli/playbookroute_test.go | 265 ++++++++++++++++++++++ 5 files changed, 662 insertions(+) create mode 100644 internal/cli/agent/playbookroute.go create mode 100644 internal/cli/playbook/routehint.go create mode 100644 internal/cli/playbookroute_test.go diff --git a/internal/cli/agent/playbookroute.go b/internal/cli/agent/playbookroute.go new file mode 100644 index 00000000..200f9ea3 --- /dev/null +++ b/internal/cli/agent/playbookroute.go @@ -0,0 +1,326 @@ +// This file is not generated by Speakeasy. It adds `vf agent add-playbook` +// and `vf agent remove-playbook`, which route a playbook to the agent and +// stop routing it, as add-workflow and remove-workflow do for workflows. +// +// `playbook create` makes a playbook the agent can't reach: the agent hands +// off only to the playbooks in its own list. The only way to add one was +// `agent update --playbooks ''`, which replaces the list, so +// a tester's Returns playbook sat unrouted and nothing said so. +// +// The API has an endpoint for one workflow but none for one playbook. So +// these commands read the agent's playbooks (one GET), add or drop the one +// named, and send the list back in one `agent update` (PATCH). Every other +// entry goes back as read, with its description, condition and required +// variables, and nothing else on the agent is sent. add-playbook's +// --description defaults to the playbook's own description, read with one +// more GET. A dry run shows the read and says what the write would send. + +package agent + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/interactive" + "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/usage" +) + +// readModifyWrite is what both commands' help says of how they work. +const readModifyWrite = " The API has no endpoint for one playbook, so vf reads the agent's playbooks, " + + "changes that one entry and writes the list back with one agent update: every other entry is kept as read, " + + "and nothing else on the agent changes. An edit made to the list between the read and the write is lost." + +// addPlaybookRequest is what add-playbook sends for: the entry to add, and +// where. +type addPlaybookRequest struct { + ProjectID string + EnvironmentAlias string + Body components.StableAgentUpdateRequestV2Playbook +} + +// removePlaybookRequest names the entry remove-playbook drops, and where. +type removePlaybookRequest struct { + PlaybookID string + ProjectID string + EnvironmentAlias string +} + +var addPlaybookCmdMeta = []flagutil.FlagMeta{ + {FlagName: "project-id", Shorthand: "p", FieldPath: "ProjectID", Kind: flagutil.FlagKindString, Required: true, Description: "[required]"}, + {FlagName: "environment-alias", Shorthand: "e", FieldPath: "EnvironmentAlias", Kind: flagutil.FlagKindString, Required: true, Description: "[required]"}, + {FlagName: "playbook-id", FieldPath: "Body.PlaybookID", Kind: flagutil.FlagKindString, Required: true, Description: "The playbook to add. Copy its ID from 'vf playbook list'. [required]"}, + {FlagName: "description", FieldPath: "Body.Description", Kind: flagutil.FlagKindString, Optional: true, Description: "When the agent should hand off to this playbook. The agent reads it to choose between its playbooks and workflows. Leave it out to use the playbook's own description."}, + {FlagName: "condition", Shorthand: "c", FieldPath: "Body.Condition", Kind: flagutil.FlagKindJSON, Optional: true, Annotations: `json:"condition,omitempty"`, Description: "The agent can hand off to the playbook only while this condition holds. Leave it out for a playbook it can always use."}, + {FlagName: "required-variables", Shorthand: "r", FieldPath: "Body.RequiredVariables", Kind: flagutil.FlagKindJSON, Optional: true, Annotations: `json:"requiredVariables,omitempty"`, Description: "Variables the agent fills from the conversation before it hands off, each with a description of what it holds."}, +} + +var removePlaybookCmdMeta = []flagutil.FlagMeta{ + {FlagName: "playbook-id", FieldPath: "PlaybookID", Kind: flagutil.FlagKindString, Required: true, Description: "The playbook to stop routing to. [required]"}, + {FlagName: "project-id", Shorthand: "p", FieldPath: "ProjectID", Kind: flagutil.FlagKindString, Required: true, Description: "[required]"}, + {FlagName: "environment-alias", Shorthand: "e", FieldPath: "EnvironmentAlias", Kind: flagutil.FlagKindString, Required: true, Description: "[required]"}, +} + +// addPlaybookRouting gives the agent group add-playbook and remove-playbook. +// Their metadata is fixed, so a mistake in it is a bug any test that builds +// the commands finds. +func addPlaybookRouting(parent *cobra.Command) { + add := &cobra.Command{ + Use: "add-playbook", + Short: "Add agent playbook", + Long: "Add one playbook to the main agent's playbooks, so the agent can hand off to it. Rejected when the list already has it." + + readModifyWrite, + Example: " vf agent add-playbook --project-id --environment-alias --playbook-id --description 'Use when the customer wants to return an item'", + RunE: runAddPlaybookCmd, + Aliases: []string{"ap"}, + } + flagutil.RegisterFlags(add, addPlaybookCmdMeta) + mustValidate(flagutil.ValidateMeta[addPlaybookRequest](addPlaybookCmdMeta)) + add.Flags().String("body", "", "Request body as JSON (alternative to individual flags). Can also be provided via stdin.") + parent.AddCommand(add) + + remove := &cobra.Command{ + Use: "remove-playbook", + Short: "Remove agent playbook", + Long: "Remove one playbook from the main agent's playbooks. The playbook itself is not deleted." + readModifyWrite, + Example: " vf agent remove-playbook --playbook-id --project-id --environment-alias ", + RunE: runRemovePlaybookCmd, + Aliases: []string{"rp"}, + } + flagutil.RegisterFlags(remove, removePlaybookCmdMeta) + mustValidate(flagutil.ValidateMeta[removePlaybookRequest](removePlaybookCmdMeta)) + parent.AddCommand(remove) + + // `agent update --playbooks` said what the list does but not its shape. + for _, c := range parent.Commands() { + if f := c.Flags().Lookup("playbooks"); c.Name() == "update" && f != nil { + f.Usage += ` For example: '[{"playbookID":"","description":""}]'. 'vf agent add-playbook' adds one without resending the list.` + } + } +} + +func mustValidate(err error) { + if err != nil { + panic("agent playbook routing: " + err.Error()) + } +} + +func runAddPlaybookCmd(cmd *cobra.Command, args []string) error { + if usage.UsageRequested(cmd) { + return usage.EmitSchema(cmd, cmd.OutOrStdout()) + } + if interactive.ShouldPrompt(cmd, addPlaybookCmdMeta) { + if err := interactive.PromptAndSetFlags(cmd, addPlaybookCmdMeta); err != nil { + return err + } + } + req, err := flagutil.BuildRequest[addPlaybookRequest](cmd, addPlaybookCmdMeta, "Body", "body") + if err != nil { + return err + } + s, opts, err := playbookClient(cmd) + if err != nil { + return err + } + entry := req.Body + list, err := routedPlaybooks(cmd, s, opts, req.ProjectID, req.EnvironmentAlias) + if err != nil { + return err + } + if client.IsDryRun(cmd) { + return previewWrite(cmd, "the agent's playbooks plus this one", entry) + } + for _, p := range list { + if p.PlaybookID == entry.PlaybookID { + return refuse(cmd, "already_routed", "Playbook "+entry.PlaybookID+" is already one of the agent's playbooks", + "`vf agent get --project-id "+req.ProjectID+" --environment-alias "+req.EnvironmentAlias+"` shows its entry", + "To change it, remove it with `vf agent remove-playbook`, then add it again") + } + } + if entry.Description == nil { + entry.Description = playbookDescription(cmd, s, opts, entry.PlaybookID, req.ProjectID, req.EnvironmentAlias) + } + list = append(list, entry) + return writePlaybooks(cmd, s, opts, req.ProjectID, req.EnvironmentAlias, list, + fmt.Sprintf("Playbook %s added to the agent's playbooks (%d in all).", entry.PlaybookID, len(list))) +} + +func runRemovePlaybookCmd(cmd *cobra.Command, args []string) error { + if usage.UsageRequested(cmd) { + return usage.EmitSchema(cmd, cmd.OutOrStdout()) + } + if interactive.ShouldPrompt(cmd, removePlaybookCmdMeta) { + if err := interactive.PromptAndSetFlags(cmd, removePlaybookCmdMeta); err != nil { + return err + } + } + req, err := flagutil.BuildRequest[removePlaybookRequest](cmd, removePlaybookCmdMeta, "", "") + if err != nil { + return err + } + s, opts, err := playbookClient(cmd) + if err != nil { + return err + } + list, err := routedPlaybooks(cmd, s, opts, req.ProjectID, req.EnvironmentAlias) + if err != nil { + return err + } + if client.IsDryRun(cmd) { + return previewWrite(cmd, "the agent's playbooks minus "+req.PlaybookID, nil) + } + kept := make([]components.StableAgentUpdateRequestV2Playbook, 0, len(list)) + for _, p := range list { + if p.PlaybookID != req.PlaybookID { + kept = append(kept, p) + } + } + if len(kept) == len(list) { + return refuse(cmd, "not_found", "Playbook "+req.PlaybookID+" isn't one of the agent's playbooks", + "`vf agent get --project-id "+req.ProjectID+" --environment-alias "+req.EnvironmentAlias+"` lists the playbooks it routes to") + } + return writePlaybooks(cmd, s, opts, req.ProjectID, req.EnvironmentAlias, kept, + fmt.Sprintf("Playbook %s removed from the agent's playbooks (%d left).", req.PlaybookID, len(kept))) +} + +// playbookClient is the SDK client and call options every request here +// uses. Bodies are read here, not by the SDK. +func playbookClient(cmd *cobra.Command) (*sdk.VoiceflowSDK, []operations.Option, error) { + s, err := client.NewClient(cmd) + if err != nil { + return nil, nil, err + } + opts, err := output.PrepareCallOpts(cmd) + if err != nil { + return nil, nil, err + } + if err := output.ValidateGlobalServerIndex(cmd, len(sdk.ServerList)); err != nil { + return nil, nil, err + } + return s, append(opts, operations.WithSkipDeserialization()), nil +} + +// routedPlaybooks reads the agent's playbooks, each as the update takes it. +// An entry vf can't read stops the command, so none is dropped. +func routedPlaybooks(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, projectID, alias string) ([]components.StableAgentUpdateRequestV2Playbook, error) { + ctx := client.WithSpinnerMessage(cmd.Context(), "Reading the agent's playbooks…") + res, err := s.Agent.Get(ctx, operations.StableAgentControllerGetV2Request{ProjectID: projectID, EnvironmentAlias: alias}, opts...) + if err != nil { + return nil, output.Error(cmd, err) + } + if client.IsDryRun(cmd) { + return nil, nil + } + var read struct { + Agent struct { + Playbooks []json.RawMessage `json:"playbooks"` + } `json:"agent"` + } + if !readBody(res.HTTPMeta.Response, &read) { + return nil, unreadable(cmd, "the agent's answer") + } + list := make([]components.StableAgentUpdateRequestV2Playbook, 0, len(read.Agent.Playbooks)+1) + for i, raw := range read.Agent.Playbooks { + var p components.StableAgentUpdateRequestV2Playbook + if err := json.Unmarshal(raw, &p); err != nil || p.PlaybookID == "" { + return nil, unreadable(cmd, fmt.Sprintf("entry %d of its playbooks (%s)", i, cut(string(raw)))) + } + list = append(list, p) + } + return list, nil +} + +// playbookDescription is the playbook's own description, or nil when it has +// none or can't be read: the update then says why, if it matters. +func playbookDescription(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, playbookID, projectID, alias string) *string { + ctx := client.WithSpinnerMessage(cmd.Context(), "Reading the playbook's description…") + res, err := s.Playbook.Get(ctx, operations.StablePlaybookControllerGetV2Request{PlaybookID: playbookID, ProjectID: projectID, EnvironmentAlias: alias}, opts...) + if err != nil || res == nil { + return nil + } + var read struct { + Playbook struct { + Description *string `json:"description"` + } `json:"playbook"` + } + if !readBody(res.HTTPMeta.Response, &read) || read.Playbook.Description == nil || strings.TrimSpace(*read.Playbook.Description) == "" { + return nil + } + return read.Playbook.Description +} + +// writePlaybooks sends list as the agent's playbooks, and prints the +// update's answer with said as its message. +func writePlaybooks(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, projectID, alias string, list []components.StableAgentUpdateRequestV2Playbook, said string) error { + res, err := s.Agent.Update(cmd.Context(), operations.StableAgentControllerUpdateV2Request{ + ProjectID: projectID, EnvironmentAlias: alias, + Body: components.StableAgentUpdateRequestV2{Playbooks: list}, + }, opts...) + if err != nil { + return output.Error(cmd, err) + } + answer := map[string]any{} + _ = readBody(res.HTTPMeta.Response, &answer) + for k, v := range answer { + if items, ok := v.([]any); ok && len(items) == 0 { + delete(answer, k) // no unresolved references or mentions + } + } + answer["message"] = said + return output.Result(cmd, answer) +} + +// previewWrite ends a dry run: the read was shown, and the write sends +// what it would have read, changed as what says. +func previewWrite(cmd *cobra.Command, what string, entry any) error { + w := cmd.ErrOrStderr() + fmt.Fprintf(w, "[DRY-RUN] Then would send: PATCH /v2/stable/agent, with playbooks set to %s\n", what) + if entry != nil { + if data, err := json.MarshalIndent(entry, " ", " "); err == nil { + fmt.Fprintf(w, "[DRY-RUN] Body: the playbooks read, then\n %s\n", data) + } + } + fmt.Fprintln(w, "[DRY-RUN] Network call skipped.") + return nil +} + +// refuse stops the command before it writes anything. +func refuse(cmd *cobra.Command, kind, title string, next ...string) error { + return output.Report(cmd, output.Explanation{Type: kind, Title: title, Why: []string{"Nothing was changed."}, Next: next}, errors.New(title)) +} + +// unreadable stops the command when vf can't read the playbooks it would +// write back. +func unreadable(cmd *cobra.Command, what string) error { + return refuse(cmd, "unexpected_response", "vf couldn't read "+what+", so it changed nothing", + "`vf agent update --playbooks` sets the whole list: `vf agent get -o json` shows the current one") +} + +// cut shortens s for a message. +func cut(s string) string { + if r := []rune(s); len(r) > 80 { + return string(r[:80]) + "…" + } + return s +} + +// readBody decodes the body the SDK left unread. +func readBody(res *http.Response, v any) bool { + if res == nil || res.Body == nil { + return false + } + defer res.Body.Close() + data, err := io.ReadAll(res.Body) + return err == nil && json.Unmarshal(data, v) == nil +} diff --git a/internal/cli/agent/root.go b/internal/cli/agent/root.go index 527dc33a..d1b75214 100644 --- a/internal/cli/agent/root.go +++ b/internal/cli/agent/root.go @@ -97,6 +97,8 @@ func InitAgentRoot(parent *cobra.Command) error { return err } + addPlaybookRouting(AgentCmd) // playbookroute.go: add-playbook and remove-playbook, which the API has no endpoint for + parent.AddCommand(AgentCmd) return nil } diff --git a/internal/cli/playbook/create.go b/internal/cli/playbook/create.go index 71accca4..c604b960 100644 --- a/internal/cli/playbook/create.go +++ b/internal/cli/playbook/create.go @@ -88,6 +88,7 @@ func runCreateCmd(cmd *cobra.Command, args []string) error { if err != nil { return output.Error(cmd, err) } + defer saysNotRouted(cmd, req, res)() // routehint.go: a new playbook isn't routed to the agent yet if err := output.Result(cmd, res); err != nil { return err diff --git a/internal/cli/playbook/routehint.go b/internal/cli/playbook/routehint.go new file mode 100644 index 00000000..8ed92eab --- /dev/null +++ b/internal/cli/playbook/routehint.go @@ -0,0 +1,68 @@ +// This file is not generated by Speakeasy. It says, after `vf playbook +// create`, that the new playbook isn't routed to the agent yet, and gives +// the command that routes it. +// +// The agent hands off only to the playbooks in its own list, and creating a +// playbook doesn't add it there. A tester's Returns playbook looked done +// after `playbook create`, but the agent could never reach it, and nothing +// said so. Now a create ends with a warning and `vf agent add-playbook` as +// Next: a line for a person, a JSON event with the hint for an agent. A dry +// run creates nothing, so it says nothing. +// +// Hooked in by one line in create.go; internal/cli/playbookroute_test.go +// covers it. + +package playbook + +import ( + "encoding/json" + + "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/operations" + "github.com/voiceflow/cli/internal/session" +) + +// saysNotRouted reads the playbook a create made, before Result prints it, +// and returns what says, once it has been, that the agent can't reach it. +func saysNotRouted(cmd *cobra.Command, req *operations.StablePlaybookControllerCreateV2Request, res *operations.StablePlaybookControllerCreateV2Response) func() { + none := func() {} + if req == nil || res == nil || client.IsDryRun(cmd) { + return none + } + var created struct { + Playbook struct { + ID string `json:"id"` + Name string `json:"name"` + } `json:"playbook"` + } + if typed := res.StablePlaybookResponseV2; typed != nil { + data, err := json.Marshal(typed) + if err != nil || json.Unmarshal(data, &created) != nil { + return none + } + } else if !output.PeekJSON(res.HTTPMeta.Response, &created) { + return none + } + id, name := created.Playbook.ID, created.Playbook.Name + if id == "" { + return none + } + if name == "" { + name = "The playbook" + } + route := "vf agent add-playbook --playbook-id " + id + if !session.Active() { + route += " -p " + req.ProjectID + " -e " + req.EnvironmentAlias + } + return func() { + flagutil.EmitWarning(cmd, flagutil.Warning{ + Type: "playbook_not_routed", + Message: name + " isn't routed yet: the agent hands off only to the playbooks in its own list, and creating one doesn't add it there.", + Hints: []string{"Next: " + route}, + }) + } +} diff --git a/internal/cli/playbookroute_test.go b/internal/cli/playbookroute_test.go new file mode 100644 index 00000000..af932b7d --- /dev/null +++ b/internal/cli/playbookroute_test.go @@ -0,0 +1,265 @@ +// This file is not generated by Speakeasy. It covers agent/playbookroute.go +// (agent add-playbook and remove-playbook) and playbook/routehint.go (a new +// playbook says it isn't routed yet). + +package cli + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +const ( + returnsPB = "6b0e1776cff37870f4eb04fb" // the playbook being routed + billingPB = "6b0e1776cff37870f4eb0400" // one the agent already routes to + shippingPB = "6b0e1776cff37870f4eb0401" // another, with nothing but its ID and description +) + +// billingEntry is an entry as `agent get` returns it, with everything an +// entry can carry, so a write that drops or changes any of it shows. +const billingEntry = `{"condition":{"assertions":[{"key":"k1","lhs":{"variableID":"v1"},"operation":"is","rhs":"gold"}],"matchAll":true,"type":"value-variable"},` + + `"description":"Use for billing questions","playbookID":"` + billingPB + `",` + + `"requiredVariables":[{"description":"The account number","id":"rv1","variableOrEntityID":"v2"}]}` +const shippingEntry = `{"description":null,"playbookID":"` + shippingPB + `"}` + +// routingServer answers as the API does for an agent routing to playbooks, +// a playbook get and a playbook create, and records each request with the +// body of each PATCH. +func routingServer(t *testing.T, playbooks string) (url string, requests func() []string, patched func() []string) { + t.Helper() + var mu sync.Mutex + var seen, bodies []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + mu.Lock() + seen = append(seen, r.Method+" "+r.URL.Path) + if r.Method == http.MethodPatch { + bodies = append(bodies, string(body)) + } + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && r.URL.Path == "/v2/stable/agent": + _, _ = io.WriteString(w, `{"agent":{"llm":{"priorityProcessing":false},"promptLineCount":3,"instructionsLineCount":9,"pathToolOrder":[],`+ + `"playbooks":[`+playbooks+`],"workflows":[{"description":"Book a call","workflowID":"wf1","requiredVariables":[],"condition":null}]}}`) + case r.Method == http.MethodPatch && r.URL.Path == "/v2/stable/agent": + _, _ = io.WriteString(w, `{"message":"Agent updated.","unresolvedReferences":[],"unresolvedMentions":[]}`) + case r.Method == http.MethodGet && r.URL.Path == "/v2/stable/playbook/"+returnsPB: + _, _ = io.WriteString(w, `{"playbook":{"id":"`+returnsPB+`","name":"Returns","description":"Use when the customer wants to return an item"}}`) + case r.Method == http.MethodPost && r.URL.Path == "/v2/stable/playbook": + w.WriteHeader(http.StatusCreated) + _, _ = io.WriteString(w, `{"playbook":{"id":"`+returnsPB+`","name":"Returns","settings":{},"createdAt":"2026-12-01T00:41:48Z","updatedAt":"2026-12-01T00:41:48Z",`+ + `"description":null,"instructions":"# Returns","pathToolOrder":[],"endTool":null,"cardTool":null,"buttonTool":null,"carouselTool":null}}`) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL) + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + return srv.URL, func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), seen...) + }, func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), bodies...) + } +} + +// runArgs runs vf with args against url and returns stdout, stderr and the +// error it ended with. +func runArgs(t *testing.T, url string, agent bool, args ...string) (stdout, stderr string, err 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 out, errOut bytes.Buffer + root.SetOut(&out) + root.SetErr(&errOut) + root.SetIn(strings.NewReader("")) + mode := "--agent-mode=false" + if agent { + mode = "--agent-mode" + } + root.SetArgs(append(args, mode, "--no-interactive")) + err = renderError(root.ExecuteC()) + return out.String(), errOut.String(), err +} + +// sameJSON fails t unless got and want are the same JSON. +func sameJSON(t *testing.T, got, want string) { + t.Helper() + var g, w any + if err := json.Unmarshal([]byte(got), &g); err != nil { + t.Fatalf("not JSON: %v\n%s", err, got) + } + if err := json.Unmarshal([]byte(want), &w); err != nil { + t.Fatalf("want isn't JSON: %v\n%s", err, want) + } + gd, _ := json.Marshal(g) + wd, _ := json.Marshal(w) + if string(gd) != string(wd) { + t.Errorf("sent:\n got %s\nwant %s", gd, wd) + } +} + +func TestAgentAddPlaybookRoutesItAndKeepsTheRest(t *testing.T) { + scope := []string{"-p", "p1", "-e", "main"} + t.Run("with a description", func(t *testing.T) { + url, requests, patched := routingServer(t, billingEntry+","+shippingEntry) + stdout, stderr, err := runArgs(t, url, false, append([]string{"agent", "add-playbook", "--playbook-id", returnsPB, "--description", "Returns and exchanges"}, scope...)...) + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if got := strings.Join(requests(), ", "); got != "GET /v2/stable/agent, PATCH /v2/stable/agent" { + t.Errorf("requests: %s", got) + } + sameJSON(t, patched()[0], `{"playbooks":[`+billingEntry+`,`+shippingEntry+`,{"description":"Returns and exchanges","playbookID":"`+returnsPB+`"}]}`) + if !strings.Contains(stdout, "Playbook "+returnsPB+" added to the agent's playbooks (3 in all).") { + t.Errorf("stdout:\n%s", stdout) + } + }) + t.Run("the playbook's own description, agent mode", func(t *testing.T) { + url, requests, patched := routingServer(t, billingEntry) + stdout, stderr, err := runArgs(t, url, true, append([]string{"agent", "add-playbook", "--playbook-id", returnsPB}, scope...)...) + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if got := strings.Join(requests(), ", "); got != "GET /v2/stable/agent, GET /v2/stable/playbook/"+returnsPB+", PATCH /v2/stable/agent" { + t.Errorf("requests: %s", got) + } + sameJSON(t, patched()[0], `{"playbooks":[`+billingEntry+`,{"description":"Use when the customer wants to return an item","playbookID":"`+returnsPB+`"}]}`) + if !strings.Contains(stdout, "(2 in all)") { + t.Errorf("stdout:\n%s", stdout) + } + }) + t.Run("already routed", func(t *testing.T) { + url, requests, _ := routingServer(t, billingEntry) + _, stderr, err := runArgs(t, url, false, append([]string{"agent", "add-playbook", "--playbook-id", billingPB, "--description", "x"}, scope...)...) + if code := output.ExitCode(err); code != output.ExitFailure { + t.Errorf("exit %d, want %d\n%s", code, output.ExitFailure, stderr) + } + if !strings.Contains(stderr, "already one of the agent's playbooks") { + t.Errorf("stderr:\n%s", stderr) + } + if got := strings.Join(requests(), ", "); got != "GET /v2/stable/agent" { + t.Errorf("requests: %s", got) + } + }) + t.Run("an entry vf can't read", func(t *testing.T) { + url, requests, _ := routingServer(t, `{"playbookID":"pb9","description":"x","condition":{"type":"something-new","matchAll":true,"assertions":[]}}`) + _, stderr, err := runArgs(t, url, false, append([]string{"agent", "add-playbook", "--playbook-id", returnsPB, "--description", "x"}, scope...)...) + if err == nil || !strings.Contains(stderr, "so it changed nothing") { + t.Errorf("err %v\n%s", err, stderr) + } + if got := strings.Join(requests(), ", "); got != "GET /v2/stable/agent" { + t.Errorf("requests: %s", got) + } + }) + t.Run("dry run", func(t *testing.T) { + url, requests, _ := routingServer(t, billingEntry) + _, stderr, err := runArgs(t, url, false, append([]string{"agent", "add-playbook", "--playbook-id", returnsPB, "--dry-run"}, scope...)...) + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if len(requests()) != 0 || !strings.Contains(stderr, "[DRY-RUN] Then would send: PATCH /v2/stable/agent") { + t.Errorf("requests %v\n%s", requests(), stderr) + } + }) +} + +func TestAgentRemovePlaybookDropsOnlyThatOne(t *testing.T) { + scope := []string{"-p", "p1", "-e", "main"} + url, requests, patched := routingServer(t, billingEntry+","+shippingEntry) + stdout, stderr, err := runArgs(t, url, false, append([]string{"agent", "remove-playbook", "--playbook-id", shippingPB}, scope...)...) + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if got := strings.Join(requests(), ", "); got != "GET /v2/stable/agent, PATCH /v2/stable/agent" { + t.Errorf("requests: %s", got) + } + sameJSON(t, patched()[0], `{"playbooks":[`+billingEntry+`]}`) + if !strings.Contains(stdout, "removed from the agent's playbooks (1 left)") { + t.Errorf("stdout:\n%s", stdout) + } + + // The last one goes too, as an empty list: a list left out changes nothing. + url, _, patched = routingServer(t, shippingEntry) + if _, stderr, err := runArgs(t, url, false, append([]string{"agent", "remove-playbook", "--playbook-id", shippingPB}, scope...)...); err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + sameJSON(t, patched()[0], `{"playbooks":[]}`) + + url, requests, _ = routingServer(t, billingEntry) + _, stderr, err = runArgs(t, url, false, append([]string{"agent", "remove-playbook", "--playbook-id", returnsPB}, scope...)...) + if code := output.ExitCode(err); code != output.ExitNotFound || !strings.Contains(stderr, "isn't one of the agent's playbooks") { + t.Errorf("exit %d\n%s", code, stderr) + } + if got := strings.Join(requests(), ", "); got != "GET /v2/stable/agent" { + t.Errorf("requests: %s", got) + } +} + +// A new playbook says it isn't routed yet, with the command that routes it. +func TestPlaybookCreateSaysItIsntRoutedYet(t *testing.T) { + args := []string{"playbook", "create", "-p", "p1", "-e", "main", "--name", "Returns"} + route := "Next: vf agent add-playbook --playbook-id " + returnsPB + " -p p1 -e main" + for _, agent := range []bool{false, true} { + url, _, _ := routingServer(t, "") + stdout, stderr, err := runArgs(t, url, agent, args...) + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if !strings.Contains(stdout, returnsPB) { + t.Errorf("the playbook wasn't printed:\n%s", stdout) + } + if agent { + var event struct { + Warning string `json:"warning"` + Type string `json:"warning_type"` + Hints []string `json:"hints"` + } + if err := json.Unmarshal([]byte(stderr), &event); err != nil { + t.Fatalf("stderr isn't one JSON warning: %v\n%s", err, stderr) + } + if event.Type != "playbook_not_routed" || !strings.HasPrefix(event.Warning, "Returns isn't routed yet") || len(event.Hints) != 1 || event.Hints[0] != route { + t.Errorf("warning: %+v", event) + } + continue + } + if !strings.Contains(stderr, "Returns isn't routed yet") || !strings.Contains(stderr, "\n "+route+"\n") { + t.Errorf("stderr:\n%s", stderr) + } + } + + url, _, _ := routingServer(t, "") + if _, stderr, _ := runArgs(t, url, false, append(args, "--dry-run")...); strings.Contains(stderr, "isn't routed") { + t.Errorf("a dry run warned:\n%s", stderr) + } +} + +// `agent update --playbooks` shows the list's shape, and points at +// add-playbook. +func TestAgentUpdatePlaybooksHelpShowsTheShape(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + f := find(t, testRoot(t), "agent", "update").Flags().Lookup("playbooks") + if f == nil || !strings.Contains(f.Usage, `'[{"playbookID":"","description":""}]'`) || !strings.Contains(f.Usage, "vf agent add-playbook") { + t.Errorf("--playbooks: %v", f) + } +} From 6a5894f43e7bb1a3c6bdd34680732333588f68ae Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:04:03 -0500 Subject: [PATCH 22/31] fix(output): a read vf's types can't hold prints as Voiceflow sent it `transcript get --format-param logs` failed in pretty, YAML, table and agent output with "couldn't read the response ... update vf", while -o json worked. The spec gives each log's createdAt and updatedAt as a date; the API sends a date and time, so the SDK's typed decode fails, and every format but -o json decodes first. A typed fix would lose the time of day, and the next field the spec gets wrong would fail the same way. So the client now keeps the body of each successful GET that answers JSON until the next request starts (client/keepanswer.go), and when the SDK can't decode it, Error prints that body as the result in the format asked for and the command succeeds, as -o json would have (output/undecoded.go). Only reads: a write's command may have more to do with its answer, so a write still fails as before. The fixture is round 5's logs transcript. --- internal/cli/testdata/transcript-logs.json | 1 + internal/cli/undecoded_test.go | 84 ++++++++++++++++++++++ internal/client/client.go | 1 + internal/client/keepanswer.go | 69 ++++++++++++++++++ internal/output/output.go | 3 + internal/output/undecoded.go | 73 +++++++++++++++++++ 6 files changed, 231 insertions(+) create mode 100644 internal/cli/testdata/transcript-logs.json create mode 100644 internal/cli/undecoded_test.go create mode 100644 internal/client/keepanswer.go create mode 100644 internal/output/undecoded.go diff --git a/internal/cli/testdata/transcript-logs.json b/internal/cli/testdata/transcript-logs.json new file mode 100644 index 00000000..a2f163bd --- /dev/null +++ b/internal/cli/testdata/transcript-logs.json @@ -0,0 +1 @@ +{"format":"logs","transcript":{"id":"6b0e17185a668e418890e3d5","sessionID":"pu-1","createdAt":"2026-12-01T00:38:48.463Z","endedAt":"2026-12-01T00:39:02.118Z","durationSeconds":14,"environmentAlias":"main","version":"draft","properties":[],"evaluations":[],"creatorURL":"https://creator.voiceflow.com/project/6b0e16df0369ea7ad5c776f7/transcripts/6b0e17185a668e418890e3d5"},"logs":[{"type":"action","data":{"type":"launch","payload":null},"createdAt":"2026-12-01T00:38:48.470Z","updatedAt":"2026-12-01T00:38:48.470Z"},{"type":"trace","data":{"type":"debug","payload":{"type":"compile","message":"compiled the draft"}},"createdAt":"2026-12-01T00:38:48.913Z","updatedAt":"2026-12-01T00:38:48.913Z"},{"type":"trace","data":{"type":"text","payload":{"message":"Hi! I'm the Northwind Coffee assistant. How can I help?","delay":0}},"createdAt":"2026-12-01T00:38:49.207Z","updatedAt":"2026-12-01T00:38:49.207Z"},{"type":"action","data":{"type":"text","payload":"what time do you open on saturday?"},"createdAt":"2026-12-01T00:38:55.031Z","updatedAt":"2026-12-01T00:38:55.031Z"},{"type":"trace","data":{"type":"knowledgeBase","payload":{"query":"opening hours saturday","chunks":[{"documentID":"6b0e1705e464c9bb0d1d2e30","score":0.4477}]}},"createdAt":"2026-12-01T00:38:56.402Z","updatedAt":"2026-12-01T00:38:56.402Z"},{"type":"trace","data":{"type":"text","payload":{"message":"On Saturdays we open at 8:00 am.","delay":0}},"createdAt":"2026-12-01T00:38:57.880Z","updatedAt":"2026-12-01T00:38:57.880Z"},{"type":"end","data":{},"createdAt":"2026-12-01T00:39:02.118Z","updatedAt":"2026-12-01T00:39:02.118Z"}]} diff --git a/internal/cli/undecoded_test.go b/internal/cli/undecoded_test.go new file mode 100644 index 00000000..2296108a --- /dev/null +++ b/internal/cli/undecoded_test.go @@ -0,0 +1,84 @@ +// This file is not generated by Speakeasy. It covers output/undecoded.go and +// client/keepanswer.go: a read's answer that vf's types can't hold prints as +// Voiceflow sent it, in every format, instead of failing. The transcript is +// round 5's `transcript get --format-param logs`, whose logs carry a date +// and time where the spec says a date. + +package cli + +import ( + "io" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// servingAnswer serves body, with status, for every request. +func servingAnswer(t *testing.T, status int, body string) string { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _, _ = io.WriteString(w, body) + })) + t.Cleanup(srv.Close) + return srv.URL +} + +func TestTranscriptLogsPrintInEveryFormat(t *testing.T) { + logs, err := os.ReadFile("testdata/transcript-logs.json") + if err != nil { + t.Fatal(err) + } + url := servingAnswer(t, http.StatusOK, string(logs)) + args := []string{"transcript", "get", "-p", "6b0e16df0369ea7ad5c776f7", "-t", "6b0e17185a668e418890e3d5", "--format-param", "logs"} + for _, c := range []struct { + name string + agent bool + extra []string + }{ + {"pretty", false, nil}, + {"yaml", false, []string{"-o", "yaml"}}, + {"table", false, []string{"-o", "table"}}, + {"toon, agent mode", true, nil}, + {"json", false, []string{"-o", "json"}}, + } { + t.Run(c.name, func(t *testing.T) { + stdout, stderr, err := runArgs(t, url, c.agent, append(append([]string{}, args...), c.extra...)...) + if err != nil { + t.Fatalf("exit %d: %v\n%s", output.ExitCode(err), err, stderr) + } + for _, want := range []string{"On Saturdays we open at 8:00 am.", "00:38:57.880"} { + if !strings.Contains(stdout, want) { + t.Errorf("stdout lacks %q:\n%s", want, stdout) + } + } + if strings.Contains(stderr, "couldn't read the response") { + t.Errorf("stderr:\n%s", stderr) + } + }) + } +} + +// Any read does the same: here an environment whose release has no date. +func TestAReadVfCantDecodePrintsAsSent(t *testing.T) { + url := servingAnswer(t, http.StatusOK, `{"environment":{"name":"Main","alias":"main","isMain":true,"createdAt":"soon","trafficPercentage":100,"releases":[]}}`) + stdout, stderr, err := runArgs(t, url, false, "environment", "get", "-p", "p1", "-e", "main") + if err != nil || !strings.Contains(stdout, "soon") { + t.Errorf("err %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr) + } +} + +// A write's answer that vf can't decode still fails: its command may have +// more to do with the answer than print it. +func TestAWriteVfCantDecodeStillFails(t *testing.T) { + url := servingAnswer(t, http.StatusCreated, `{"playbook":{"id":5,"name":"Returns"}}`) + _, stderr, err := runArgs(t, url, false, "playbook", "create", "-p", "p1", "-e", "main", "--name", "Returns") + if output.ExitCode(err) != output.ExitFailure || !strings.Contains(stderr, "couldn't read the response") { + t.Errorf("exit %d\n%s", output.ExitCode(err), stderr) + } +} diff --git a/internal/client/client.go b/internal/client/client.go index ead725a0..c9b87a78 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -53,6 +53,7 @@ func NewClient(cmd *cobra.Command) (*sdk.VoiceflowSDK, error) { if testClient := testclient.NewTestHTTPClient(); testClient != nil { httpClient = testClient } + httpClient = WrapClientToKeepAnswers(httpClient) // keepanswer.go: a read's answer the SDK can't decode still prints 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) diff --git a/internal/client/keepanswer.go b/internal/client/keepanswer.go new file mode 100644 index 00000000..7be2692a --- /dev/null +++ b/internal/client/keepanswer.go @@ -0,0 +1,69 @@ +// This file is not generated by Speakeasy. It keeps a read's answer as it +// arrives, so that when the SDK can't decode it, vf can still print it +// (internal/output/undecoded.go). +// +// The SDK reads the body, fails to decode it and returns only the error, so +// the body is gone by the time the command reports. This keeps a copy of +// the body of a successful GET that answers JSON as the SDK reads it, and +// forgets it when the next request starts. Nothing else changes: the SDK +// reads the same bytes at the same time. + +package client + +import ( + "bytes" + "io" + "mime" + "net/http" + + "github.com/voiceflow/cli/internal/output" +) + +// maxKept is the largest answer kept. A larger one fails as before. +const maxKept = 64 << 20 + +// WrapClientToKeepAnswers keeps each read's JSON answer until the next +// request. +func WrapClientToKeepAnswers(inner HTTPClient) HTTPClient { + return &answerKeeper{inner: inner} +} + +type answerKeeper struct{ inner HTTPClient } + +func (k *answerKeeper) Do(req *http.Request) (*http.Response, error) { + output.ForgetAnswer() + res, err := k.inner.Do(req) + if err != nil || res == nil || res.Body == nil || req.Method != http.MethodGet || res.StatusCode/100 != 2 { + return res, err + } + if media, _, _ := mime.ParseMediaType(res.Header.Get("Content-Type")); media != "application/json" { + return res, err + } + res.Body = &keptBody{ReadCloser: res.Body, res: res} + return res, err +} + +// keptBody copies what is read through it, and keeps the answer once the +// whole of it has been read. +type keptBody struct { + io.ReadCloser + res *http.Response + copy bytes.Buffer + full bool // more than maxKept +} + +func (b *keptBody) Read(p []byte) (int, error) { + n, err := b.ReadCloser.Read(p) + if !b.full { + if b.copy.Len()+n > maxKept { + b.full = true + b.copy = bytes.Buffer{} + } else { + b.copy.Write(p[:n]) + } + } + if err == io.EOF && !b.full { + output.KeepAnswer(b.res, b.copy.Bytes()) + } + return n, err +} diff --git a/internal/output/output.go b/internal/output/output.go index 46adbe5f..578c044c 100644 --- a/internal/output/output.go +++ b/internal/output/output.go @@ -398,6 +398,9 @@ func Error(cmd *cobra.Command, err error) error { if isAboutDryRunResponse(cmd, err) { return nil } + if printed, perr := printUndecoded(cmd, err); printed { // undecoded.go: a read's answer vf's types can't hold prints as sent + return perr + } format := resolveOutputFormat(cmd) jqExpr, _ := flagutil.GetStringFlag(cmd, "jq") diff --git a/internal/output/undecoded.go b/internal/output/undecoded.go new file mode 100644 index 00000000..a7956444 --- /dev/null +++ b/internal/output/undecoded.go @@ -0,0 +1,73 @@ +// This file is not generated by Speakeasy. It prints a read's answer as +// Voiceflow sent it when vf's types can't hold it, instead of failing. +// +// Every format but -o json decodes the answer into the SDK's types first, +// and a field the spec describes wrongly fails the whole command. +// `transcript get --format-param logs` failed in pretty, YAML and table +// output, "could not unmarshal … update vf", because the spec gives each +// log's createdAt as a date and the API sends a date and time; -o json, +// which prints the body as sent, worked. +// +// internal/client/keepanswer.go keeps the body of the latest successful GET +// that answered JSON. When the SDK then can't decode that body, Error prints +// it as the result instead, through Result, in the format asked for, and the +// command succeeds, as -o json would have. Only reads: a write's command +// may have more to do with its answer (wait for it, check it), so a write +// still fails as before. + +package output + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "strings" + "sync" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/sdk/models/components" +) + +var kept struct { + sync.Mutex + res *http.Response + body []byte +} + +// KeepAnswer remembers res, a read's answer, with its whole body, until the +// next request. +func KeepAnswer(res *http.Response, body []byte) { + kept.Lock() + defer kept.Unlock() + kept.res, kept.body = res, body +} + +// ForgetAnswer drops the answer kept, as a new request starts. +func ForgetAnswer() { KeepAnswer(nil, nil) } + +// asSent is an answer as Voiceflow sent it, in the shape Result prints. +type asSent struct { + HTTPMeta components.HTTPMetadata + Answer any +} + +// printUndecoded prints the answer kept as the result, when err says the +// SDK couldn't decode it. It reports whether it did. +func printUndecoded(cmd *cobra.Command, err error) (bool, error) { + if err == nil || !strings.Contains(err.Error(), "error unmarshaling json response body") { + return false, nil + } + kept.Lock() + res, body := kept.res, kept.body + kept.res, kept.body = nil, nil + kept.Unlock() + var answer any + if res == nil || json.Unmarshal(body, &answer) != nil { + return false, nil + } + sent := *res + sent.Body = io.NopCloser(bytes.NewReader(body)) + return true, Result(cmd, &asSent{HTTPMeta: components.HTTPMetadata{Request: res.Request, Response: &sent}, Answer: answer}) +} From c440352f5b4096e84262087986e43e86b47761ee Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:11:13 -0500 Subject: [PATCH 23/31] feat(environment): export saves a whole environment as JSON A migrator had no way to take a project out of Voiceflow with vf. The API has an export endpoint, GET /v2/stable/environment/{alias}/export, but the spec marks it x-speakeasy-ignore, so the SDK has no method for it and no command was generated. sdk/environmentexport.go adds Environment.Export, written as Speakeasy writes Environment.Get: same server URL, credential, hooks and HTTP client, so --dry-run, --debug, --timeout, -H and a missing token behave as for any other call, and an error status is the usual SDK error (a 404 exits 4). The answer is left unread. `vf environment export -p -e [--file path]` prints the export as JSON, indented, in agent mode too, or writes it to --file once the whole answer has arrived, replacing the file, and says where and how big. -o and --jq apply when given. A dry run writes nothing. --- internal/cli/environment/export.go | 187 +++++++++++++++++++++++++ internal/cli/environment/root.go | 2 + internal/cli/environmentexport_test.go | 146 +++++++++++++++++++ internal/sdk/environmentexport.go | 151 ++++++++++++++++++++ 4 files changed, 486 insertions(+) create mode 100644 internal/cli/environment/export.go create mode 100644 internal/cli/environmentexport_test.go create mode 100644 internal/sdk/environmentexport.go diff --git a/internal/cli/environment/export.go b/internal/cli/environment/export.go new file mode 100644 index 00000000..7c68b13a --- /dev/null +++ b/internal/cli/environment/export.go @@ -0,0 +1,187 @@ +// This file is not generated by Speakeasy. It adds `vf environment export`, +// which saves a whole environment as one JSON document. +// +// A migrator had no way to take a project out of Voiceflow with vf: the API +// has an export endpoint, but the spec hides it from the SDK +// (x-speakeasy-ignore), so no command was generated for it. This one calls +// it through sdk.Environment.Export (internal/sdk/environmentexport.go), +// with the same credential, flags and errors as every other command, and +// writes the answer to --file, or prints it. +// +// The export is JSON, so that is what prints, in agent mode too, indented +// so a saved file reads and diffs line by line. -o and --jq still apply +// when given. --file writes the file only once the whole answer has +// arrived, so a read cut off by --timeout leaves an existing file as it +// was; a dry run writes nothing. + +package environment + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/interactive" + "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/ui" + "github.com/voiceflow/cli/internal/usage" +) + +var exportCmdMeta = []flagutil.FlagMeta{ + {FlagName: "environment-alias", Shorthand: "e", FieldPath: "EnvironmentAlias", Kind: flagutil.FlagKindString, Required: true, Description: "[required]"}, + {FlagName: "project-id", Shorthand: "p", FieldPath: "ProjectID", Kind: flagutil.FlagKindString, Required: true, Description: "[required]"}, +} + +// addExportCmd gives the environment group export. Its metadata is fixed, +// so a mistake in it is a bug any test that builds the commands finds. +func addExportCmd(parent *cobra.Command) { + cmd := &cobra.Command{ + Use: "export", + Short: "Export environment", + Long: "Export everything in an environment as one JSON document, often 100KB and more: " + + "the project and agent, workflows and their diagrams, playbooks, tools, functions, variables, " + + "messages, prompts, knowledge base settings and the rest. Prints it, or writes it to --file. " + + "Rich text is a string, with {name} for a variable, entity or secret reference.", + Example: " vf environment export --project-id --environment-alias main --file export.json", + RunE: runExportCmd, + } + flagutil.RegisterFlags(cmd, exportCmdMeta) + if err := flagutil.ValidateMeta[sdk.EnvironmentExportRequest](exportCmdMeta); err != nil { + panic("environment export: " + err.Error()) + } + cmd.Flags().String("file", "", "Write the export to this file, replacing what is there, instead of printing it.") + parent.AddCommand(cmd) +} + +// exported is the export as Voiceflow sent it, for -o and --jq. +type exported struct { + HTTPMeta components.HTTPMetadata + Export any +} + +// written says where --file put the export. Result prints what a +// response holds, so the summary is held like one. +type written struct { + Written struct { + File string `json:"file"` + Bytes int `json:"bytes"` + } +} + +func runExportCmd(cmd *cobra.Command, args []string) error { + if usage.UsageRequested(cmd) { + return usage.EmitSchema(cmd, cmd.OutOrStdout()) + } + if interactive.ShouldPrompt(cmd, exportCmdMeta) { + if err := interactive.PromptAndSetFlags(cmd, exportCmdMeta); err != nil { + return err + } + } + req, err := flagutil.BuildRequest[sdk.EnvironmentExportRequest](cmd, exportCmdMeta, "", "") + if err != nil { + return err + } + file, _ := cmd.Flags().GetString("file") + s, err := client.NewClient(cmd) + if err != nil { + return err + } + opts, err := output.PrepareCallOpts(cmd) + if err != nil { + return err + } + ctx := client.WithSpinnerMessage(cmd.Context(), "Exporting environment "+req.EnvironmentAlias+"…") + res, err := s.Environment.Export(ctx, *req, opts...) + if err != nil { + return output.Error(cmd, err) + } + httpRes := res.HTTPMeta.Response + raw, err := io.ReadAll(httpRes.Body) + httpRes.Body.Close() + if err != nil { + return output.Error(cmd, fmt.Errorf("reading the response: %w", err)) // a cut-off read reports as a timeout + } + if client.IsDryRun(cmd) { + if file != "" { + fmt.Fprintf(cmd.ErrOrStderr(), "[DRY-RUN] Would write the export to %s.\n", file) + } + return nil + } + var doc bytes.Buffer + if err := json.Indent(&doc, raw, "", " "); err != nil { + return output.Report(cmd, output.Explanation{ + Type: "unexpected_response", + Title: "Voiceflow's export wasn't JSON, so vf wrote nothing", + Next: []string{"'--debug' shows the raw response"}, + }, err) + } + doc.WriteByte('\n') + + if file != "" { + return writeExport(cmd, req, file, doc.Bytes()) + } + if explicit(cmd) { + var v any + d := json.NewDecoder(bytes.NewReader(raw)) + d.UseNumber() + if err := d.Decode(&v); err != nil { + return output.Error(cmd, err) + } + httpRes.Body = io.NopCloser(bytes.NewReader(raw)) + return output.Result(cmd, &exported{HTTPMeta: res.HTTPMeta, Export: v}) + } + _, err = cmd.OutOrStdout().Write(doc.Bytes()) + return err +} + +// explicit is whether -o or --jq asks for something other than the JSON +// an export is. +func explicit(cmd *cobra.Command) bool { + jq, _ := flagutil.GetStringFlag(cmd, "jq") + return jq != "" || cmd.Flags().Changed("output-format") +} + +// writeExport writes doc to file and says so. +func writeExport(cmd *cobra.Command, req *sdk.EnvironmentExportRequest, file string, doc []byte) error { + if err := os.WriteFile(file, doc, 0o644); err != nil { + return output.Report(cmd, output.Explanation{ + Type: "file_error", + Title: "vf couldn't write the export to " + file, + Why: []string{err.Error()}, + Next: []string{"Check that the folder exists and can be written to, or leave out --file to print the export"}, + }, err) + } + if !output.ForAPerson(cmd) { + path, err := filepath.Abs(file) + if err != nil { + path = file + } + var w written + w.Written.File, w.Written.Bytes = path, len(doc) + return output.Result(cmd, &w) + } + u := output.UI(cmd, cmd.OutOrStdout()) + _, err := fmt.Fprintln(cmd.OutOrStdout(), u.Status(ui.StatusDone, + fmt.Sprintf("Exported environment %s to %s (%s).", req.EnvironmentAlias, file, size(len(doc))))) + return err +} + +// size is n bytes, for a person. +func size(n int) string { + switch { + case n < 1024: + return fmt.Sprintf("%d bytes", n) + case n < 1024*1024: + return fmt.Sprintf("%d KB", (n+512)/1024) + } + return fmt.Sprintf("%.1f MB", float64(n)/(1024*1024)) +} diff --git a/internal/cli/environment/root.go b/internal/cli/environment/root.go index 7d518e03..5ccf907d 100644 --- a/internal/cli/environment/root.go +++ b/internal/cli/environment/root.go @@ -69,6 +69,8 @@ func InitEnvironmentRoot(parent *cobra.Command) error { return err } + addExportCmd(EnvironmentCmd) // export.go: the API's export, which the spec hides from the SDK + parent.AddCommand(EnvironmentCmd) return nil } diff --git a/internal/cli/environmentexport_test.go b/internal/cli/environmentexport_test.go new file mode 100644 index 00000000..1277ea83 --- /dev/null +++ b/internal/cli/environmentexport_test.go @@ -0,0 +1,146 @@ +// This file is not generated by Speakeasy. It covers environment/export.go +// and sdk/environmentexport.go: `vf environment export` reads the API's +// export, which the spec hides from the SDK, and prints it or writes it to +// --file as Voiceflow sent it. + +package cli + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/voiceflow/cli/internal/output" +) + +// anExport has keys out of order, a number too big for a float and text a +// re-encoding would escape, so only the bytes as sent pass. +const anExport = `{"version":{"_id":"v1","name":"Initial"},"project":{"name":"Northwind","seed":9007199254740993},"messages":[{"text":"Returns & exchanges today"}],"diagrams":{}}` + +// exportServer serves anExport for environment main of project p1, and a +// 404 for any other. +func exportServer(t *testing.T) (url string, requests func() []*http.Request) { + t.Helper() + var mu sync.Mutex + var got []*http.Request + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + got = append(got, r.Clone(r.Context())) + mu.Unlock() + w.Header().Set("Content-Type", "application/json; charset=utf-8") + if r.Method != http.MethodGet || r.URL.Path != "/v2/stable/environment/main/export" || r.URL.Query().Get("projectID") != "p1" { + w.WriteHeader(http.StatusNotFound) + io.WriteString(w, `{"message":"Environment not found"}`) + return + } + io.WriteString(w, anExport) + })) + t.Cleanup(srv.Close) + return srv.URL, func() []*http.Request { + mu.Lock() + defer mu.Unlock() + return append([]*http.Request(nil), got...) + } +} + +// indented is anExport as the command prints and saves it. +func indented(t *testing.T) string { + t.Helper() + var b bytes.Buffer + if err := json.Indent(&b, []byte(anExport), "", " "); err != nil { + t.Fatal(err) + } + return b.String() + "\n" +} + +func TestEnvironmentExportPrintsTheJSONAsSent(t *testing.T) { + for _, agent := range []bool{false, true} { + url, requests := exportServer(t) + stdout, stderr, err := runArgs(t, url, agent, "environment", "export", "-p", "p1", "-e", "main") + if err != nil { + t.Fatalf("agent %v: %v\n%s", agent, err, stderr) + } + if stdout != indented(t) { + t.Errorf("agent %v: stdout\n%s\nwant\n%s", agent, stdout, indented(t)) + } + reqs := requests() + if len(reqs) != 1 || !strings.Contains(reqs[0].Header.Get("Authorization"), "vfp_fake") { + t.Errorf("agent %v: requests %v", agent, reqs) + } + } +} + +func TestEnvironmentExportWritesTheFile(t *testing.T) { + file := filepath.Join(t.TempDir(), "export.json") + if err := os.WriteFile(file, []byte("an older export, longer than the new one is: "+strings.Repeat("x", 500)), 0o644); err != nil { + t.Fatal(err) + } + url, _ := exportServer(t) + stdout, stderr, err := runArgs(t, url, false, "environment", "export", "-p", "p1", "-e", "main", "--file", file) + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + saved, _ := os.ReadFile(file) + if string(saved) != indented(t) { + t.Errorf("file\n%s\nwant\n%s", saved, indented(t)) + } + if want := "Exported environment main to " + file + " ("; !strings.HasPrefix(stdout, want) { + t.Errorf("stdout %q, want it to start %q", stdout, want) + } + + stdout, stderr, err = runArgs(t, url, true, "environment", "export", "-p", "p1", "-e", "main", "--file", file) + if err != nil { + t.Fatalf("agent mode: %v\n%s", err, stderr) + } + if !strings.Contains(stdout, file) || !strings.Contains(stdout, "bytes") || strings.Contains(stdout, "Northwind") { + t.Errorf("agent mode stdout:\n%s", stdout) + } +} + +func TestEnvironmentExportTakesJqAndOutputFormat(t *testing.T) { + url, _ := exportServer(t) + stdout, stderr, err := runArgs(t, url, false, "environment", "export", "-p", "p1", "-e", "main", "--jq", ".project.name") + if err != nil || strings.TrimSpace(stdout) != "Northwind" { + t.Errorf("--jq: %v %q\n%s", err, stdout, stderr) + } + stdout, stderr, err = runArgs(t, url, false, "environment", "export", "-p", "p1", "-e", "main", "-o", "yaml") + if err != nil || !strings.Contains(stdout, "name: Northwind") { + t.Errorf("-o yaml: %v\n%s\n%s", err, stdout, stderr) + } +} + +func TestEnvironmentExportNotFound(t *testing.T) { + file := filepath.Join(t.TempDir(), "export.json") + url, _ := exportServer(t) + stdout, stderr, err := runArgs(t, url, false, "environment", "export", "-p", "p1", "-e", "staging", "--file", file) + if output.ExitCode(err) != output.ExitNotFound || stdout != "" { + t.Errorf("exit %d, stdout %q\n%s", output.ExitCode(err), stdout, stderr) + } + if _, statErr := os.Stat(file); !os.IsNotExist(statErr) { + t.Errorf("a failed export wrote %s", file) + } +} + +func TestEnvironmentExportDryRunWritesNothing(t *testing.T) { + file := filepath.Join(t.TempDir(), "export.json") + url, requests := exportServer(t) + stdout, stderr, err := runArgs(t, url, false, "environment", "export", "-p", "p1", "-e", "main", "--file", file, "--dry-run") + if err != nil || stdout != "" || len(requests()) != 0 { + t.Fatalf("err %v, stdout %q, %d requests\n%s", err, stdout, len(requests()), stderr) + } + for _, want := range []string{"[DRY-RUN] Would send: GET " + url + "/v2/stable/environment/main/export?projectID=p1", "[DRY-RUN] Would write the export to " + file + "."} { + if !strings.Contains(stderr, want) { + t.Errorf("stderr lacks %q:\n%s", want, stderr) + } + } + if _, statErr := os.Stat(file); !os.IsNotExist(statErr) { + t.Errorf("a dry run wrote %s", file) + } +} diff --git a/internal/sdk/environmentexport.go b/internal/sdk/environmentexport.go new file mode 100644 index 00000000..56d350bb --- /dev/null +++ b/internal/sdk/environmentexport.go @@ -0,0 +1,151 @@ +// This file is not generated by Speakeasy. It adds Environment.Export, the +// one call `vf environment export` makes (internal/cli/environment/export.go). +// +// The spec marks StableEnvironmentController_exportV2, GET +// /v2/stable/environment/{environmentAlias}/export, x-speakeasy-ignore, so +// the SDK has no method for it and vf had no way to save a project to a +// file. This is that method, written as Speakeasy writes Environment.Get: +// the same server URL, credential, hooks and HTTP client, so --dry-run, +// --debug, --timeout, -H and a missing token behave as they do for every +// other call, and an error status is the same SDKDefaultError. The answer +// is JSON, often 100KB and more, and is left unread for the command to +// write out as sent: there is no type to decode it into. +// +// If the operation is ever generated, environment.go gains its own Export +// and this file stops compiling: delete it then. + +package sdk + +import ( + "context" + "fmt" + "net/http" + + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/sdk/models/sdkerrors" + "github.com/voiceflow/cli/internal/sdk/sdkinternal/hooks" + "github.com/voiceflow/cli/internal/sdk/sdkinternal/utils" +) + +// EnvironmentExportRequest names the environment to export. +type EnvironmentExportRequest struct { + EnvironmentAlias string `pathParam:"style=simple,explode=false,name=environmentAlias"` + ProjectID string `queryParam:"style=form,explode=true,name=projectID"` +} + +// EnvironmentExportResponse holds the export unread in HTTPMeta.Response. +type EnvironmentExportResponse struct { + HTTPMeta components.HTTPMetadata +} + +// Export reads the whole environment: its agent, workflows, playbooks, +// tools, variables, messages, prompts and the rest, as one JSON document. +func (s *Environment) Export(ctx context.Context, request EnvironmentExportRequest, opts ...operations.Option) (*EnvironmentExportResponse, error) { + o := operations.Options{} + supportedOptions := []string{ + operations.SupportedOptionTimeout, + operations.SupportedOptionSkipDeserialization, + } + + for _, opt := range opts { + if err := opt(&o, supportedOptions...); err != nil { + return nil, fmt.Errorf("error applying option: %w", err) + } + } + + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } + opURL, err := utils.GenerateURL(ctx, baseURL, "/v2/stable/environment/{environmentAlias}/export", request, nil) + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + hookCtx := hooks.HookContext{ + SDK: s.rootSDK, + SDKConfiguration: s.sdkConfiguration, + BaseURL: baseURL, + Context: ctx, + OperationID: "StableEnvironmentController_exportV2", + SecuritySource: s.sdkConfiguration.Security, + } + + timeout := o.Timeout + if timeout == nil { + timeout = s.sdkConfiguration.Timeout + } + + if timeout != nil { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, *timeout) + defer cancel() + } + + req, err := http.NewRequestWithContext(ctx, "GET", opURL, nil) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + + if err := utils.PopulateQueryParams(ctx, req, request, nil, nil); err != nil { + return nil, fmt.Errorf("error populating query params: %w", err) + } + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + for k, v := range o.SetHeaders { + req.Header.Set(k, v) + } + + req, err = s.hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{"4XX", "5XX"}, httpRes.StatusCode) { + _httpRes, err := s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + if httpRes.StatusCode == 200 && utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`) { + return &EnvironmentExportResponse{HTTPMeta: components.HTTPMetadata{Request: req, Response: httpRes}}, nil + } + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + switch { + case httpRes.StatusCode == 200: + return nil, sdkerrors.NewSDKDefaultError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + case httpRes.StatusCode >= 400 && httpRes.StatusCode < 600: + return nil, sdkerrors.NewSDKDefaultError("API error occurred", httpRes.StatusCode, string(rawBody), httpRes) + default: + return nil, sdkerrors.NewSDKDefaultError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } +} From a8e0871d65f06b0ba35f383792633bd6793b5c74 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:47:45 -0500 Subject: [PATCH 24/31] fix(cli): a missing-flag hint repeats the flags typed, and shows an enum's values MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `conversation send -p … --text hello --no-interactive` was told to run `vf conversation send --action "{\"payload\":\"hello\",…}" --project-id … --text hello …`, and vf refuses that line: "--text and --action both say what to send". The hint was built from every flag set by the time the request was built, and send had set --action itself from --text. `document create-table --csv` sets --items and --schema the same way. Each command now notes the flags its line set as it starts, before its own code sets any (typedflags.go), and the "Pass them:" line repeats only those. A flag left out shows the values it takes where its help lists them, `--version-param ` rather than ``, and a true/false one is written `--flag=`, since `--flag false` leaves "false" a stray word. --- internal/cli/missingflags.go | 74 +++++++++++++++++++++++++++---- internal/cli/missingflags_test.go | 28 ++++++++++++ internal/cli/root.go | 1 + internal/cli/typedflags.go | 50 +++++++++++++++++++++ 4 files changed, 145 insertions(+), 8 deletions(-) create mode 100644 internal/cli/typedflags.go diff --git a/internal/cli/missingflags.go b/internal/cli/missingflags.go index 8661fd70..7f00fe52 100644 --- a/internal/cli/missingflags.go +++ b/internal/cli/missingflags.go @@ -7,11 +7,18 @@ // given: `vf conversation send -u x` said "Pass it: `vf conversation send // --project-id `", without -u, and named --environment-alias only // on the next run. +// +// The command line is built from the flags typed, not from what vf made of +// them. `send --text hello` sets --action itself, and the line repeated it +// next to --text, a pair vf refuses ("--text and --action both say what to +// send"). A flag left out shows its choices where it has some, +// `--version-param `, not ``. package cli import ( "regexp" + "slices" "strings" "github.com/spf13/cobra" @@ -98,22 +105,73 @@ func explainMissingFlags(cmd *cobra.Command, flags []string) output.Explanation } // commandLineWith is the command line that runs cmd with the flags it was -// given and the missing ones added, each as : vf conversation send -// --user-id x --project-id . Global flags are left out. +// given and the missing ones added, each as a placeholder: vf conversation +// send --user-id x --project-id . Global flags are left out. func commandLineWith(cmd *cobra.Command, missing []string) string { + words := typedLine(cmd) + for _, name := range missing { + if stand := flagutil.StandInFor(cmd, name); stand != "" { + name = stand // the simpler way to give it + } + words = append(words, leftOut(cmd, name)) + } + return strings.Join(words, " ") +} + +// typedLine is cmd's path and the flags typed on its command line, each as +// it would be written again, in the order help lists them, but for those +// named in except, which the caller gives anew. Global flags are left out, +// and so is a flag vf set from another (typedflags.go). +func typedLine(cmd *cobra.Command, except ...string) []string { words := []string{cmd.CommandPath()} cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { - if f.Changed { + if typed(cmd, f) && !slices.Contains(except, f.Name) { words = append(words, givenFlag(f)...) } }) - for _, name := range missing { - if stand := flagutil.StandInFor(cmd, name); stand != "" { - name = stand // the simpler way to give it + return words +} + +// leftOut is flag name of cmd as a hint shows it when it wasn't given: +// --version-param , --user-id , and a true/false +// flag as --wait=, since `--wait false` would leave "false" a +// stray word. +func leftOut(cmd *cobra.Command, name string) string { + f := cmd.Flags().Lookup(name) + switch { + case f == nil: + return "--" + name + " " + case f.Value.Type() == "bool": + return "--" + name + "=" + } + if choices := flagChoices(f); len(choices) > 0 { + return "--" + name + " <" + strings.Join(choices, "|") + ">" + } + return "--" + name + " " +} + +// optionsRE finds the values an enum flag takes in its help: "Whether to +// run the draft or published version. (options: draft, published)", or the +// whole of it, "options: draft, published [required]". +var optionsRE = regexp.MustCompile(`(?:^|\()options: ([^()\[\]]+?)\s*(?:\)|\[|$)`) + +// flagChoices are the values f takes when it takes only some, as its help +// lists them, or nil. A list too long to read in a command line is nil. +func flagChoices(f *pflag.Flag) []string { + m := optionsRE.FindStringSubmatch(f.Usage) + if m == nil { + return nil + } + choices := strings.Split(m[1], ", ") + if len(choices) > 8 { + return nil + } + for _, c := range choices { + if !plainWord.MatchString(c) { + return nil } - words = append(words, "--"+name, "") } - return strings.Join(words, " ") + return choices } // givenFlag is f as it would be written again on a command line. A secret diff --git a/internal/cli/missingflags_test.go b/internal/cli/missingflags_test.go index 269ad1b0..e54bc9b8 100644 --- a/internal/cli/missingflags_test.go +++ b/internal/cli/missingflags_test.go @@ -159,3 +159,31 @@ func TestAMissingActionNamesText(t *testing.T) { } } } + +// round-5 human-poweruser: `send -p … --text hello --no-interactive` was told +// "Pass them: `vf conversation send --action "{\"payload\":\"hello\",…}" +// --project-id … --text hello …`", and vf refuses --text with --action. The +// line repeats the flags typed, not the --action vf made of --text. +// --version-param is left out: it defaults to draft. +func TestTheCommandLineRepeatsOnlyWhatWasTyped(t *testing.T) { + x := runWithStdin(t, "", "conversation", "send", "-p", "p1", "--text", "hello") + want := "Pass them: `vf conversation send --project-id p1 --text hello --user-id --environment-alias `" + if all := explained(x); !strings.Contains(all, want) || strings.Contains(all, "--action") { + t.Errorf("want %q, and no --action, in:\n%s", want, all) + } +} + +// A flag left out shows the values it takes, and a true/false one is given +// with =, since `--flag false` would leave "false" a stray word. +func TestALeftOutFlagShowsItsChoices(t *testing.T) { + cmd := &cobra.Command{Use: "get"} + cmd.Flags().String("type", "", "The type of the tool to fetch. (options: api, mcp, function) [required]") + cmd.Flags().String("version-param", "", "options: draft, published [required]") + cmd.Flags().String("name", "", "Its name (options: are, not given here") + cmd.Flags().Bool("enabled", false, "") + got := commandLineWith(cmd, []string{"type", "version-param", "name", "enabled"}) + want := "get --type --version-param --name --enabled=" + if got != want { + t.Errorf("got %s\nwant %s", got, want) + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index cde93699..67e9ccc6 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -245,6 +245,7 @@ func NewRootCommand() (*cobra.Command, error) { rejectStrayArgs(rootCmd) // strayargs.go: a command that takes no arguments says so askFirst(rootCmd) // confirm.go: deletes and merges ask before they send, at a terminal offerStrict(rootCmd) // strict.go: --strict fails a write whose {tokens} didn't bind + noteTypedFlags(rootCmd) // typedflags.go: a suggested command repeats the flags typed, not those vf set describeBareFlags(rootCmd) // barehelp.go: a flag the spec left undescribed says what it is nameVFCommandsInHelp(rootCmd) // namehelp.go: vf's commands and flags, not MCP tools and API fields diff --git a/internal/cli/typedflags.go b/internal/cli/typedflags.go new file mode 100644 index 00000000..08c004f0 --- /dev/null +++ b/internal/cli/typedflags.go @@ -0,0 +1,50 @@ +// This file is not generated by Speakeasy. It notes which flags a command +// line set, so that a command vf suggests repeats those and no others. +// +// Some commands set flags of their own from the ones given: `conversation +// send --text hello` sets --action to {"type":"text","payload":"hello"}, and +// `document create-table --csv` sets --items and --schema. By the time a +// required flag turns out to be missing, those look given as well, and the +// "Pass them:" line repeated --action next to --text, which vf refuses. + +package cli + +import ( + "slices" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// typedFlagsNote is the annotation that lists, comma-separated, the flags a +// command's line set. +const typedFlagsNote = "vf:typed-flags" + +// noteTypedFlags has every command under root note the flags its line set +// as it starts, before its own code sets any. +func noteTypedFlags(root *cobra.Command) { + pre := root.PersistentPreRunE + root.PersistentPreRunE = func(cmd *cobra.Command, args []string) error { + var names []string + cmd.Flags().Visit(func(f *pflag.Flag) { names = append(names, f.Name) }) + if cmd.Annotations == nil { + cmd.Annotations = map[string]string{} + } + cmd.Annotations[typedFlagsNote] = strings.Join(names, ",") + if pre == nil { + return nil + } + return pre(cmd, args) + } +} + +// typed reports whether cmd's command line set f. Before cmd has started, +// as when its arguments are checked, every flag set is one typed. +func typed(cmd *cobra.Command, f *pflag.Flag) bool { + names, noted := cmd.Annotations[typedFlagsNote] + if !noted { + return f.Changed + } + return f.Changed && slices.Contains(strings.Split(names, ","), f.Name) +} From 0d89c8555a7c547c31907fb6b79e92d30cd04d70 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:50:35 -0500 Subject: [PATCH 25/31] fix(cli): a stray-word hint offers the whole line, with the flags typed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The command offered for a stray word was a piece of the line. `vf transcript get -p X` offered `vf transcript get --transcript-id ` without -p, which failed again for want of --project-id. `conversation send --text Hello there`, unquoted, sends "Hello" and leaves "there", and the hint offered `--text 'there'`, the message without its first word. Both hints are now the whole command line, built as the missing-flag hint is, from the flags typed: `vf transcript get --project-id X --transcript-id `, and `vf conversation send … --text 'Hello there'`. Words that come with --text are the rest of its message, and the line leaves out the --action that --text stands for, which vf refuses beside it. --- internal/cli/strayargs.go | 31 ++++++++++++++++++++++++++++--- internal/cli/strayargs_test.go | 23 ++++++++++++++++++++--- 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/internal/cli/strayargs.go b/internal/cli/strayargs.go index 5e20172b..581595db 100644 --- a/internal/cli/strayargs.go +++ b/internal/cli/strayargs.go @@ -14,6 +14,12 @@ // `) says so with Args and is left alone, as is a group, whose stray // words are unknownSubcommand's (errors.go), and the root, whose words are // the home prompt's. +// +// The command it offers in their place is the whole line, with the flags +// typed (missingflags.go). It used to be a piece of one: `transcript get +// -p X` offered `vf transcript get --transcript-id ` without -p, +// which then failed for want of --project-id, and `--text Hello there` +// offered `--text 'there'`, the message without its first word. package cli @@ -26,11 +32,13 @@ import ( "github.com/spf13/cobra" "github.com/spf13/pflag" + "github.com/voiceflow/cli/internal/flagutil" "github.com/voiceflow/cli/internal/output" ) // strayArgsError reports the arguments a command that takes none was given. type strayArgsError struct { + cmd *cobra.Command path string args []string flags bool // the command has flags of its own @@ -75,7 +83,7 @@ func noArgs(cmd *cobra.Command, args []string) error { // cobra checks arguments before PersistentPreRunE, the first place that // applies --agent-mode, and the flags are parsed by now. output.InitAgentMode(cmd) - return &strayArgsError{path: cmd.CommandPath(), args: args, flags: hasOwnFlags(cmd), text: cmd.Flags().Lookup("text") != nil, id: missingIDFlag(cmd)} + return &strayArgsError{cmd: cmd, path: cmd.CommandPath(), args: args, flags: hasOwnFlags(cmd), text: cmd.Flags().Lookup("text") != nil, id: missingIDFlag(cmd)} } // missingIDFlag is cmd's one required ID flag that wasn't given, such as @@ -107,11 +115,12 @@ func explainStrayArgs(err error) (output.Explanation, bool) { x := output.Explanation{Type: "usage_error", Title: e.Error(), Why: []string{"Nothing was run."}} if e.text { // `conversation send … hello there` is a message: say how to send it. - x.Next = append(x.Next, "To send it as a message: `--text "+shellQuote(strings.Join(e.args, " "))+"`") + x.Next = append(x.Next, "To send it as a message: `"+asMessage(e.cmd, e.args)+"`") } if e.id != "" && len(e.args) == 1 && !e.text { // `transcript get 6b0d…` meant the ID. - x.Next = append(x.Next, "To give it as the ID: `"+e.path+" --"+e.id+" "+shellWord(e.args[0])+"`") + line := append(typedLine(e.cmd), "--"+e.id, shellWord(e.args[0])) + x.Next = append(x.Next, "To give it as the ID: `"+strings.Join(line, " ")+"`") } if e.flags { x.Next = append(x.Next, "`"+e.path+" --help` lists its flags") @@ -123,6 +132,22 @@ func explainStrayArgs(err error) (output.Explanation, bool) { return x, true } +// asMessage is cmd's line with words sent as the message. Words that came +// with --text are the rest of its message, which needed quotes: `--text +// Hello there` sends 'Hello there'. --text takes the place of the flag it +// stands for, --action, which vf refuses beside it. +func asMessage(cmd *cobra.Command, words []string) string { + message := strings.Join(words, " ") + except := []string{"text"} + if f := cmd.Flags().Lookup("text"); f != nil { + if typed(cmd, f) { + message = f.Value.String() + " " + message + } + except = append(except, f.Annotations[flagutil.StandsFor]...) + } + return strings.Join(append(typedLine(cmd, except...), "--text", shellQuote(message)), " ") +} + // hasOwnFlags reports whether cmd has flags of its own to show in help. func hasOwnFlags(cmd *cobra.Command) bool { own := false diff --git a/internal/cli/strayargs_test.go b/internal/cli/strayargs_test.go index cd053583..ceb908f1 100644 --- a/internal/cli/strayargs_test.go +++ b/internal/cli/strayargs_test.go @@ -85,7 +85,7 @@ func TestAStrayArgumentIsNamedAndNothingIsSent(t *testing.T) { x := explainCLIError(cmd, err) want := `vf conversation send takes no arguments (got "hello", "there"); pass values with flags` if x.Type != "usage_error" || x.Title != want || !strings.Contains(explained(x), "`vf conversation send --help` lists its flags") || - !strings.Contains(explained(x), "To send it as a message: `--text 'hello there'`") { + !strings.Contains(explained(x), "To send it as a message: `vf conversation send --environment-alias main --project-id p1 --user-id u1 --version-param draft --text 'hello there'`") { t.Errorf("%s: got %+v", agent, x) } if got := output.IsAgentMode(); got != (agent == "--agent-mode=true") { @@ -120,7 +120,8 @@ func TestCobraNoArgsGetsTheSameError(t *testing.T) { // round-4 human-poweruser: `transcript get ` got a hint about quoting // spaces. A lone word on a command with one required ID flag not given is -// offered as that ID. +// offered as that ID. round 5: the line it offered dropped -p, and failed +// for want of --project-id; it keeps the flags typed. func TestALoneStrayWordIsOfferedAsTheID(t *testing.T) { root := testRoot(t) get := find(t, root, "transcript", "get") @@ -129,7 +130,23 @@ func TestALoneStrayWordIsOfferedAsTheID(t *testing.T) { } x, ok := explainStrayArgs(get.ValidateArgs([]string{"6b0dabc"})) all := explained(x) - if !ok || !strings.Contains(all, "To give it as the ID: `vf transcript get --transcript-id 6b0dabc`") || strings.Contains(all, "needs quotes") { + if !ok || !strings.Contains(all, "To give it as the ID: `vf transcript get --project-id p1 --transcript-id 6b0dabc`") || strings.Contains(all, "needs quotes") { t.Errorf("got:\n%s", all) } } + +// round-5 human-newcomer: `--text Hello there`, unquoted, sent "Hello" and +// left "there", and the hint offered `--text 'there'`. The words after +// --text are the rest of its message, and the line keeps the other flags. +func TestWordsAfterTextAreTheRestOfTheMessage(t *testing.T) { + root := testRoot(t) + send := find(t, root, "conversation", "send") + if err := send.ParseFlags([]string{"--text", "Hello", "there", "friend", "-u", "u1", "-v", "draft"}); err != nil { + t.Fatal(err) + } + x, _ := explainStrayArgs(send.ValidateArgs(send.Flags().Args())) + want := "To send it as a message: `vf conversation send --user-id u1 --version-param draft --text 'Hello there friend'`" + if all := explained(x); !strings.Contains(all, want) { + t.Errorf("want %q in:\n%s", want, all) + } +} From a6b5a1e11bda8ac7bd2c1c3677be3d09063b5ec8 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:55:06 -0500 Subject: [PATCH 26/31] fix(cli): "Did you mean" for a misspelt command or flag is the whole line `vf transcrpit search -p X` was asked "Did you mean `vf transcript`?" and `vf secret ls -p X` "Did you mean `vf secret list`?". Run as written, the first printed the group's help and the second asked for a project: the rest of the line was gone. A misspelt flag got only the flag, `--name`, to fit back into the line by hand. And a flag given no value was told "Give it one: `--version-param `", without the values it takes. The suggestion is now the line vf was run with, the misspelt word replaced, with the command's own flags as the missing-flag hint writes them (typofix.go): `vf transcript search --project-id X`, `vf workspace create --name "two words"`. The line is parsed into copies of the command's flags, so the real ones are left as they were. Where the fixed flag takes only some values and the one typed isn't among them (`tool get -t ` as --type), and in the home prompt, whose lines aren't vf's arguments, the hint names the command or flag alone, as before. A flag given no value shows its choices: `--version-param `. --- internal/cli/errors.go | 7 ++- internal/cli/typofix.go | 112 +++++++++++++++++++++++++++++++++++ internal/cli/typofix_test.go | 112 +++++++++++++++++++++++++++++++++++ 3 files changed, 228 insertions(+), 3 deletions(-) create mode 100644 internal/cli/typofix.go create mode 100644 internal/cli/typofix_test.go diff --git a/internal/cli/errors.go b/internal/cli/errors.go index 3d929430..535d6ce0 100644 --- a/internal/cli/errors.go +++ b/internal/cli/errors.go @@ -13,6 +13,7 @@ package cli import ( + "cmp" "context" "encoding/json" "errors" @@ -234,7 +235,7 @@ func explainCLIError(cmd *cobra.Command, err error) output.Explanation { 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, "Did you mean `"+cmp.Or(fixedLine(cmd.Root(), m[1], s), target.CommandPath()+" "+s)+"`?") // typofix.go: the whole line } x.Next = append(x.Next, "`"+target.CommandPath()+" --help` lists its commands") return x @@ -251,7 +252,7 @@ func explainCLIError(cmd *cobra.Command, err error) output.Explanation { near = shorthandElsewhere(cmd, m[1]) } for _, s := range near { - x.Next = append(x.Next, "Did you mean `--"+s+"`?") + x.Next = append(x.Next, "Did you mean `"+cmp.Or(fixedLine(cmd.Root(), name, "--"+s), "--"+s)+"`?") // typofix.go: the whole line } x.Next = append(x.Next, help+" lists its flags") return x @@ -262,7 +263,7 @@ func explainCLIError(cmd *cobra.Command, err error) output.Explanation { name = f.Name } x.Title = "--" + name + " needs a value" - x.Next = []string{"Give it one: `--" + name + " `", help + " shows what it takes"} + x.Next = []string{"Give it one: `" + leftOut(cmd, name) + "`", help + " shows what it takes"} // missingflags.go: return x } if m := badArgumentRE.FindStringSubmatch(msg); m != nil { diff --git a/internal/cli/typofix.go b/internal/cli/typofix.go new file mode 100644 index 00000000..649ebd91 --- /dev/null +++ b/internal/cli/typofix.go @@ -0,0 +1,112 @@ +// This file is not generated by Speakeasy. It makes the "Did you mean" for +// a misspelt command or flag the whole line, with the misspelling fixed. +// +// `vf transcrpit search -p X` was asked "Did you mean `vf transcript`?", +// and `vf secret ls -p X` "Did you mean `vf secret list`?": run as written, +// the first printed the group's help and the second asked for a project. +// The rest of the line was gone. A misspelt flag got only the flag, `--name`, +// to fit back into the line by hand. + +package cli + +import ( + "slices" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// fixedLine is the line vf was run with, the word wrong in it replaced by +// fix, as a hint offers it: the command it names, then the flags of its own +// the line gave (missingflags.go) and any other words. A misspelt flag, +// --nmae, or -z, keeps its value: `--nmae=x` becomes `--name=x`. It is "" +// when the line doesn't hold wrong, as in the home prompt, whose lines +// aren't vf's arguments, or when the fixed line names no command. +func fixedLine(root *cobra.Command, wrong, fix string) string { + words := slices.Clone(commandLine()) + i := slices.IndexFunc(words, func(w string) bool { + return w == wrong || (strings.HasPrefix(wrong, "-") && strings.HasPrefix(w, wrong+"=")) + }) + if i < 0 || slices.Contains(words[:i], "--") { + return "" + } + words[i] = fix + strings.TrimPrefix(words[i], wrong) + cmd, rest, err := root.Find(words) + if err != nil || cmd == nil || cmd == root { + return "" + } + if !strings.HasPrefix(fix, "-") && !slices.Contains(strings.Fields(cmd.CommandPath()), fix) { + return "" + } + flags := copyFlags(cmd) + if flags.Parse(rest) != nil { + return "" + } + line := []string{cmd.CommandPath()} + local := cmd.LocalFlags() + fits := true + flags.Visit(func(f *pflag.Flag) { + fixed := "--"+f.Name == fix + if choices := flagChoices(f); fixed && len(choices) > 0 && !slices.Contains(choices, f.Value.String()) { + fits = false // `tool get -t ` meant --tool-id, not --type + } + // The global flags typed are left out, as a missing-flag hint + // leaves them out, but for the one fixed: `--jqq .` is `--jq .`. + if local.Lookup(f.Name) != nil || fixed { + line = append(line, givenFlag(f)...) + } + }) + if !fits { + return "" + } + for _, arg := range flags.Args() { + line = append(line, shellWord(arg)) + } + return strings.Join(line, " ") +} + +// copyFlags is a flag set with a flag for each of cmd's, its own and those +// it inherits, that notes what it is given. Parsing a line into it leaves +// cmd's flags as they are. Flags it doesn't know are skipped. +func copyFlags(cmd *cobra.Command) *pflag.FlagSet { + flags := pflag.NewFlagSet(cmd.Name(), pflag.ContinueOnError) + flags.SetOutput(discard{}) + flags.ParseErrorsAllowlist.UnknownFlags = true + add := func(f *pflag.Flag) { + if flags.Lookup(f.Name) != nil { + return + } + var v pflag.Value = ¬edValue{typ: f.Value.Type()} + if _, ok := f.Value.(pflag.SliceValue); ok { + v = ¬edValues{notedValue{typ: f.Value.Type()}} + } + flags.AddFlag(&pflag.Flag{Name: f.Name, Shorthand: f.Shorthand, Usage: f.Usage, NoOptDefVal: f.NoOptDefVal, Value: v}) + } + cmd.LocalFlags().VisitAll(add) + cmd.InheritedFlags().VisitAll(add) + return flags +} + +// notedValue is a flag's value as given, whatever its type. +type notedValue struct { + typ string + values []string +} + +func (v *notedValue) Set(s string) error { v.values = append(v.values, s); return nil } +func (v *notedValue) Type() string { return v.typ } +func (v *notedValue) String() string { + if len(v.values) == 0 { + return "" + } + return v.values[len(v.values)-1] +} + +// notedValues is a list flag's values as given, each time it was. +type notedValues struct{ notedValue } + +func (v *notedValues) Append(s string) error { return v.Set(s) } +func (v *notedValues) Replace(s []string) error { v.values = s; return nil } +func (v *notedValues) GetSlice() []string { return v.values } +func (v *notedValues) String() string { return strings.Join(v.values, ",") } diff --git a/internal/cli/typofix_test.go b/internal/cli/typofix_test.go new file mode 100644 index 00000000..01150ea9 --- /dev/null +++ b/internal/cli/typofix_test.go @@ -0,0 +1,112 @@ +// This file is not generated by Speakeasy. It covers typofix.go: a "Did you +// mean" for a misspelt command or flag is the whole line, fixed. + +package cli + +import ( + "bytes" + "os" + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/output" +) + +// runAsMain runs args as main does, with them as the process's arguments, and +// returns the command that failed and how vf explains its error, as +// renderError would print it. +func runAsMain(t *testing.T, args ...string) (*cobra.Command, output.Explanation, error) { + t.Helper() + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + saved := os.Args + os.Args = append([]string{"vf"}, args...) + t.Cleanup(func() { os.Args = saved }) + 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(args) + cmd, err := unknownSubcommand(root, args) + if err == nil { + cmd, err = root.ExecuteC() + } + if err == nil || err.Error() == "" { + return cmd, output.Explanation{}, err + } + if msg := err.Error(); unknownFlagRE.MatchString(msg) || needsValueRE.MatchString(msg) || badArgumentRE.MatchString(msg) { + parseFlagsAfterError(cmd) // as renderError does + } + return cmd, explainCLIError(cmd, err), err +} + +// round-5 human-poweruser: `transcrpit search -p X` was asked "Did you mean +// `vf transcript`?", and `secret ls -p X` "`vf secret list`?", which drop +// the rest of the line. A misspelt flag got only the flag. Each is now the +// line typed, fixed, with the command's own flags. +func TestADidYouMeanIsTheWholeLine(t *testing.T) { + for _, tc := range []struct { + args []string + want []string + not string + }{ + {[]string{"transcrpit", "search", "-p", "p1", "--agent-mode=false"}, []string{"Did you mean `vf transcript search --project-id p1`?"}, ""}, + {[]string{"secret", "ls", "-p", "p1", "-o", "json"}, []string{"Did you mean `vf secret list --project-id p1`?"}, ""}, + {[]string{"workspace", "create", "--nmae", "two words", "--token", "vfp_secret"}, []string{"Did you mean `vf workspace create --name \"two words\"`?"}, "vfp_secret"}, + {[]string{"project", "list", "--jqq", ".name"}, []string{"Did you mean `vf project list --jq .name`?"}, ""}, + // -t is --tool-id on other commands and --type on some, and "t1" + // isn't a type, so only --tool-id gets the line. + {[]string{"tool", "get", "-p", "p1", "-e", "main", "-t", "t1"}, []string{ + "Did you mean `vf tool get --environment-alias main --project-id p1 --tool-id t1`?", + "Did you mean `--type`?", + }, "--type t1"}, + } { + _, x, _ := runAsMain(t, tc.args...) + all := explained(x) + for _, want := range tc.want { + if !strings.Contains(all, want) { + t.Errorf("%q: want %q in:\n%s", tc.args, want, all) + } + } + if tc.not != "" && strings.Contains(all, tc.not) { + t.Errorf("%q: %q in:\n%s", tc.args, tc.not, all) + } + } +} + +// round-5 agent-migrator: `--version-param ` didn't say what the +// values are. A flag given no value shows them. +func TestAFlagWithoutAValueShowsItsChoices(t *testing.T) { + _, x, _ := runAsMain(t, "conversation", "send", "-p", "p1", "-v") + if want := "Give it one: `--version-param `"; !strings.Contains(explained(x), want) { + t.Errorf("want %q in:\n%s", want, explained(x)) + } +} + +// Where the line run isn't vf's arguments, as in the home prompt, the hint +// names the command alone, as before. +func TestADidYouMeanWithoutTheLineNamesTheCommand(t *testing.T) { + saved := os.Args + os.Args = []string{"vf"} + t.Cleanup(func() { os.Args = saved }) + root := testRoot(t) + secret := find(t, root, "secret") + x := explainCLIError(secret, &unknownCommandError{"ls", "vf secret"}) + if all := explained(x); !strings.Contains(all, "Did you mean `vf secret list`?") { + t.Errorf("got:\n%s", all) + } +} + +type unknownCommandError struct{ word, path string } + +func (e *unknownCommandError) Error() string { + return `unknown command "` + e.word + `" for "` + e.path + `"` +} From 7264ea87eac3a0ed44c71d31295f86ce1b8d5aa4 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:58:50 -0500 Subject: [PATCH 27/31] fix(output): a create's Next lines give every flag their command requires MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After `tool create`, Next offered `vf tool get --tool-id … --project-id … --environment-alias main`, and run as written it failed: "vf tool get needs --type". The Next lines gave the new thing's ID and the scope flags the create was given, and nothing else the get or list requires, though the type was right there in what the create answered. A nested thing's get or list needs its parent the same way (`function variable get` needs --function-id). Each Next line now adds every other flag its command requires, its value taken from the create's answer: --type from "type", --function-id from "functionID" (nextneeds.go). A value the answer doesn't have is . --- internal/output/created.go | 8 ++--- internal/output/created_test.go | 6 ++-- internal/output/hintfit_test.go | 27 ++++++++++++++- internal/output/nextneeds.go | 56 ++++++++++++++++++++++++++++++++ internal/output/ownsteps_test.go | 2 +- 5 files changed, 90 insertions(+), 9 deletions(-) create mode 100644 internal/output/nextneeds.go diff --git a/internal/output/created.go b/internal/output/created.go index 1f166b8b..08f05db8 100644 --- a/internal/output/created.go +++ b/internal/output/created.go @@ -72,7 +72,7 @@ func afterResult(cmd *cobra.Command, res interface{}) func() { } fmt.Fprintln(os.Stderr, u.Status(ui.StatusDone, "Created "+what+within(obj))) return func() { - tips := nextSteps(cmd, group, id) + tips := nextSteps(cmd, group, id, obj) if len(tips) > 0 { fmt.Fprintln(os.Stderr, u.Bold("Next:")) for _, row := range u.Tips(tips, ui.TerminalWidth(os.Stderr)-2) { @@ -164,7 +164,7 @@ func within(obj map[string]interface{}) string { // 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 { +func nextSteps(cmd *cobra.Command, group, id string, obj map[string]interface{}) []ui.Tip { short := session.Active() with := func(c, flags string) string { if short { @@ -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: withScope(cmd, sibling.CommandPath()+" --"+idFlag+" "+id), Does: "see it"}) // hintfit.go: with -p and -e + tips = append(tips, ui.Tip{Command: withScope(cmd, sibling.CommandPath()+" --"+idFlag+" "+id+alsoNeeded(sibling, idFlag, obj)), Does: "see it"}) // hintfit.go: with -p and -e; nextneeds.go: and --type case sibling.Name() == "list": - tips = append(tips, ui.Tip{Command: withScope(cmd, sibling.CommandPath()), Does: "list them"}) + tips = append(tips, ui.Tip{Command: withScope(cmd, sibling.CommandPath()+alsoNeeded(sibling, "", obj)), Does: "list them"}) } } return tips diff --git a/internal/output/created_test.go b/internal/output/created_test.go index 3962c70d..0e9ee16f 100644 --- a/internal/output/created_test.go +++ b/internal/output/created_test.go @@ -96,19 +96,19 @@ func TestCreatedObjectUnwrapsTheResponse(t *testing.T) { func TestNextStepsCarryIDsOutsideThePrompt(t *testing.T) { cmds := group("project") session.Stop() - long := nextSteps(cmds["create"], "project", "p1") + long := nextSteps(cmds["create"], "project", "p1", nil) 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") + short := nextSteps(cmds["create"], "project", "p1", nil) if short[1].Command != "vf environment list" { t.Errorf("in the prompt: %+v", short) } variable := group("variable") - tips := nextSteps(variable["create"], "variable", "v1") + tips := nextSteps(variable["create"], "variable", "v1", nil) var got []string for _, tip := range tips { got = append(got, tip.Command) diff --git a/internal/output/hintfit_test.go b/internal/output/hintfit_test.go index 99086452..89050556 100644 --- a/internal/output/hintfit_test.go +++ b/internal/output/hintfit_test.go @@ -111,7 +111,7 @@ func TestAReasonOfTheServersOwnIsntContradicted(t *testing.T) { 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") { + for _, tip := range nextSteps(cmd, "event", "ev1", nil) { got = append(got, tip.Command) } want := []string{ @@ -122,3 +122,28 @@ func TestNextStepsCarryTheScopeFlags(t *testing.T) { t.Errorf("tips = %q\nwant %q", got, want) } } + +// round-5 agent-builder and fix-verifier: after `tool create`, Next offered +// `vf tool get --tool-id …` without --type, and it failed: "vf tool get +// needs --type". The tips carry each flag their command requires, from +// what the create answered. +func TestNextStepsCarryEveryRequiredFlag(t *testing.T) { + cmd := scoped(t, "tool", "create", map[string]string{"project-id": "p1", "environment-alias": "main"}) + get, _, _ := cmd.Root().Find([]string{"tool", "get"}) + get.Flags().String("type", "", "(options: api, function)") + get.Flags().String("folder-id", "", "") + for _, name := range []string{"type", "folder-id"} { + _ = get.Flags().SetAnnotation(name, "speakeasy:required", []string{"true"}) + } + var got []string + for _, tip := range nextSteps(cmd, "tool", "t1", map[string]interface{}{"id": "t1", "type": "function"}) { + got = append(got, tip.Command) + } + want := []string{ + "vf tool get --tool-id t1 --folder-id --type function --project-id p1 --environment-alias main", + "vf tool 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/nextneeds.go b/internal/output/nextneeds.go new file mode 100644 index 00000000..26fd8312 --- /dev/null +++ b/internal/output/nextneeds.go @@ -0,0 +1,56 @@ +// This file is not generated by Speakeasy. It gives a create's Next lines +// the flags the commands they name require, beyond the ID and the scope. +// +// After `tool create`, Next offered `vf tool get --tool-id … --project-id … +// --environment-alias main`, and run as written it failed: "vf tool get +// needs --type". The type was right there, in what the create answered. A +// nested thing's get or list needs its parent the same way: `function +// variable get` needs --function-id. + +package output + +import ( + "slices" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// alsoNeeded is " --flag value" for each flag next requires that isn't +// idFlag or a scope flag (withScope adds those), its value taken from obj, +// what the create answered: --type from "type", --function-id from +// "functionID". A value obj doesn't have is . +func alsoNeeded(next *cobra.Command, idFlag string, obj map[string]interface{}) string { + var add strings.Builder + next.LocalFlags().VisitAll(func(f *pflag.Flag) { + required := f.Annotations["speakeasy:required"] + if f.Hidden || len(required) == 0 || required[0] != "true" || f.Name == idFlag || slices.Contains(scopeFlags, f.Name) { + return + } + value := "" + if v := firstString(obj, fieldOf(f.Name)); v != "" { + value = quoteArg(v) + } + add.WriteString(" --" + f.Name + " " + value) + }) + return add.String() +} + +// fieldOf is the field a flag names in an answer: function-id is +// functionID, version-param is version. +func fieldOf(flag string) string { + words := strings.Split(strings.TrimSuffix(flag, "-param"), "-") + for i, w := range words { + switch { + case i == 0: + case w == "id": + words[i] = "ID" + case w == "ids": + words[i] = "IDs" + default: + words[i] = strings.ToUpper(w[:1]) + w[1:] + } + } + return strings.Join(words, "") +} diff --git a/internal/output/ownsteps_test.go b/internal/output/ownsteps_test.go index b43d9a70..09606ae0 100644 --- a/internal/output/ownsteps_test.go +++ b/internal/output/ownsteps_test.go @@ -11,7 +11,7 @@ func TestACreateNamesItsOwnNextSteps(t *testing.T) { cmd := scoped(t, "folder", "create", map[string]string{"project-id": "p1", "environment-alias": "main"}) cmd.Annotations = map[string]string{NextSteps: "vf folder list --folder-id {id}\tits contents\nnot a step"} var got []string - for _, tip := range nextSteps(cmd, "folder", "f1") { + for _, tip := range nextSteps(cmd, "folder", "f1", nil) { got = append(got, tip.Command+" "+tip.Does) } want := []string{ From 9cde97bbc6bd33fc1cc4f4fb50b3413cc87e83c3 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:01:25 -0500 Subject: [PATCH 28/31] fix(conversation): a stale turn's warning says what vf did, not what the next turn will MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After an edit mid-conversation, a turn that ran the older build warned "vf has compiled it, so the next turn runs your latest edits". In the usability sweep the next turn still answered without the edit twice, and only a new --user-id took it. Whether the conversation kept the old build or the model kept to its earlier replies, vf can't tell, so the promise was one it couldn't keep. The warning now says what vf knows, that it has compiled the draft, and how to be sure a conversation runs the edits: start a new one, with a new --user-id, or reset this user's with `vf conversation state delete --user-id … --project-id … --environment-alias … --version-param draft`, given in full. send's help and the README say the same. When vf compiles is unchanged. --- README.md | 2 +- internal/cli/autocompile_test.go | 34 +++++++++++++++++++++++- internal/cli/conversation/autocompile.go | 31 +++++++++++++++++---- 3 files changed, 60 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 3ed62baf..e87fe809 100644 --- a/README.md +++ b/README.md @@ -108,7 +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` that starts a conversation: a `launch` action, or any message to a user ID with no conversation going (new, or its last one ended; vf reads the user's state to tell). A later turn runs the build as it is. If that turn ran an older build (you edited mid-conversation), vf compiles right after it and warns, so the next turn runs the edits; a new `--user-id` runs them at once. `--no-compile` talks to the last build as it is; the published version is never compiled. +- **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` that starts a conversation: a `launch` action, or any message to a user ID with no conversation going (new, or its last one ended; vf reads the user's state to tell). A later turn runs the build as it is. If that turn ran an older build (you edited mid-conversation), vf compiles right after it and warns. To be sure a conversation runs your edits, start a new one: a new `--user-id`, or `vf conversation state delete` to reset the user's. `--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 `--jq`**: `ID=$(vf project create … --jq .project.id)`. A string result prints raw, as `jq -r` prints it; anything else prints as JSON. - **`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 index 04f22ec3..08766d09 100644 --- a/internal/cli/autocompile_test.go +++ b/internal/cli/autocompile_test.go @@ -120,7 +120,7 @@ func TestAConversationWithTheDraftCompilesItFirst(t *testing.T) { 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 { + if says := strings.Contains(out, "Compiled the draft") || strings.Contains(out, "vf has compiled the draft now"); 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`) { @@ -130,6 +130,38 @@ func TestAConversationWithTheDraftCompilesItFirst(t *testing.T) { } } +// round-5 human-newcomer and fix-verifier: after a mid-conversation edit +// vf warned "vf has compiled it, so the next turn runs your latest edits", +// and the next turn still answered without them; a new --user-id took them. +// The warning says only what vf did, and how to start a new conversation, +// with a command that runs as written. +func TestAStaleTurnSaysHowToBeSureOfTheEdits(t *testing.T) { + url, _ := conversationServer(t, 200, staleTurn) + out, err := runConversation(t, url, "send", "-u", "sam smith", "-v", "draft", "-p", "p1", "-e", "main", "--text", "hi") + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + out = strings.Join(strings.Fields(out), " ") // as one line, however it wraps + reset := `vf conversation state delete --user-id "sam smith" --project-id p1 --environment-alias main --version-param draft` + for _, want := range []string{"This turn ran an older build of the draft. vf has compiled the draft now.", "a new --user-id", "'" + reset + "'"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } + if strings.Contains(out, "next turn") { + t.Errorf("promises the next turn:\n%s", out) + } + root := testRoot(t) + words := shellWords(t, reset) + cmd, rest, err := root.Find(words[1:]) + if err != nil || cmd.CommandPath() != "vf conversation state delete" { + t.Fatalf("%q runs %v: %v", reset, cmd, err) + } + if err := cmd.ParseFlags(rest); err != nil || len(cmd.Flags().Args()) != 0 { + t.Errorf("%q: %v %q", reset, err, cmd.Flags().Args()) + } +} + // A first --text to a user ID with no conversation going starts one, so it // compiles the draft first, as a launch does. It ran the old build, and vf // said so only after. diff --git a/internal/cli/conversation/autocompile.go b/internal/cli/conversation/autocompile.go index 83126049..c52e38f1 100644 --- a/internal/cli/conversation/autocompile.go +++ b/internal/cli/conversation/autocompile.go @@ -17,9 +17,13 @@ // // A send later in a conversation keeps its build: nothing cheap says the // draft changed since. If its turn 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. +// and says so. It used to add "so the next turn runs your latest edits", +// and in the usability sweep the next turn still answered without them +// twice, where a new user ID took them at once. Whether the conversation +// kept the old build or the model kept to its earlier replies, vf can't +// tell, so the warning says what it did and the way to be sure: a new +// conversation. --no-compile runs whatever was last compiled. The published +// version is a release, and is never compiled. package conversation @@ -27,6 +31,7 @@ import ( "encoding/json" "fmt" "net/http" + "strconv" "strings" "time" @@ -56,7 +61,7 @@ func addNoCompileFlag(cmd *cobra.Command) { // sendCompiles is what send's help says about compiling the draft. const sendCompiles = `With the draft, vf compiles it before a turn that starts a conversation, so that turn runs your latest edits. A launch starts one, and so does a message to a user ID with no conversation going: one new to the agent, or one whose conversation ended. vf reads the user's state to tell. -A later turn runs the draft as last compiled: nothing says before it whether you edited the agent since. If it ran an older build, vf compiles right after it and warns, so the next turn runs your edits; a new --user-id runs them at once. --no-compile skips all of this. The published version is never compiled.` +A later turn runs the draft as last compiled: nothing says before it whether you edited the agent since. If it ran an older build, vf compiles right after it and warns. To be sure a conversation runs your edits, start a new one: a new --user-id, or 'vf conversation state delete' to reset the user's. --no-compile skips all of this. The published version is never compiled.` // compileBeforeScript compiles the draft before run-script, which always // starts a new conversation. @@ -130,11 +135,27 @@ func compileAfterStaleSend(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operati 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.") + warn(cmd, "This turn ran an older build of the draft. vf has compiled the draft now. To be sure a conversation runs your latest edits, start a new one: a new --user-id, or reset this user's with '"+resetCommand(req)+"'.") return nil } } +// resetCommand is the command that deletes the state of req's user, so the +// next send to it starts a new conversation. +func resetCommand(req *operations.StableConversationControllerSendRequest) string { + words := []string{"vf conversation state delete"} + for _, f := range []struct{ name, value string }{ + {"user-id", req.UserID}, {"project-id", req.ProjectID}, {"environment-alias", req.EnvironmentAlias}, + } { + value := f.value + if value == "" || strings.ContainsAny(value, " \t\"'\\$`") { + value = strconv.Quote(value) + } + words = append(words, "--"+f.name, value) + } + return strings.Join(append(words, "--version-param", "draft"), " ") +} + // 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) { From 83bd0b7b943112d50b60d16ac46a1495b6cced55 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:29:45 -0500 Subject: [PATCH 29/31] fix(cli): a missing-flag hint's list and command line run as written The test that runs every command vf suggests (a later commit) found two kinds of missing-flag hint that failed as written: - The list that shows an ID's values dropped the flags typed, and what it needs itself. `vf tool get -e staging` pointed at `vf tool list`, which lists main's tools; `vf api-tool variable update` at `vf variable list`, the agent's variables; `vf project get` at `vf project list`, which needs --workspace-id. The list now keeps the IDs and aliases typed that it takes, gives a placeholder for each flag it requires that the command was run without or doesn't have, and is the one in the command's own group when the group is the flag's noun. - "Pass them" left out a body that must be one of its forms. `vf tool create -e main` was handed a line without --body-param, which then failed with "the body is none of its forms". The line now gives the first form, as help's examples do. When the body is all that's left out, that error offers the line with a form too, where it said only that --help lists the forms. --- internal/cli/errors.go | 1 + internal/cli/errors_test.go | 2 +- internal/cli/missingflags.go | 83 ++++++++++++++++++++++++++++++- internal/cli/missingflags_test.go | 59 +++++++++++++++++++++- internal/output/badbody.go | 8 +++ test/errors-teach.test.ts | 2 +- 6 files changed, 150 insertions(+), 5 deletions(-) diff --git a/internal/cli/errors.go b/internal/cli/errors.go index 535d6ce0..3bdd8495 100644 --- a/internal/cli/errors.go +++ b/internal/cli/errors.go @@ -42,6 +42,7 @@ func init() { // Nor can it list your workspaces, which says whether you're in the // organization or workspace a refused request targeted. output.CheckAccess = checkAccess + output.LineWithAForm = lineWithAForm // missingflags.go: a body of none of its forms } // checkAccess finds the organization or workspace cmd targeted among your diff --git a/internal/cli/errors_test.go b/internal/cli/errors_test.go index 043a6280..ee11e692 100644 --- a/internal/cli/errors_test.go +++ b/internal/cli/errors_test.go @@ -97,7 +97,7 @@ func TestAMissingFlagSaysWhereItsValueComesFrom(t *testing.T) { } 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 `"} { + for _, want := range []string{"vf project get needs --project-id", "--no-interactive is set", "`vf project list --workspace-id ` 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) } diff --git a/internal/cli/missingflags.go b/internal/cli/missingflags.go index 7f00fe52..d2de675d 100644 --- a/internal/cli/missingflags.go +++ b/internal/cli/missingflags.go @@ -12,7 +12,9 @@ // them. `send --text hello` sets --action itself, and the line repeated it // next to --text, a pair vf refuses ("--text and --action both say what to // send"). A flag left out shows its choices where it has some, -// `--version-param `, not ``. +// `--version-param `, not ``. A union the command +// requires gets a form, and the list that shows an ID's values keeps the +// IDs typed, so each line runs as written. package cli @@ -55,7 +57,7 @@ func explainMissingFlags(cmd *cobra.Command, flags []string) output.Explanation var pickers []string for i, f := range flags { - if list := listCommandFor(cmd, f); list != "" { + if list := listFor(cmd, f, flags); list != "" { takes := "it takes" if len(flags) > 1 { takes = names[i] + " takes" @@ -115,6 +117,83 @@ func commandLineWith(cmd *cobra.Command, missing []string) string { } words = append(words, leftOut(cmd, name)) } + return strings.Join(append(words, formsLeftOut(cmd, missing)...), " ") +} + +// formsLeftOut gives a form, as help's examples do, to each union cmd +// requires that neither the line typed nor missing gives. `tool create -p +// p1` was told to pass --name and the rest, and the line it was handed then +// failed with "the body is none of its forms". +func formsLeftOut(cmd *cobra.Command, missing []string) []string { + given := slices.Clone(missing) + cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + if typed(cmd, f) { + given = append(given, f.Name) + } + }) + var words []string + cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + if f.Hidden || !needsAForm(f) || flagutil.StoodInFor(cmd, given, f.Name) { + return + } + if slices.ContainsFunc(given, func(name string) bool { return name == f.Name || strings.HasPrefix(name, f.Name+".") }) { + return + } + words = append(words, aForm(cmd, f.Annotations[flagutil.UnionNeedsAForm][0])...) // examplehelp.go + }) + return words +} + +// lineWithAForm is the line cmd was run with, with a form for each union it +// requires that the line doesn't give, or "" when it gives them all. `tool +// create -p p1 -e main` said only that the body "is none of its forms". +func lineWithAForm(cmd *cobra.Command) string { + if len(formsLeftOut(cmd, nil)) == 0 { + return "" + } + return commandLineWith(cmd, nil) +} + +// listFor is the command that lists the values flag takes, with the IDs and +// aliases typed that it takes too, so it looks where cmd does: `vf tool list +// --environment-alias staging`, not the default environment's tools. A flag +// the list requires that cmd was run without, or doesn't have, is a +// placeholder, as in the line that passes the missing flags. It is the list +// in cmd's own group when the group is the flag's noun, so `vf api-tool +// variable update` points at `vf api-tool variable list --api-tool-id +// `, not at the agent's variables. "" when no command lists them. +func listFor(cmd *cobra.Command, flag string, missing []string) string { + var list *cobra.Command + if noun := strings.TrimSuffix(flag, "-id"); noun != flag && cmd.HasParent() && cmd.Parent().Name() == noun { + for _, c := range cmd.Parent().Commands() { + if c.Name() == "list" { + list = c + } + } + } + if list == nil { + path := listCommandFor(cmd, flag) // errors.go + if path == "" { + return "" + } + found, _, err := cmd.Root().Find(strings.Fields(path)[1:]) + if err != nil { + return path + } + list = found + } + words := []string{list.CommandPath()} + cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + scope := strings.HasSuffix(f.Name, "-id") || strings.HasSuffix(f.Name, "-alias") + if scope && f.Name != flag && typed(cmd, f) && list.Flags().Lookup(f.Name) != nil { + words = append(words, givenFlag(f)...) + } + }) + list.LocalFlags().VisitAll(func(f *pflag.Flag) { + if !f.Hidden && isRequired(f) && (cmd.Flags().Lookup(f.Name) == nil || slices.Contains(missing, f.Name)) { + words = append(words, leftOut(list, f.Name)) + } + }) return strings.Join(words, " ") } diff --git a/internal/cli/missingflags_test.go b/internal/cli/missingflags_test.go index e54bc9b8..e9c0a95d 100644 --- a/internal/cli/missingflags_test.go +++ b/internal/cli/missingflags_test.go @@ -25,7 +25,7 @@ func TestEveryMissingFlagIsNamedInOneRun(t *testing.T) { for _, want := range []string{ "vf function create needs --environment-alias and --code", "--no-interactive is set, so vf didn't ask for them.", - "`vf environment list` shows the values --environment-alias takes", + "`vf environment list --project-id p1` shows the values --environment-alias takes", "Pass them: `vf function create --name \"two words\" --project-id p1 --environment-alias --code `", } { if !strings.Contains(all, want) { @@ -173,6 +173,63 @@ func TestTheCommandLineRepeatsOnlyWhatWasTyped(t *testing.T) { } } +// TestEverySuggestedCommandRuns found the list a hint points at looking +// elsewhere: `vf tool list` for tools in -e staging lists main's, and `vf +// variable list` for an API tool's variable lists the agent's. The list +// keeps the IDs typed, and asks for what it needs besides. +func TestTheListOfValuesLooksWhereTheCommandDoes(t *testing.T) { + for _, c := range []struct { + args []string + want string + }{ + {[]string{"tool", "get", "-p", "p1", "-e", "staging", "--type", "function"}, "`vf tool list --environment-alias staging --project-id p1` shows the values it takes"}, + {[]string{"api-tool", "variable", "update", "-p", "p1", "-e", "main"}, "`vf api-tool variable list --environment-alias main --project-id p1 --api-tool-id ` shows the values it takes"}, + {[]string{"environment", "get"}, "`vf environment list --project-id ` shows the values --environment-alias takes"}, + } { + x := runWithStdin(t, "", append(c.args, "--no-interactive")...) + if all := explained(x); !strings.Contains(all, c.want) { + t.Errorf("%q: want %q in:\n%s", c.args, c.want, all) + } + } +} + +// A union cmd requires, such as tool create's body, is in the line that +// passes the missing flags, as one of its forms: without one, the line ran +// into "the body is none of its forms". +func TestThePassLineGivesAUnionItsForm(t *testing.T) { + x := runWithStdin(t, "", "tool", "create", "-e", "main", "--no-interactive") + want := "Pass it: `vf tool create --environment-alias main --project-id --body-param.api `" + if all := explained(x); !strings.Contains(all, want) { + t.Errorf("want %q in:\n%s", want, all) + } + x = runWithStdin(t, "", "tool", "create", "-e", "main", "--body-param.function", `{"functionID":"f1"}`, "--no-interactive") + if all := explained(x); strings.Contains(all, "--body-param.api") { + t.Errorf("a second form, beside the one given:\n%s", all) + } +} + +// With every other flag given, a body of none of its forms is found as the +// request is built, and said with only "--help lists the forms". It gives +// the line typed with a form, too. +func TestABodyOfNoFormGetsTheLineWithOne(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + root := testRoot(t) + var buf strings.Builder + root.SetOut(&buf) + root.SetErr(&buf) + root.SetArgs([]string{"tool", "create", "-p", "p1", "-e", "main", "--agent-mode=false", "--no-interactive", "--dry-run"}) + if _, err := root.ExecuteC(); err == nil { + t.Fatalf("no error:\n%s", buf.String()) + } + want := "Give it one, such as: 'vf tool create --environment-alias main --project-id p1 --body-param.api '" + if !strings.Contains(buf.String(), "none of its forms") || !strings.Contains(buf.String(), want) { + t.Errorf("want %q in:\n%s", want, buf.String()) + } +} + // A flag left out shows the values it takes, and a true/false one is given // with =, since `--flag false` would leave "false" a stray word. func TestALeftOutFlagShowsItsChoices(t *testing.T) { diff --git a/internal/output/badbody.go b/internal/output/badbody.go index eecacc73..31e28ed6 100644 --- a/internal/output/badbody.go +++ b/internal/output/badbody.go @@ -30,6 +30,11 @@ import ( "github.com/voiceflow/cli/internal/flagutil" ) +// LineWithAForm is the line cmd was run with, with one of its body's forms +// added, or "". The cli package sets it (missingflags.go): output can't see +// which flags were typed, nor the forms' fields. +var LineWithAForm = func(*cobra.Command) string { return "" } + var ( marshalTypeRE = regexp.MustCompile(`error calling MarshalJSON for type \*?(?:\w+\.)?(\w+): `) nullUnionRE = regexp.MustCompile(`could not marshal union type (\w+): all fields are null`) @@ -72,6 +77,9 @@ func explainBadBody(cmd *cobra.Command, err error) (Explanation, bool) { 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"} + if line := LineWithAForm(cmd); line != "" { + x.Next = append([]string{"Give it one, such as: `" + line + "`"}, x.Next...) + } } } return x, true diff --git a/test/errors-teach.test.ts b/test/errors-teach.test.ts index fb53e3ea..2b05bcb6 100644 --- a/test/errors-teach.test.ts +++ b/test/errors-teach.test.ts @@ -114,7 +114,7 @@ describe('required-flag preflight', () => { 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(JSON.stringify(envelope.hints)).toContain("'vf project list --workspace-id ' shows the values it takes"); expect(result.stderr).not.toContain('statusCode'); // no server round-trip happened }); From 0d2d2ca494918fa22b61bc7fba5414bb5f151a4e Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:30:56 -0500 Subject: [PATCH 30/31] fix(output): Next and not-found lines give every flag their command requires MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tests that run every command vf suggests (a later commit) found lines that the command they name refused: - `vf workspace create` offered `vf project create --workspace-id … --name `, without the --type project create requires. - `vf phone-number create` offered `vf phone-number get --phone-number-id …` without --workspace-id. The create takes it in its body, so withScope had no flag to carry; it now comes from the answer. A parent ID the answer lacks comes from the create's flags. - The list a 404 points at left out what it requires: `vf function path list` the --function-id, `vf test turn list` the --test-id, `vf project list` the --workspace-id. withScope now adds each flag the command requires that the line doesn't give, with the value typed, or else . --- internal/output/created.go | 6 ++-- internal/output/hintfit.go | 2 +- internal/output/hintfit_test.go | 41 +++++++++++++++++++++++++++ internal/output/nextneeds.go | 49 +++++++++++++++++++++++++++++---- test/errors-teach.test.ts | 2 +- 5 files changed, 89 insertions(+), 11 deletions(-) diff --git a/internal/output/created.go b/internal/output/created.go index 08f05db8..82088c3c 100644 --- a/internal/output/created.go +++ b/internal/output/created.go @@ -175,7 +175,7 @@ func nextSteps(cmd *cobra.Command, group, id string, obj map[string]interface{}) 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 project create", "--workspace-id "+id+" --name --type "), Does: "add a project to it"}, {Command: with("vf workspace get", "--workspace-id "+id), Does: "see it"}, } case "project": @@ -190,9 +190,9 @@ func nextSteps(cmd *cobra.Command, group, id string, obj map[string]interface{}) for _, sibling := range cmd.Parent().Commands() { switch { case sibling.Name() == "get" && sibling.Flags().Lookup(idFlag) != nil: - tips = append(tips, ui.Tip{Command: withScope(cmd, sibling.CommandPath()+" --"+idFlag+" "+id+alsoNeeded(sibling, idFlag, obj)), Does: "see it"}) // hintfit.go: with -p and -e; nextneeds.go: and --type + tips = append(tips, ui.Tip{Command: withScope(cmd, sibling.CommandPath()+" --"+idFlag+" "+id+alsoNeeded(cmd, sibling, idFlag, obj)), Does: "see it"}) // hintfit.go: with -p and -e; nextneeds.go: and --type case sibling.Name() == "list": - tips = append(tips, ui.Tip{Command: withScope(cmd, sibling.CommandPath()+alsoNeeded(sibling, "", obj)), Does: "list them"}) + tips = append(tips, ui.Tip{Command: withScope(cmd, sibling.CommandPath()+alsoNeeded(cmd, sibling, "", obj)), Does: "list them"}) } } return tips diff --git a/internal/output/hintfit.go b/internal/output/hintfit.go index aad9b46a..25b958e6 100644 --- a/internal/output/hintfit.go +++ b/internal/output/hintfit.go @@ -172,7 +172,7 @@ func withScope(cmd *cobra.Command, next string) string { } next += " --" + name + " " + quoteArg(f.Value.String()) } - return next + return next + stillNeeded(cmd, target, next) // nextneeds.go: and what else target requires } // vfCommandNames rewrites the MCP tool and API field names in a server diff --git a/internal/output/hintfit_test.go b/internal/output/hintfit_test.go index 89050556..bacabe98 100644 --- a/internal/output/hintfit_test.go +++ b/internal/output/hintfit_test.go @@ -147,3 +147,44 @@ func TestNextStepsCarryEveryRequiredFlag(t *testing.T) { t.Errorf("tips = %q\nwant %q", got, want) } } + +// TestEverySuggestedCommandRuns found the list a 404 points at missing what +// it requires: `vf function path list` the --function-id, `vf project list` +// the --workspace-id. It gives the value typed, or a placeholder. +func TestAListAfterANotFoundGivesWhatItRequires(t *testing.T) { + cmd := scoped(t, "path", "get", map[string]string{"project-id": "p1", "path-id": "x"}) + list, _, _ := cmd.Root().Find([]string{"path", "list"}) + list.Flags().String("function-id", "", "") + _ = list.Flags().SetAnnotation("function-id", "speakeasy:required", []string{"true"}) + if got, want := withScope(cmd, "vf path list"), "vf path list --project-id p1 --function-id "; got != want { + t.Errorf("got %s\nwant %s", got, want) + } + cmd.Flags().String("function-id", "", "") + _ = cmd.Flags().Set("function-id", "f1") + if got, want := withScope(cmd, "vf path list"), "vf path list --project-id p1 --function-id f1"; got != want { + t.Errorf("got %s\nwant %s", got, want) + } +} + +// TestEveryNextLineRuns found `phone-number create`, which takes its +// workspace in the body, offering `vf phone-number get --phone-number-id +// …` without the --workspace-id get requires; withScope adds only the scope +// flags the create took. The answer has it. +func TestNextStepsCarryAScopeTheCreateTookInItsBody(t *testing.T) { + cmd := scoped(t, "phone-number", "create", nil) + get, _, _ := cmd.Root().Find([]string{"phone-number", "get"}) + get.Flags().String("workspace-id", "", "") + _ = get.Flags().SetAnnotation("workspace-id", "speakeasy:required", []string{"true"}) + got := nextSteps(cmd, "phone-number", "n1", map[string]interface{}{"id": "n1", "workspaceID": "w1"}) + if want := "vf phone-number get --phone-number-id n1 --workspace-id w1"; len(got) == 0 || got[0].Command != want { + t.Errorf("tips = %v\nwant %q first", got, want) + } + // A create that takes it gives it as it was typed, once. + cmd = scoped(t, "tool", "create", map[string]string{"project-id": "p1"}) + get, _, _ = cmd.Root().Find([]string{"tool", "get"}) + _ = get.Flags().SetAnnotation("project-id", "speakeasy:required", []string{"true"}) + got = nextSteps(cmd, "tool", "t1", map[string]interface{}{"id": "t1", "projectID": "p2"}) + if want := "vf tool get --tool-id t1 --project-id p1"; len(got) == 0 || got[0].Command != want { + t.Errorf("tips = %v\nwant %q first", got, want) + } +} diff --git a/internal/output/nextneeds.go b/internal/output/nextneeds.go index 26fd8312..d020180c 100644 --- a/internal/output/nextneeds.go +++ b/internal/output/nextneeds.go @@ -1,11 +1,13 @@ -// This file is not generated by Speakeasy. It gives a create's Next lines -// the flags the commands they name require, beyond the ID and the scope. +// This file is not generated by Speakeasy. It gives a create's Next lines, +// and the list a not-found points at, the flags the commands they name +// require, beyond the ID and the scope. // // After `tool create`, Next offered `vf tool get --tool-id … --project-id … // --environment-alias main`, and run as written it failed: "vf tool get // needs --type". The type was right there, in what the create answered. A // nested thing's get or list needs its parent the same way: `function -// variable get` needs --function-id. +// variable get` needs --function-id. So does the list after a 404: `vf +// function path get` pointed at a `vf function path list` without one. package output @@ -15,22 +17,57 @@ import ( "github.com/spf13/cobra" "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/session" ) // alsoNeeded is " --flag value" for each flag next requires that isn't // idFlag or a scope flag (withScope adds those), its value taken from obj, // what the create answered: --type from "type", --function-id from -// "functionID". A value obj doesn't have is . -func alsoNeeded(next *cobra.Command, idFlag string, obj map[string]interface{}) string { +// "functionID", or else as the create was given it. Any other is . A scope flag made, +// the create, doesn't take is one withScope can't add, so it is here too: +// `phone-number get` needs the --workspace-id that `phone-number create` +// gave in its body. +func alsoNeeded(made, next *cobra.Command, idFlag string, obj map[string]interface{}) string { var add strings.Builder next.LocalFlags().VisitAll(func(f *pflag.Flag) { required := f.Annotations["speakeasy:required"] - if f.Hidden || len(required) == 0 || required[0] != "true" || f.Name == idFlag || slices.Contains(scopeFlags, f.Name) { + if f.Hidden || len(required) == 0 || required[0] != "true" || f.Name == idFlag { return } + if slices.Contains(scopeFlags, f.Name) && (made.Flags().Lookup(f.Name) != nil || session.Active()) { + return // withScope's, or the home prompt's context's + } value := "" if v := firstString(obj, fieldOf(f.Name)); v != "" { value = quoteArg(v) + } else if typed := made.Flags().Lookup(f.Name); typed != nil && typed.Changed { + value = quoteArg(typed.Value.String()) // the --function-id a variable was made with + } + add.WriteString(" --" + f.Name + " " + value) + }) + return add.String() +} + +// stillNeeded is " --flag value" for each flag target requires that next, +// a command line for it, doesn't give: the value cmd was given, or else +// . After a 404, `vf function path list` needs the --function-id +// the get had, and `vf project list` a --workspace-id the get never took. +func stillNeeded(cmd, target *cobra.Command, next string) string { + words := strings.Fields(next) + var add strings.Builder + target.LocalFlags().VisitAll(func(f *pflag.Flag) { + required := f.Annotations["speakeasy:required"] + if f.Hidden || len(required) == 0 || required[0] != "true" || len(f.Annotations[flagutil.UnionNeedsAForm]) > 0 { + return + } + if slices.ContainsFunc(words, func(w string) bool { return w == "--"+f.Name || strings.HasPrefix(w, "--"+f.Name+"=") }) { + return + } + value := "" + if given := cmd.Flags().Lookup(f.Name); given != nil && given.Changed { + value = quoteArg(given.Value.String()) } add.WriteString(" --" + f.Name + " " + value) }) diff --git a/test/errors-teach.test.ts b/test/errors-teach.test.ts index 2b05bcb6..69c37ebe 100644 --- a/test/errors-teach.test.ts +++ b/test/errors-teach.test.ts @@ -243,7 +243,7 @@ describe('human-mode errors print once', () => { expect(result.exitCode).toBe(4); // not found 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).toContain("'vf project list --workspace-id ' lists the IDs you can use"); expect(result.stderr).not.toContain('{'); // no raw JSON body for a person }); From ee86c7c6111d4f74b3964f9039f558822cca8b0d Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:32:57 -0500 Subject: [PATCH 31/31] test(cli): every command vf suggests runs as written MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The usability sweep found suggested commands failing one at a time: a "Pass them:" line with --action beside --text, which vf refuses; an ID hint that dropped the -p typed; "Did you mean `vf transcript`?" for a line with more on it; a tool get Next line without its --type. Each was fixed where it was found. TestEverySuggestedCommandRuns makes every command make the usual mistakes against a fake API on 127.0.0.1: required flags left out, stray words, an ID or a message given as words, a misspelt command, group or flag, and an ID the API doesn't know. It gathers each `vf …` the explanation offers, 2814 of them (1000 different), and holds each to cmdcheck.Check: the command exists and isn't a group, every flag exists and takes its value, no two flags vf refuses together, no stray word, the flags typed are kept, and nothing the command requires is left out. A mistake vf knows the fix for must get a whole line, not a piece. TestEveryNextLineRuns does the same for the 50 Next lines a create, clone or duplicate prints. On d4d386d, before this branch, they report 3274 and 9 problems, among them each of the sweep's: --text with --action, the dropped -p, the unquoted message and misspelt flag given as pieces, the bare group, and tool get without --type. They also found what the two commits before this fixed. --- internal/cli/suggested_test.go | 340 ++++++++++++++++++++++++++++++++ internal/cmdcheck/cmdcheck.go | 312 +++++++++++++++++++++++++++++ internal/output/export_test.go | 16 ++ internal/output/nextrun_test.go | 82 ++++++++ 4 files changed, 750 insertions(+) create mode 100644 internal/cli/suggested_test.go create mode 100644 internal/cmdcheck/cmdcheck.go create mode 100644 internal/output/export_test.go create mode 100644 internal/output/nextrun_test.go diff --git a/internal/cli/suggested_test.go b/internal/cli/suggested_test.go new file mode 100644 index 00000000..c012e42d --- /dev/null +++ b/internal/cli/suggested_test.go @@ -0,0 +1,340 @@ +// This file is not generated by Speakeasy. It checks that every command vf +// suggests after a mistake runs as written, across every command. +// +// The usability sweep found the suggestions failing one at a time: a +// "Pass them:" line with --action beside --text, which vf refuses; an ID +// hint without the -p typed; "Did you mean `vf transcript`?" for a line +// with more on it. Each was fixed where it was found. This makes every +// command make the usual mistakes, gathers each `vf …` the explanation +// offers, and holds it to cmdcheck.Check, in the spirit of +// TestEveryExampleRunsAsWritten (examplehelp_test.go). A create's Next lines +// are checked in output (nextrun_test.go). + +package cli + +import ( + "bytes" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/cmdcheck" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/output" +) + +// mistake is one way to get a command line wrong. +type mistake struct { + kind string + args []string // the line, after vf + typed []string // the command's own flags it gives, by name + // complete is whether a suggestion for this command must give every + // flag it requires: the line gave them all, or the hint adds the rest. + complete bool +} + +func TestEverySuggestedCommandRuns(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"message":"Not found"}`)) + })) + t.Cleanup(srv.Close) + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", srv.URL) + t.Setenv("HOME", t.TempDir()) + null, err := os.Open(os.DevNull) + if err != nil { + t.Fatal(err) + } + savedIn := os.Stdin + os.Stdin = null + t.Cleanup(func() { os.Stdin = savedIn; null.Close() }) + csv := filepath.Join(t.TempDir(), "rows.csv") + if err := os.WriteFile(csv, []byte("name,price\noat milk,0.60\n"), 0o600); err != nil { + t.Fatal(err) + } + + tree := testRoot(t) // the tree the suggestions are read against + // Each kind of mistake runs in a tree of its own, once per command, so + // no command keeps the flags of an earlier run. + trees := map[string]*cobra.Command{} + suggested, lines := 0, map[string]bool{} + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + walk(sub) + } + if c == tree || c.HasSubCommands() || !c.Runnable() || c.Hidden || skipMistakes[strings.Fields(c.CommandPath())[1]] { + return + } + for _, m := range mistakesFor(c, csv, srv.URL) { + root := trees[m.kind] + if root == nil { + if root, err = NewRootCommand(); err != nil { + t.Fatal(err) + } + trees[m.kind] = root + } + x, ran, ok := explainMistake(t, root, m.args) + if !ok { + continue + } + derived := derivedFlags(ran) + text := strings.Join(append(append([]string{x.Title}, x.Why...), x.Next...), "\n") + found := cmdcheck.Commands(text) + for _, line := range found { + suggested++ + lines[line] = true + for _, problem := range checkSuggestion(tree, c, m, derived, line) { + t.Errorf("%s: `vf %s` suggests `%s`, which %s", m.kind, strings.Join(m.args, " "), line, problem) + } + } + // A piece of a line, "Did you mean `--name`?", is for the + // reader to fit back in by hand: a mistake vf knows the fix + // for gets a whole one. + if fixable[m.kind] && !slices.ContainsFunc(found, func(line string) bool { return !strings.Contains(line, "--help") }) { + t.Errorf("%s: `vf %s` offers no command to run but help:\n%s", m.kind, strings.Join(m.args, " "), text) + } + } + } + walk(tree) + t.Logf("checked %d suggestions, %d different", suggested, len(lines)) + if suggested < 1000 { + t.Errorf("checked only %d suggestions", suggested) + } +} + +// fixable are the mistakes vf can say the whole line for: words that aren't +// an ID or a message, or an ID the API doesn't know, it can't. +var fixable = map[string]bool{"missing flags": true, "an ID as a word": true, "an unquoted message": true, "a misspelt command": true, "a misspelt group": true, "a misspelt flag": true} + +// skipMistakes are the commands that sign in, browse or read the docs +// site: they talk to no fake server. +var skipMistakes = map[string]bool{"auth": true, "configure": true, "explore": true, "docs": true} + +// checkSuggestion is what would stop line, suggested after mistake m with +// command c, from running as written; vf set the flags derived from those +// typed. A suggestion for another command, such as `vf tool list`, looks +// where c did, with the IDs and aliases typed that it takes too, and gives +// what it requires, but for a +// guess at a misspelt word: `vf workflow link` for `vf workflow lits` is +// the line typed with one word fixed, and what link needs besides is for +// its own hint to say. +func checkSuggestion(tree, c *cobra.Command, m mistake, derived []string, line string) []string { + o := cmdcheck.Options{Keep: m.typed, Complete: m.complete, Derived: derived} + if words, err := cmdcheck.Words(line); err == nil && len(words) > 0 { + target, _, err := tree.Find(words[1:]) + switch { + case slices.Contains(words, "--help"): + o = cmdcheck.Options{} // `vf x --help` lists its flags, and needs none + case err == nil && target.CommandPath() != c.CommandPath(): + o.Derived = nil // vf set them for c + o.Keep = slices.DeleteFunc(slices.Clone(m.typed), func(name string) bool { return !where(name) || target.Flags().Lookup(name) == nil }) + o.Complete = m.kind != "a misspelt command" && m.kind != "a misspelt group" + } + } + return cmdcheck.Check(tree, line, o) +} + +// where reports whether flag name says where to look: an ID or an alias. +func where(name string) bool { + return strings.HasSuffix(name, "-id") || strings.HasSuffix(name, "-ids") || strings.HasSuffix(name, "-alias") +} + +// explainMistake runs args in root as main does and explains its error, +// as vf prints it: an error returned, or one a command reported itself. It +// gives the command that ran, too. +func explainMistake(t *testing.T, root *cobra.Command, args []string) (output.Explanation, *cobra.Command, bool) { + t.Helper() + saved := os.Args + os.Args = append([]string{"vf"}, args...) + defer func() { os.Args = saved }() + output.ResetAgentMode() + defer output.ResetAgentMode() + var buf bytes.Buffer + root.SetOut(&buf) + root.SetErr(&buf) + root.SetArgs(args) + cmd, err := unknownSubcommand(root, args) + if err == nil { + cmd, err = root.ExecuteC() + } + if err == nil { + return output.Explanation{}, cmd, false + } + if err.Error() == "" { // reported as it happened: an API error + for err != nil && err.Error() == "" { + err = errors.Unwrap(err) // its exit code, then output.AlreadyReported + } + return output.ExplainError(cmd, err), cmd, true + } + if msg := err.Error(); unknownFlagRE.MatchString(msg) || needsValueRE.MatchString(msg) || badArgumentRE.MatchString(msg) { + parseFlagsAfterError(cmd) // as renderError does + } + return explainCLIError(cmd, err), cmd, true +} + +// derivedFlags are the flags of cmd that vf set from others typed, such as +// --schema from --csv: a line that gives the others gives them too. +func derivedFlags(cmd *cobra.Command) []string { + var names []string + if cmd != nil { + cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + if f.Changed && !typed(cmd, f) { + names = append(names, f.Name) + } + }) + } + return names +} + +// mistakesFor are the usual mistakes with c: a required flag left out, a +// stray word, an ID given as a word, a message unquoted, a misspelt command +// or group, a misspelt flag, and, for a get, an ID the API doesn't know. +func mistakesFor(c *cobra.Command, csv, server string) []mistake { + path := strings.Fields(c.CommandPath())[1:] + global := []string{"--no-interactive", "--agent-mode=false", "--server-url", server} + required, stand := requiredFlags(c, csv) + all := slices.Concat(stand, required) + names := func(fs []flagArg) []string { + var out []string + for _, f := range fs { + out = append(out, f.name) + } + return out + } + line := func(words ...[]string) []string { return slices.Concat(words...) } + + without := func(name string) []flagArg { + return slices.DeleteFunc(slices.Clone(all), func(f flagArg) bool { return f.name == name }) + } + + var ms []mistake + // Give what stands in for a flag (--text), or else the first required + // flag, and leave out the rest. + given := stand + if len(given) == 0 && len(required) > 0 { + given = required[:1] + } + if len(all) > len(given) { + ms = append(ms, mistake{"missing flags", line(path, args(given), global, []string{"--dry-run"}), names(given), true}) + } + ms = append(ms, mistake{"stray words", line(path, args(all), []string{"hello", "there"}, global), names(all), true}) + if id := missingIDFlag(c); id != "" && c.Flags().Lookup("text") == nil { + if rest := without(id); len(rest) < len(all) { + ms = append(ms, mistake{"an ID as a word", line(path, args(rest), []string{"x9"}, global), names(rest), true}) + } + } + if c.Flags().Lookup("text") != nil { + rest := without("text") + ms = append(ms, mistake{"an unquoted message", line(path, args(rest), []string{"--text", "Hello", "there"}, global), append(names(rest), "text"), true}) + } + ms = append(ms, mistake{"a misspelt command", line(path[:len(path)-1], []string{misspell(c.Parent(), path[len(path)-1])}, args(all), global), names(all), true}) + if len(path) > 1 { + ms = append(ms, mistake{"a misspelt group", line([]string{misspell(c.Root(), path[0])}, path[1:], args(all), global), names(all), true}) + } + if len(all) > 0 && len(all[0].name) > 3 { + wrong := args(all) + wrong[0] = "--" + misspell(nil, all[0].name) + ms = append(ms, mistake{"a misspelt flag", line(path, wrong, global), names(all[1:]), true}) + } + if c.Name() == "get" && len(all) > 0 { + ms = append(ms, mistake{"an unknown ID", line(path, args(all), global), names(all), false}) + } + return ms +} + +// flagArg is a flag given a value that it takes. +type flagArg struct{ name, value string } + +func args(fs []flagArg) []string { + var out []string + for _, f := range fs { + if f.value == "" { + out = append(out, "--"+f.name) + } else { + out = append(out, "--"+f.name, f.value) + } + } + return out +} + +// requiredFlags are c's required flags in help's order, a union by a form, +// each with a value it takes, and apart from them the flags that stand in +// for one (--text for --action), in place of those. +func requiredFlags(c *cobra.Command, csv string) (required, stand []flagArg) { + var standing []string + c.LocalFlags().VisitAll(func(f *pflag.Flag) { + if others := f.Annotations[flagutil.StandsFor]; len(others) > 0 && !f.Hidden { + stand = append(stand, flagArg{f.Name, valueFor(f, csv)}) + standing = append(standing, f.Name) + } + }) + words := missingRequired(c, nil) // examplehelp.go + for i := 0; i < len(words); i++ { + name, ok := strings.CutPrefix(words[i], "--") + f := c.Flags().Lookup(name) + if !ok || f == nil { + continue + } + if f.Value.Type() != "bool" { + i++ // its placeholder + } + if !flagutil.StoodInFor(c, standing, name) { + required = append(required, flagArg{name, valueFor(f, csv)}) + } + } + return required, stand +} + +// valueFor is a value f takes: its first choice, the JSON its help gives, +// a number, the CSV file for --csv, or an ID. A true/false flag takes none. +func valueFor(f *pflag.Flag, csv string) string { + t := f.Value.Type() + switch json := f.Annotations[flagutil.TakesJSON]; { + case t == "bool": + return "" + case len(cmdcheck.Choices(f)) > 0: + return cmdcheck.Choices(f)[0] + case len(json) > 0 && json[0] != "": + return json[0] + case strings.HasPrefix(t, "int"), strings.HasPrefix(t, "float"): + return "1" + case strings.Contains(f.Usage, "takes a day ("), strings.HasSuffix(f.Name, "-date"): + return "2026-06-01" + case f.Name == "csv", strings.HasPrefix(f.Usage, "Path to file"): + return csv + } + return "x1" +} + +// misspell swaps two letters of word, as a quick typist does, into a word +// that names nothing under parent: get becomes gte. +func misspell(parent *cobra.Command, word string) string { + for i := len(word) - 2; i >= 1; i-- { + b := []byte(word) + b[i], b[i+1] = b[i+1], b[i] + if typo := string(b); typo != word && (parent == nil || !hasChild(parent, typo)) { + return typo + } + } + return word + "x" +} + +func hasChild(parent *cobra.Command, word string) bool { + for _, c := range parent.Commands() { + if c.Name() == word || slices.Contains(c.Aliases, word) { + return true + } + } + return false +} diff --git a/internal/cmdcheck/cmdcheck.go b/internal/cmdcheck/cmdcheck.go new file mode 100644 index 00000000..c061f175 --- /dev/null +++ b/internal/cmdcheck/cmdcheck.go @@ -0,0 +1,312 @@ +// This file is not generated by Speakeasy. It checks that a command vf +// suggests would run as written, for the tests that collect them. +// +// vf's hints and Next lines hand people and agents whole commands to run: +// "Pass them: `vf conversation send …`", "Did you mean `vf transcript +// search …`?", "Next: vf tool get --tool-id …". Agents run them word for +// word. The usability sweep found them failing as written, one at a time: +// a --action vf refused beside --text, a dropped -p, a tool get without its +// required --type. Check reads a line as the command tree would and says +// what would stop it, so a test can hold every suggestion to that. +// +// Nothing in vf itself uses this package; only tests import it. + +package cmdcheck + +import ( + "fmt" + "maps" + "regexp" + "slices" + "strconv" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/voiceflow/cli/internal/flagutil" +) + +// Commands are the vf commands in text, in `backticks` as hints write them. +func Commands(text string) []string { + var found []string + for _, m := range codeSpan.FindAllStringSubmatch(text, -1) { + if m[1] == "vf" || strings.HasPrefix(m[1], "vf ") { + found = append(found, m[1]) + } + } + return found +} + +var codeSpan = regexp.MustCompile("`([^`]+)`") + +// Options say what else a line must do besides parse. +type Options struct { + // Keep are the flags typed on the line the suggestion answers, by + // name, which it must give again. + Keep []string + // Complete is whether the line must give every flag its command + // requires, with a value or a . + Complete bool + // Derived are the flags vf sets itself from others the line gives, + // such as --schema from --csv. They count as given. + Derived []string +} + +// Check is what would stop line from running as written against root's +// commands: words a shell can't split, a command or flag that doesn't +// exist, a group, which only prints its help, a value a flag doesn't take, +// two flags vf refuses together, a stray word, a flag typed that it drops, +// and, with Complete, a required flag it leaves out. A placeholder, +// or , counts as a value of any type. +func Check(root *cobra.Command, line string, o Options) []string { + words, err := Words(line) + if err != nil { + return []string{err.Error()} + } + if len(words) == 0 || words[0] != "vf" { + return []string{"doesn't start with vf"} + } + cmd, rest, err := root.Find(words[1:]) + if err != nil || cmd == nil { + return []string{fmt.Sprintf("names no command: %v", err)} + } + flags := copyFlags(cmd) + if err := flags.Parse(rest); err != nil { + return []string{err.Error()} + } + if args := flags.Args(); len(args) > 0 && (cmd.Args == nil || cmd.ValidateArgs(args) != nil) { + return []string{fmt.Sprintf("%s doesn't take the words %q", cmd.CommandPath(), args)} + } + if cmd.HasSubCommands() && cmd.Args == nil && flags.Lookup("help").Value.String() == "" { + return []string{"names the group " + cmd.CommandPath() + ", which runs nothing but its help"} + } + + var problems []string + set := map[string]bool{} + flags.Visit(func(f *pflag.Flag) { + set[f.Name] = true + for _, v := range f.Value.(*noted).values { + if problem := badValue(f, v); problem != "" { + problems = append(problems, problem) + } + } + }) + problems = append(problems, refusedTogether(cmd, set)...) + given := maps.Clone(set) + for _, name := range o.Keep { + if !set[name] { + problems = append(problems, "drops --"+name+", which was typed") + } + } + if o.Complete { + for _, name := range o.Derived { + given[name] = true + } + problems = append(problems, leftOut(cmd, given)...) + } + return problems +} + +// badValue is why f can't take v, or "". +func badValue(f *pflag.Flag, v string) string { + if strings.HasPrefix(v, "<") && strings.HasSuffix(v, ">") { + return "" + } + var err error + switch t := f.Value.(*noted).typ; { + case t == "bool": + _, err = strconv.ParseBool(v) + case strings.HasPrefix(t, "int"): + _, err = strconv.ParseInt(v, 10, 64) + case strings.HasPrefix(t, "float"): + _, err = strconv.ParseFloat(v, 64) + } + if err != nil { + return fmt.Sprintf("--%s takes a %s, not %q", f.Name, f.Value.Type(), v) + } + if choices := Choices(f); len(choices) > 0 && !slices.Contains(choices, v) { + return fmt.Sprintf("--%s takes one of %s, not %q", f.Name, strings.Join(choices, ", "), v) + } + return "" +} + +var optionsRE = regexp.MustCompile(`(?:^|\()options: ([^()\[\]]+?)\s*(?:\)|\[|$)`) + +// Choices are the values f takes when its help lists them, or nil. +func Choices(f *pflag.Flag) []string { + if m := optionsRE.FindStringSubmatch(f.Usage); m != nil { + return strings.Split(m[1], ", ") + } + return nil +} + +// refusedTogether names the pairs of flags in set that vf refuses together: +// a flag and one it stands for (--text and --action, --csv and --items), +// two forms of one union, and cobra's mutually exclusive groups. +func refusedTogether(cmd *cobra.Command, set map[string]bool) []string { + var problems []string + forms := map[string]string{} + for _, name := range sorted(set) { + f := cmd.Flags().Lookup(name) + if f == nil { + continue + } + for _, other := range f.Annotations[flagutil.StandsFor] { + if set[other] { + problems = append(problems, "gives --"+name+" and --"+other+", which vf refuses together") + } + } + // --body-param.api.* and --body-param.function.* are two forms of + // --body-param. + if parts := strings.SplitN(name, ".", 3); len(parts) >= 2 && cmd.Flags().Lookup(parts[0]) != nil { + form := parts[0] + "." + parts[1] + if cmd.Flags().Lookup(form) == nil { + continue + } + if seen, ok := forms[parts[0]]; ok && seen != form { + problems = append(problems, "gives two forms of --"+parts[0]+": --"+seen+" and --"+form) + } + forms[parts[0]] = form + } + for _, group := range f.Annotations["cobra_annotation_mutually_exclusive"] { + for _, other := range strings.Split(group, " ") { + if other != name && set[other] && name < other { + problems = append(problems, "gives --"+name+" and --"+other+", which are mutually exclusive") + } + } + } + } + return problems +} + +// leftOut names the flags cmd requires that set doesn't give: a required +// flag no flag set stands in for, a union none of whose forms is set, and a +// field of a form given through its fields. +func leftOut(cmd *cobra.Command, set map[string]bool) []string { + var problems []string + given := sorted(set) + cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { + if f.Hidden || set[f.Name] || flagutil.StoodInFor(cmd, given, f.Name) { + return + } + if with := f.Annotations[flagutil.RequiredWithForm]; len(with) > 0 { + if formGiven(given, with[0]) { + problems = append(problems, "gives --"+with[0]+".* but leaves out --"+f.Name) + } + return + } + if required := f.Annotations["speakeasy:required"]; len(required) == 0 || required[0] != "true" { + return + } + if len(f.Annotations[flagutil.UnionNeedsAForm]) > 0 && formGiven(given, f.Name) { + return + } + problems = append(problems, "leaves out --"+f.Name+", which "+cmd.CommandPath()+" requires") + }) + return problems +} + +// formGiven reports whether given set the form or union base through a +// flag under it: --body-param.function.description. +func formGiven(given []string, base string) bool { + return slices.ContainsFunc(given, func(name string) bool { return strings.HasPrefix(name, base+".") }) +} + +func sorted(set map[string]bool) []string { + names := make([]string, 0, len(set)) + for name := range set { + names = append(names, name) + } + slices.Sort(names) + return names +} + +// copyFlags is a flag set with a flag for each of cmd's, its own, those it +// inherits and --help, that notes the values it is given. Parsing a line +// into it leaves cmd as it is. +func copyFlags(cmd *cobra.Command) *pflag.FlagSet { + flags := pflag.NewFlagSet(cmd.Name(), pflag.ContinueOnError) + flags.SetOutput(nowhere{}) + add := func(f *pflag.Flag) { + if flags.Lookup(f.Name) == nil && (f.Shorthand == "" || flags.ShorthandLookup(f.Shorthand) == nil) { + flags.AddFlag(&pflag.Flag{Name: f.Name, Shorthand: f.Shorthand, Usage: f.Usage, NoOptDefVal: f.NoOptDefVal, Value: ¬ed{typ: f.Value.Type()}}) + } + } + cmd.LocalFlags().VisitAll(add) + cmd.InheritedFlags().VisitAll(add) + if flags.Lookup("help") == nil { + flags.AddFlag(&pflag.Flag{Name: "help", Shorthand: "h", NoOptDefVal: "true", Value: ¬ed{typ: "bool"}}) + } + return flags +} + +// noted is a flag's values as given, whatever its type. +type noted struct { + typ string + values []string +} + +func (v *noted) Set(s string) error { v.values = append(v.values, s); return nil } +func (v *noted) Type() string { return v.typ } +func (v *noted) String() string { return strings.Join(v.values, ",") } + +type nowhere struct{} + +func (nowhere) Write(p []byte) (int, error) { return len(p), nil } + +// Words splits line as a POSIX shell would, for the quoting vf writes: +// 'single', "double" with backslash escapes, and a backslash outside quotes. +// A is one word, spaces and all: the reader fills it in. +func Words(line string) ([]string, error) { + 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 { + return nil, fmt.Errorf("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) && strings.IndexByte("\\\"$`", line[i+1]) >= 0 { + i++ + } + cur.WriteByte(line[i]) + } + if i >= len(line) { + return nil, fmt.Errorf("unclosed \" in %s", line) + } + inWord = true + case ch == '<' && !inWord && strings.IndexByte(line[i:], '>') > 0: + // A placeholder, or , is one word to fill in. + end := i + strings.IndexByte(line[i:], '>') + cur.WriteString(line[i : end+1]) + i = end + 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, nil +} diff --git a/internal/output/export_test.go b/internal/output/export_test.go new file mode 100644 index 00000000..933ed50f --- /dev/null +++ b/internal/output/export_test.go @@ -0,0 +1,16 @@ +// This file is not generated by Speakeasy. It lets nextrun_test.go, in +// package output_test so that it can build vf's command tree, read the Next +// lines a create prints. + +package output + +import "github.com/spf13/cobra" + +// NextCommands are the commands nextSteps offers once cmd has made id. +func NextCommands(cmd *cobra.Command, group, id string, obj map[string]interface{}) []string { + var lines []string + for _, tip := range nextSteps(cmd, group, id, obj) { + lines = append(lines, tip.Command) + } + return lines +} diff --git a/internal/output/nextrun_test.go b/internal/output/nextrun_test.go new file mode 100644 index 00000000..fe7f6b09 --- /dev/null +++ b/internal/output/nextrun_test.go @@ -0,0 +1,82 @@ +// This file is not generated by Speakeasy. It checks that every Next line a +// create prints runs as written, for every command that makes something. +// +// `vf tool create` offered "Next: vf tool get --tool-id …", and tool get +// refused it: it needs --type too. The line carried the ID and the scope, +// and nothing else get requires. This makes each create, clone and +// duplicate announce a new thing and holds each Next line to +// cmdcheck.Check: a command that exists, flags it takes, the scope typed, +// and every flag it requires. The hints after a mistake are checked in +// package cli (suggested_test.go). + +package output_test + +import ( + "strings" + "testing" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/cli" + "github.com/voiceflow/cli/internal/cmdcheck" + "github.com/voiceflow/cli/internal/output" +) + +// scope are the flags a create is given that say where the new thing is. +var scope = map[string]string{"workspace-id": "w1", "project-id": "p1", "environment-alias": "main"} + +func TestEveryNextLineRuns(t *testing.T) { + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("HOME", t.TempDir()) + root, err := cli.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) + } + switch c.Name() { + case "create", "clone", "duplicate": + default: + return + } + var typed []string + for name, value := range scope { + if c.Flags().Lookup(name) != nil { + if err := c.Flags().Set(name, value); err != nil { + t.Fatal(err) + } + typed = append(typed, name) + } + } + for _, line := range output.NextCommands(c, c.Parent().Name(), "x1", map[string]interface{}{"id": "x1"}) { + checked++ + for _, problem := range cmdcheck.Check(root, line, cmdcheck.Options{Keep: takes(root, line, typed), Complete: true}) { + t.Errorf("%s offers `%s`, which %s", c.CommandPath(), line, problem) + } + } + } + walk(root) + t.Logf("checked %d Next lines", checked) + if checked < 40 { + t.Errorf("checked only %d Next lines", checked) + } +} + +// takes are the flags of names that line's command takes. +func takes(root *cobra.Command, line string, names []string) []string { + target, _, err := root.Find(strings.Fields(line)[1:]) + if err != nil { + return nil + } + var out []string + for _, name := range names { + if target.Flags().Lookup(name) != nil { + out = append(out, name) + } + } + return out +}